diff options
author | Michael Lando <ml636r@att.com> | 2018-03-04 14:53:33 +0200 |
---|---|---|
committer | Michael Lando <ml636r@att.com> | 2018-03-07 13:19:05 +0000 |
commit | a5445100050e49e83f73424198d73cd72d672a4d (patch) | |
tree | cacf4df817df31be23e4e790d1dda857bdae061e /catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations | |
parent | 51157f92c21976cba4914c378aaa3cba49826931 (diff) |
Sync Integ to Master
Change-Id: I71e3acc26fa612127756ac04073a522b9cc6cd74
Issue-ID: SDC-977
Signed-off-by: Gitelman, Tal (tg851x) <tg851x@intl.att.com>
Diffstat (limited to 'catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations')
12 files changed, 2315 insertions, 1456 deletions
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 706007bdd7..cbd612d024 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 @@ -68,7 +68,7 @@ public class ArtifactsOperations extends BaseOperation { public Either<ArtifactDefinition, StorageOperationStatus> addArifactToComponent(ArtifactDefinition artifactInfo, String parentId, NodeTypeEnum type, boolean failIfExist, String instanceId) { String artifactId = artifactInfo.getUniqueId(); - if (artifactId == null && artifactInfo.getEsId()!=null) { + if (artifactId == null && artifactInfo.getEsId() != null) { artifactId = artifactInfo.getEsId(); } Either<ArtifactDataDefinition, StorageOperationStatus> status = updateArtifactOnGraph(parentId, artifactInfo, type, artifactId, instanceId, false, false); @@ -186,8 +186,7 @@ public class ArtifactsOperations extends BaseOperation { } /** - * - * @param parentId the id of the instance container + * @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 */ @@ -267,27 +266,27 @@ public class ArtifactsOperations extends BaseOperation { if (isUpdate) { ArtifactTypeEnum type = ArtifactTypeEnum.findType(artifactData.getArtifactType()); switch (type) { - case HEAT_ENV: - if (edgeLabel == EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS) { - generateUUID(artifactData, oldVesrion); - } else { - updateVersionAndDate(artifactData, oldVesrion); - } - break; - case HEAT: - case HEAT_NET: - case HEAT_VOL: - generateUUID(artifactData, oldVesrion); - break; - default: - if (oldChecksum == null || oldChecksum.isEmpty()) { - if (currentChecksum != null) { + case HEAT_ENV: + if (edgeLabel == EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS) { generateUUID(artifactData, oldVesrion); + } else { + updateVersionAndDate(artifactData, oldVesrion); } - } else if ((currentChecksum != null && !currentChecksum.isEmpty()) && !oldChecksum.equals(currentChecksum)) { + break; + case HEAT: + case HEAT_NET: + case HEAT_VOL: generateUUID(artifactData, oldVesrion); - } - break; + break; + default: + if (oldChecksum == null || oldChecksum.isEmpty()) { + if (currentChecksum != null) { + generateUUID(artifactData, oldVesrion); + } + } else if ((currentChecksum != null && !currentChecksum.isEmpty()) && !oldChecksum.equals(currentChecksum)) { + generateUUID(artifactData, oldVesrion); + } + break; } } else { if (oldChecksum == null || oldChecksum.isEmpty()) { @@ -315,11 +314,11 @@ public class ArtifactsOperations extends BaseOperation { String id = heatEnv.getGeneratedFromId(); ComponentTypeEnum compType; switch (parentType) { - case ResourceInstance: - compType = ComponentTypeEnum.RESOURCE_INSTANCE; - break; - default: - compType = componentType; + case ResourceInstance: + compType = ComponentTypeEnum.RESOURCE_INSTANCE; + break; + default: + compType = componentType; } return getArtifactById(parentId, id, compType, containerId); } @@ -430,7 +429,7 @@ public class ArtifactsOperations extends BaseOperation { return artMap; } - private Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> getInstanceArtifactsByLabel(String parentId, String instanceId, EdgeLabelEnum edgeLabelEnum) { + 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()); @@ -449,34 +448,34 @@ public class ArtifactsOperations extends BaseOperation { * if (nodeType == NodeTypeEnum.ResourceInstance) { edgeLabelEnum = EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS; vertexTypeEnum = VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS; isDeepElement = true; } else { */ switch (groupType) { - case TOSCA: - edgeLabelEnum = EdgeLabelEnum.TOSCA_ARTIFACTS; - vertexTypeEnum = VertexTypeEnum.TOSCA_ARTIFACTS; - break; - case DEPLOYMENT: - if (nodeType == NodeTypeEnum.ResourceInstance) { - edgeLabelEnum = EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS; - vertexTypeEnum = VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS; - isDeepElement = true; - } else { - edgeLabelEnum = EdgeLabelEnum.DEPLOYMENT_ARTIFACTS; - vertexTypeEnum = VertexTypeEnum.DEPLOYMENT_ARTIFACTS; - } - break; - case SERVICE_API: - edgeLabelEnum = EdgeLabelEnum.SERVICE_API_ARTIFACTS; - vertexTypeEnum = VertexTypeEnum.SERVICE_API_ARTIFACTS; - break; - default: - if (nodeType == NodeTypeEnum.ResourceInstance) { - edgeLabelEnum = EdgeLabelEnum.INSTANCE_ARTIFACTS; - vertexTypeEnum = VertexTypeEnum.INSTANCE_ARTIFACTS; - isDeepElement = true; - } else { - edgeLabelEnum = EdgeLabelEnum.ARTIFACTS; - vertexTypeEnum = VertexTypeEnum.ARTIFACTS; - } - break; + case TOSCA: + edgeLabelEnum = EdgeLabelEnum.TOSCA_ARTIFACTS; + vertexTypeEnum = VertexTypeEnum.TOSCA_ARTIFACTS; + break; + case DEPLOYMENT: + if (nodeType == NodeTypeEnum.ResourceInstance) { + edgeLabelEnum = EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS; + vertexTypeEnum = VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS; + isDeepElement = true; + } else { + edgeLabelEnum = EdgeLabelEnum.DEPLOYMENT_ARTIFACTS; + vertexTypeEnum = VertexTypeEnum.DEPLOYMENT_ARTIFACTS; + } + break; + case SERVICE_API: + edgeLabelEnum = EdgeLabelEnum.SERVICE_API_ARTIFACTS; + vertexTypeEnum = VertexTypeEnum.SERVICE_API_ARTIFACTS; + break; + default: + if (nodeType == NodeTypeEnum.ResourceInstance) { + edgeLabelEnum = EdgeLabelEnum.INSTANCE_ARTIFACTS; + vertexTypeEnum = VertexTypeEnum.INSTANCE_ARTIFACTS; + isDeepElement = true; + } else { + edgeLabelEnum = EdgeLabelEnum.ARTIFACTS; + vertexTypeEnum = VertexTypeEnum.ARTIFACTS; + } + break; } // } return new ImmutableTriple<EdgeLabelEnum, Boolean, VertexTypeEnum>(edgeLabelEnum, isDeepElement, vertexTypeEnum); @@ -505,10 +504,10 @@ public class ArtifactsOperations extends BaseOperation { if (edgeLabelEnum != EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS && edgeLabelEnum != EdgeLabelEnum.INSTANCE_ARTIFACTS) { uniqueId = UniqueIdBuilder.buildPropertyUniqueId(componentId, artifactToUpdate.getArtifactLabel()); } else { - uniqueId = UniqueIdBuilder.buildPropertyUniqueId(instanceId, artifactToUpdate.getArtifactLabel()); + uniqueId = UniqueIdBuilder.buildInstanceArtifactUniqueId(componentId, instanceId, artifactToUpdate.getArtifactLabel()); } artifactToUpdate.setUniqueId(uniqueId); - if(!isDeletePlaceholder) + if (!isDeletePlaceholder) artifactToUpdate.setEsId(uniqueId); } else artifactToUpdate.setUniqueId(artifactId); @@ -547,15 +546,19 @@ public class ArtifactsOperations extends BaseOperation { oldVersion = oldArtifactData.getArtifactVersion(); //duplicated flag didn't receive from UI, take from DB artifactToUpdate.setDuplicated(oldArtifactData.getDuplicated()); - + if (isNeedToClone) artifactToUpdate.setDuplicated(Boolean.FALSE); else { if (artifactToUpdate.getDuplicated()) { - String id = type != NodeTypeEnum.ResourceInstance ? componentId : instanceId; - String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(id, artifactToUpdate.getArtifactLabel()); + String uniqueId = ""; + if(type != NodeTypeEnum.ResourceInstance) + uniqueId = UniqueIdBuilder.buildPropertyUniqueId(componentId, artifactToUpdate.getArtifactLabel()); + else + uniqueId = UniqueIdBuilder.buildInstanceArtifactUniqueId(componentId, instanceId, artifactToUpdate.getArtifactLabel()); + artifactToUpdate.setUniqueId(uniqueId); - if(!isDeletePlaceholder) + if (!isDeletePlaceholder) artifactToUpdate.setEsId(uniqueId); artifactToUpdate.setDuplicated(Boolean.FALSE); } @@ -594,12 +597,12 @@ public class ArtifactsOperations extends BaseOperation { artifacts.put(artifactToUpdate.getArtifactLabel(), artifactToUpdate); } - for ( Entry<String, MapArtifactDataDefinition> e : artifactInst.entrySet() ) { + for (Entry<String, MapArtifactDataDefinition> e : artifactInst.entrySet()) { List<ArtifactDataDefinition> toscaDataListPerInst = e.getValue().getMapToscaDataDefinition().values().stream().collect(Collectors.toList()); List<String> pathKeysPerInst = new ArrayList<>(); pathKeysPerInst.add(e.getKey()); status = updateToscaDataDeepElementsOfToscaElement(componentId, edgeLabelEnum, vertexTypeEnum, toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.ARTIFACT_LABEL); - if ( status != StorageOperationStatus.OK) { + if (status != StorageOperationStatus.OK) { log.debug("Failed to update atifacts group for instance {} in component {} edge type {} error {}", instanceId, componentId, edgeLabelEnum, status); res = Either.right(status); break; @@ -637,14 +640,14 @@ public class ArtifactsOperations extends BaseOperation { private boolean validateParentType(NodeTypeEnum type) { boolean isValid = false; switch (type) { - case Resource: - case InterfaceOperation: - case Service: - case ResourceInstance: - isValid = true; - break; - default: - log.debug("Not supported node type for artifact relation : {} ", type); + case Resource: + case InterfaceOperation: + case Service: + case ResourceInstance: + isValid = true; + break; + default: + log.debug("Not supported node type for artifact relation : {} ", type); } return isValid; } @@ -727,4 +730,5 @@ public class ArtifactsOperations extends BaseOperation { } return result; } + } 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 537198d395..3b64a6b208 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 @@ -21,6 +21,7 @@ package org.openecomp.sdc.be.model.jsontitan.operations; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; @@ -54,6 +55,8 @@ 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.tosca.ToscaDataDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.PolicyDefinition; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; @@ -549,6 +552,27 @@ public abstract class BaseOperation { return statusRes; } + StorageOperationStatus overrideToscaDataOfToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, Map<String, ? extends ToscaDataDefinition> toscaData) { + return titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse) + .left() + .bind(graphVertex -> overrideToscaElementData(graphVertex, toscaData, edgeLabel)) + .either(graphVertex -> StorageOperationStatus.OK, + DaoStatusConverter::convertTitanStatusToStorageStatus); + } + + private Either<GraphVertex, TitanOperationStatus> overrideToscaElementData(GraphVertex toscaElement, Map<String, ? extends ToscaDataDefinition> toscaData, EdgeLabelEnum edgeLabelEnum) { + return titanDao.getChildVertex(toscaElement, edgeLabelEnum, JsonParseFlagEnum.ParseJson) + .left() + .bind(dataVertex -> overrideToscaElementData(dataVertex, toscaElement, toscaData, edgeLabelEnum)) + .right() + .map(err -> logAndReturn(err, "failed to override tosca data for element {} of type {}. status: {}", toscaElement.getUniqueId(), edgeLabelEnum, err)); + } + + private Either<GraphVertex, TitanOperationStatus> overrideToscaElementData(GraphVertex dataElement, GraphVertex toscaElement, Map<String, ? extends ToscaDataDefinition> toscaData, EdgeLabelEnum edgeLabelEnum) { + dataElement.setJson(toscaData); + return updateOrCopyOnUpdate(dataElement, toscaElement, edgeLabelEnum); + } + /** * Adds list of tosca data deep elements to tosca element with specified uid according received labels * @@ -693,6 +717,36 @@ public abstract class BaseOperation { } /** + * + * @param toscaElementId the id of the tosca element data container + * @param edgeLabel the edge label of the data type to update + * @param toscaDataMap the data to update + * @param key the key in the json object where the map object block resides + * @return the status of the update operation + */ + public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataDeepElementsBlockToToscaElement(String toscaElementId, EdgeLabelEnum edgeLabel, MapDataDefinition<T> toscaDataMap, String key) { + return titanDao.getVertexById(toscaElementId, JsonParseFlagEnum.NoParse) + .either(toscaElement -> updateToscaDataDeepElementsBlockToToscaElement(toscaElement, edgeLabel, toscaDataMap, key), + DaoStatusConverter::convertTitanStatusToStorageStatus); + } + + private <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataDeepElementsBlockToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, MapDataDefinition<T> toscaDataMap, String key) { + return titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson) + .left() + .bind(dataVertex -> updateToscaDataDeepElementsBlockToToscaElement(toscaElement, dataVertex, edgeLabel, toscaDataMap, key)) + .either(updatedVertex -> StorageOperationStatus.OK, + DaoStatusConverter::convertTitanStatusToStorageStatus); + } + + private <T extends ToscaDataDefinition> Either<GraphVertex, TitanOperationStatus> updateToscaDataDeepElementsBlockToToscaElement(GraphVertex toscaElement, GraphVertex dataElement, EdgeLabelEnum edgeLabel, MapDataDefinition<T> toscaDataMap, String key) { + Map<String, T> mapToscaDataDefinition = toscaDataMap.getMapToscaDataDefinition(); + updateDeepElements(dataElement, mapToscaDataDefinition, Collections.singletonList(key)); + return updateOrCopyOnUpdate(dataElement, toscaElement, edgeLabel) + .right() + .map(err -> logAndReturn(err, "failed while trying to update data vertex from tosca element {}, of type {} . status {}", toscaElement.getUniqueId(), edgeLabel, err)); + } + + /** * Updates tosca data element of tosca element by specified uid according received labels * * @param toscaElementUid @@ -833,7 +887,7 @@ public abstract class BaseOperation { existingToscaDataMap = (Map<String, T>) toscaDataVertex.getJson(); } - validateRes = validateMergeToscaData(toscaElement, toscaDataList, mapKeyField, existingToscaDataMap, isUpdate); + validateRes = validateMergeToscaData(toscaElement, toscaDataList, mapKeyField, existingToscaDataMap, isUpdate); if (validateRes.isRight()) { result = validateRes.right().value(); CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed validate tosca data upon adding to tosca element {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel, result); @@ -1389,7 +1443,7 @@ public abstract class BaseOperation { protected String buildGroupInstanceName(String instanceName, String groupName) { return ValidationUtils.normalizeComponentInstanceName(instanceName) + ".." + groupName; } - + protected String generateCustomizationUUID() { return UUID.randomUUID().toString(); } @@ -1398,4 +1452,9 @@ public abstract class BaseOperation { properties.forEach(p -> p.convertPropertyDataToInstancePropertyData()); } + private TitanOperationStatus logAndReturn(TitanOperationStatus titanOperationStatus, String logMsg, Object ... logParams) { + logger.debug(logMsg, logParams); + return titanOperationStatus; + } + } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ExternalReferencesOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ExternalReferencesOperation.java new file mode 100644 index 0000000000..76fb0a9151 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ExternalReferencesOperation.java @@ -0,0 +1,261 @@ +package org.openecomp.sdc.be.model.jsontitan.operations; + +import fj.data.Either; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.elements.MapComponentInstanceExternalRefs; +import org.openecomp.sdc.be.model.jsontitan.utils.IdMapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.*; + +/** + * Created by yavivi on 26/01/2018. + */ +@Component +public class ExternalReferencesOperation extends BaseOperation { + + private static final Logger log = LoggerFactory.getLogger(ExternalReferencesOperation.class); + + public IdMapper getIdMapper() { + return idMapper; + } + + public void setIdMapper(IdMapper idMapper) { + this.idMapper = idMapper; + } + + @Autowired + protected IdMapper idMapper; + + /** + * Constructor + */ + public ExternalReferencesOperation(TitanDao titanDao, NodeTypeOperation nto, TopologyTemplateOperation tto, IdMapper idMapper){ + this.titanDao = titanDao; + this.topologyTemplateOperation = tto; + this.nodeTypeOperation = nto; + this.idMapper = idMapper; + } + + public Either<String, ActionStatus> addExternalReferenceWithCommit(String serviceUuid, String componentInstanceName, String objectType, String reference) { + Either<String, ActionStatus> addResult = this.addExternalReference(serviceUuid, componentInstanceName, objectType, reference); + this.titanDao.commit(); + return addResult; + } + + public Either<String, ActionStatus> deleteExternalReferenceWithCommit(String serviceUuid, String componentInstanceName, String objectType, String reference) { + Either<String, ActionStatus> result = this.deleteExternalReference(serviceUuid, componentInstanceName, objectType, reference); + this.titanDao.commit(); + return result; + } + + public Either<String, ActionStatus> updateExternalReferenceWithCommit(String serviceVertexUuid, String componentInstanceName, String objectType, String oldRef, String newRef) { + Either<String, ActionStatus> updateResult = this.updateExternalReference(serviceVertexUuid, componentInstanceName, objectType, oldRef, newRef); + this.titanDao.commit(); + return updateResult; + } + + public Either<String, ActionStatus> addExternalReference(String assetUuid, String componentInstanceName, String objectType, String reference) { + + //Get Service vertex + Either<GraphVertex, TitanOperationStatus> vertexById = this.titanDao.getVertexById(assetUuid); + if (vertexById.isRight()){ + return Either.right(ActionStatus.RESOURCE_NOT_FOUND); + } + + GraphVertex serviceVertex = vertexById.left().value(); + + final String compInstanceUniqueId = idMapper.mapComponentNameToUniqueId(componentInstanceName, serviceVertex); + if (compInstanceUniqueId == null) { + return Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND); + } + + //Get the external references map vertex + final Either<GraphVertex, TitanOperationStatus> dataVertexResult = this.getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS); + + //Check whether data vertex found + GraphVertex externalRefsVertex = dataVertexResult.isLeft() ? dataVertexResult.left().value() : null; + + //instanceId -> externalRefsMap + Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData = null; + if (externalRefsVertex == null) { + //External Refs vertext does not exist, create its map. + externalReferencesFullData = new HashMap<String, MapComponentInstanceExternalRefs>() { + { + MapComponentInstanceExternalRefs externalRefsMap = new MapComponentInstanceExternalRefs(); + put(compInstanceUniqueId, externalRefsMap); + } + }; + } else { + externalReferencesFullData = (Map<String, MapComponentInstanceExternalRefs>) externalRefsVertex.getJson(); + if (externalReferencesFullData.get(compInstanceUniqueId) == null){ + externalReferencesFullData.put(compInstanceUniqueId, new MapComponentInstanceExternalRefs()); + } + } + + boolean isAdded = this.addExternalRef(externalReferencesFullData, compInstanceUniqueId, objectType, reference); + this.updateFullToscaData(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS, VertexTypeEnum.EXTERNAL_REF, externalReferencesFullData); + + return isAdded ? Either.left(reference) : Either.right(ActionStatus.EXT_REF_ALREADY_EXIST); + } + + public Either<String, ActionStatus> deleteExternalReference(String assetUuid, String componentInstanceName, String objectType, String reference){ + //Get Service vertex + Either<GraphVertex, TitanOperationStatus> vertexById = this.titanDao.getVertexById(assetUuid); + if (vertexById.isRight()){ + return Either.right(ActionStatus.RESOURCE_NOT_FOUND); + } + GraphVertex serviceVertex = vertexById.left().value(); + + final String compInstanceUniqueId = idMapper.mapComponentNameToUniqueId(componentInstanceName, serviceVertex); + if (compInstanceUniqueId == null) { + return Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND); + } + + //Get the external references map vertex + final Either<GraphVertex, TitanOperationStatus> dataVertexResult = this.getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS); + + //Check whether data vertex found + GraphVertex externalRefsVertex = dataVertexResult.isLeft() ? dataVertexResult.left().value() : null; + boolean refDeleted = false; + if (externalRefsVertex != null) { + Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData = (Map<String, MapComponentInstanceExternalRefs>) externalRefsVertex.getJson(); + if (externalReferencesFullData != null) { + refDeleted = this.deleteExternalRef(externalReferencesFullData, compInstanceUniqueId, objectType, reference); + this.updateFullToscaData(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS, VertexTypeEnum.EXTERNAL_REF, externalReferencesFullData); //@ TODO if ref deleted + } + } + + if (refDeleted) { + return Either.left(reference); + } else { + return Either.right(ActionStatus.EXT_REF_NOT_FOUND); + } + } + + public Either<String, ActionStatus> updateExternalReference(String assetUuid, String componentInstanceName, String objectType, String oldRef, String newRef) { + //Get Service vertex + Either<GraphVertex, TitanOperationStatus> vertexById = this.titanDao.getVertexById(assetUuid); + if (vertexById.isRight()){ + return Either.right(ActionStatus.RESOURCE_NOT_FOUND); + } + + GraphVertex serviceVertex = vertexById.left().value(); + + //Map instance_name -> uuid + final String compInstanceUniqueId = idMapper.mapComponentNameToUniqueId(componentInstanceName, serviceVertex); + if (compInstanceUniqueId == null) { + return Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND); + } + + //Get the external references map vertex + final Either<GraphVertex, TitanOperationStatus> dataVertexResult = this.getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS); + + //Check whether data vertex found + GraphVertex externalRefsVertex = dataVertexResult.isLeft() ? dataVertexResult.left().value() : null; + boolean refReplaced = false; + if (externalRefsVertex != null) { + Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData = (Map<String, MapComponentInstanceExternalRefs>) externalRefsVertex.getJson(); + if (externalReferencesFullData != null) { + refReplaced = this.updateExternalRef(externalReferencesFullData, compInstanceUniqueId, objectType, oldRef, newRef); + this.updateFullToscaData(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS, VertexTypeEnum.EXTERNAL_REF, externalReferencesFullData); + } + } + if (refReplaced) { + return Either.left(newRef); + } else { + return Either.right(ActionStatus.EXT_REF_NOT_FOUND); + } + } + + public Either<Map<String, List<String>>, ActionStatus> getExternalReferences(String assetUuid, String objectType) { + //Get Service vertex + Either<GraphVertex, TitanOperationStatus> vertexById = this.titanDao.getVertexById(assetUuid); + if (vertexById.isRight()){ + return Either.right(ActionStatus.RESOURCE_NOT_FOUND); + } + + GraphVertex serviceVertex = vertexById.left().value(); + + Map<String, List<String>> result = new HashMap(); + + //Get the external references map vertex + final Either<GraphVertex, TitanOperationStatus> dataVertexResult = this.getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS); + //Check whether data vertex found + GraphVertex externalRefsVertex = dataVertexResult.isLeft() ? dataVertexResult.left().value() : null; + if (externalRefsVertex != null) { + Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData = (Map<String, MapComponentInstanceExternalRefs>) externalRefsVertex.getJson(); + if (externalReferencesFullData != null) { + externalReferencesFullData.entrySet().forEach( + s -> { + List<String> externalRefsByObjectType = externalReferencesFullData.get(s.getKey()).getExternalRefsByObjectType(objectType); + List<String> refList = externalRefsByObjectType == null ? new ArrayList<>() : externalRefsByObjectType; + String key = idMapper.mapUniqueIdToComponentNameTo(s.getKey(), serviceVertex); + result.put(key, refList); + } + ); + return Either.left(result); + } + } + //No external References Node found on this asset + return Either.left(new HashMap<>()); + } + + public Either<List<String>, ActionStatus> getExternalReferences(String assetUuid, String componentInstanceName, String objectType) { + //Get Service vertex + Either<GraphVertex, TitanOperationStatus> vertexById = this.titanDao.getVertexById(assetUuid); + if (vertexById.isRight()){ + return Either.right(ActionStatus.RESOURCE_NOT_FOUND); + } + + GraphVertex serviceVertex = vertexById.left().value(); + final String compInstanceUniqueId = idMapper.mapComponentNameToUniqueId(componentInstanceName, serviceVertex); + if (compInstanceUniqueId == null) { + return Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND); + } + + //Get the external references map vertex + final Either<GraphVertex, TitanOperationStatus> dataVertexResult = this.getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS); + + //Check whether data vertex found + GraphVertex externalRefsVertex = dataVertexResult.isLeft() ? dataVertexResult.left().value() : null; + if (externalRefsVertex != null) { + Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData = (Map<String, MapComponentInstanceExternalRefs>) externalRefsVertex.getJson(); + if (externalReferencesFullData != null) { + return Either.left(this.getExternalReferencesByObjectId(externalReferencesFullData, compInstanceUniqueId, objectType)); + } + } + + //No external References Node found on this asset + return Either.left(new LinkedList()); + } + + private List<String> getExternalReferencesByObjectId(Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData, String componentInstanceId, String objectType) { + MapComponentInstanceExternalRefs externalRefsMap = externalReferencesFullData.get(componentInstanceId); + List<String> externalRefsByObjectType = externalRefsMap.getExternalRefsByObjectType(objectType); + return externalRefsByObjectType != null ? externalRefsByObjectType : new LinkedList<String>(); + } + + private boolean updateExternalRef(Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData, String componentInstanceId, String objectType, String oldRef, String newRef) { + MapComponentInstanceExternalRefs externalRefsMap = externalReferencesFullData.get(componentInstanceId); + return externalRefsMap.replaceExternalRef(objectType, oldRef, newRef); + } + + private boolean deleteExternalRef(Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData, String componentInstanceId, String objectType, String reference) { + MapComponentInstanceExternalRefs externalRefsMap = externalReferencesFullData.get(componentInstanceId); + return externalRefsMap.deleteExternalRef(objectType, reference); + } + + private boolean addExternalRef(Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData, String componentInstanceId, String objectType, String reference) { + MapComponentInstanceExternalRefs externalRefsMap = externalReferencesFullData.get(componentInstanceId); + return externalRefsMap.addExternalRef(objectType, reference); + } +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ForwardingPathOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ForwardingPathOperation.java new file mode 100644 index 0000000000..ad4c1fb4f3 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ForwardingPathOperation.java @@ -0,0 +1,122 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.jsontitan.operations; + +import fj.data.Either; +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.JsonParseFlagEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; +import org.openecomp.sdc.common.jsongraph.util.CommonUtility; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Set; +import java.util.UUID; + +@org.springframework.stereotype.Component("forwarding-paths-operations") +public class ForwardingPathOperation extends BaseOperation { + private static Logger logger = LoggerFactory.getLogger(ForwardingPathOperation.class.getName()); + + + public Either<Set<String>, StorageOperationStatus> deleteForwardingPath(Service service, Set<String> forwardingPathsToDelete) { + Either<Set<String>, StorageOperationStatus> result = null; + Either<GraphVertex, TitanOperationStatus> getComponentVertex; + StorageOperationStatus status = null; + + if (result == null) { + getComponentVertex = titanDao.getVertexById(service.getUniqueId(), JsonParseFlagEnum.NoParse); + if (getComponentVertex.isRight()) { + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentVertex.right().value())); + } + } + if (result == null) { + + status = deleteToscaDataElements(service.getUniqueId(), EdgeLabelEnum.FORWARDING_PATH,new ArrayList<>(forwardingPathsToDelete)); + + if (status != StorageOperationStatus.OK) { + result = Either.right(status); + } + } + + if (result == null) { + result = Either.left(forwardingPathsToDelete); + } + return result; + } + + public Either<ForwardingPathDataDefinition, StorageOperationStatus> addForwardingPath(String serviceId, ForwardingPathDataDefinition currentPath) { + return addOrUpdateForwardingPath(false, serviceId, currentPath); + } + + public Either<ForwardingPathDataDefinition, StorageOperationStatus> updateForwardingPath(String serviceId, ForwardingPathDataDefinition currentPath) { + return addOrUpdateForwardingPath(true, serviceId, currentPath); + } + + private Either<ForwardingPathDataDefinition, StorageOperationStatus> addOrUpdateForwardingPath(boolean isUpdateAction, String serviceId, ForwardingPathDataDefinition currentPath) { + + StorageOperationStatus statusRes; + Either<GraphVertex, TitanOperationStatus> getToscaElementRes; + + getToscaElementRes = titanDao.getVertexById(serviceId, JsonParseFlagEnum.NoParse); + if (getToscaElementRes.isRight()) { + TitanOperationStatus status = getToscaElementRes.right().value(); + CommonUtility.addRecordToLog(logger, CommonUtility.LogLevelEnum.DEBUG, "Failed to get tosca element {} upon adding the properties. Status is {}. ", serviceId, status); + statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status); + return Either.right(statusRes); + } + GraphVertex serviceVertex = getToscaElementRes.left().value(); + if (!isUpdateAction){ + currentPath.setUniqueId(UUID.randomUUID().toString()); + } + statusRes = performUpdateToscaAction(isUpdateAction, serviceVertex, Arrays.asList(currentPath), JsonPresentationFields.FORWARDING_PATH); + { + if (!statusRes.equals(StorageOperationStatus.OK)) { + logger.error("Failed to find the parent capability of capability type {}. status is {}", serviceId, statusRes); + return Either.right(statusRes); + } + return Either.left(currentPath); + } + + } + + + private StorageOperationStatus performUpdateToscaAction(boolean isUpdate, GraphVertex graphVertex, List<ForwardingPathDataDefinition> toscaDataList, JsonPresentationFields mapKeyField) { + if (isUpdate) { + return updateToscaDataOfToscaElement(graphVertex, EdgeLabelEnum.FORWARDING_PATH, VertexTypeEnum.FORWARDING_PATH, toscaDataList, JsonPresentationFields.UNIQUE_ID); + } else { + return addToscaDataToToscaElement(graphVertex, EdgeLabelEnum.FORWARDING_PATH, VertexTypeEnum.FORWARDING_PATH, toscaDataList, JsonPresentationFields.UNIQUE_ID); + } + } + +} + + + 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 87053ff454..668a6d973a 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 @@ -34,14 +34,12 @@ import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.GroupDefinition; import org.openecomp.sdc.be.model.GroupInstance; import org.openecomp.sdc.be.model.GroupInstanceProperty; import org.openecomp.sdc.be.model.GroupProperty; -import org.openecomp.sdc.be.model.User; 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; @@ -56,9 +54,9 @@ import fj.data.Either; @org.springframework.stereotype.Component("groups-operation") public class GroupsOperation extends BaseOperation { - private static Logger logger = LoggerFactory.getLogger(GroupsOperation.class.getName()); + private static final Logger log = LoggerFactory.getLogger(GroupsOperation.class); - public Either<List<GroupDefinition>, StorageOperationStatus> createGroups(Component component, User user, ComponentTypeEnum componentType, Map<String, GroupDataDefinition> groups) { + public Either<List<GroupDefinition>, StorageOperationStatus> createGroups(Component component, Map<String, GroupDataDefinition> groups) { Either<List<GroupDefinition>, StorageOperationStatus> result = null; Either<GraphVertex, TitanOperationStatus> getComponentVertex = null; @@ -76,20 +74,13 @@ public class GroupsOperation extends BaseOperation { result = Either.right(status); } } - /* if (result == null) { - status = topologyTemplateOperation.associateGroupsPropertiesToComponent(getComponentVertex.left().value(), groupsProperties); - if (status != StorageOperationStatus.OK) { - result = Either.right(status); - } - }*/ if (result == null) { result = Either.left(ModelConverter.convertToGroupDefinitions(groups)); } return result; } - public Either<List<GroupDefinition>, StorageOperationStatus> addGroups(Component component, User user, ComponentTypeEnum componentType, List<GroupDataDefinition> groups) { - // TODO Auto-generated method stub + public Either<List<GroupDefinition>, StorageOperationStatus> addGroups(Component component, List<GroupDataDefinition> groups) { Either<List<GroupDefinition>, StorageOperationStatus> result = null; Either<GraphVertex, TitanOperationStatus> getComponentVertex = null; StorageOperationStatus status = null; @@ -115,8 +106,7 @@ public class GroupsOperation extends BaseOperation { return result; } - public Either<List<GroupDefinition>, StorageOperationStatus> deleteGroups(Component component, User user, ComponentTypeEnum componentType, List<GroupDataDefinition> groups) { - // TODO Auto-generated method stub + public Either<List<GroupDefinition>, StorageOperationStatus> deleteGroups(Component component, List<GroupDataDefinition> groups) { Either<List<GroupDefinition>, StorageOperationStatus> result = null; Either<GraphVertex, TitanOperationStatus> getComponentVertex = null; StorageOperationStatus status = null; @@ -143,8 +133,7 @@ public class GroupsOperation extends BaseOperation { return result; } - public Either<List<GroupDefinition>, StorageOperationStatus> updateGroups(Component component, ComponentTypeEnum componentType, List<GroupDataDefinition> groups) { - // TODO Auto-generated method stub + public <T extends GroupDataDefinition> Either<List<GroupDefinition>, StorageOperationStatus> updateGroups(Component component, List<T> groups) { Either<List<GroupDefinition>, StorageOperationStatus> result = null; Either<GraphVertex, TitanOperationStatus> getComponentVertex = null; StorageOperationStatus status = null; @@ -184,12 +173,11 @@ public class GroupsOperation extends BaseOperation { Either<List<GroupProperty>,StorageOperationStatus> result = null; Either<GraphVertex, TitanOperationStatus> getComponentVertex = null; GraphVertex componentVertex = null; - StorageOperationStatus status = null; if (result == null) { getComponentVertex = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata); if (getComponentVertex.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch component {}. Status is {} ", componentId); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch component {}. Status is {} ", componentId); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentVertex.right().value())); } } @@ -206,7 +194,7 @@ public class GroupsOperation extends BaseOperation { StorageOperationStatus updateDataRes = updateToscaDataOfToscaElement(componentVertex, EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, group, JsonPresentationFields.NAME); if ( updateDataRes != StorageOperationStatus.OK ){ - logger.debug("Failed to update properties for group {} error {}", group.getName(), updateDataRes); + log.debug("Failed to update properties for group {} error {}", group.getName(), updateDataRes); result = Either.right(updateDataRes); } } @@ -214,7 +202,7 @@ public class GroupsOperation extends BaseOperation { componentVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); Either<GraphVertex, TitanOperationStatus> updateRes = titanDao.updateVertex(componentVertex); if (updateRes.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update the component {}. Status is {} ", componentId, updateRes.right().value()); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the component {}. Status is {} ", componentId, updateRes.right().value()); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateRes.right().value())); } } @@ -241,7 +229,7 @@ public class GroupsOperation extends BaseOperation { } - public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstances(Component component, ComponentTypeEnum componentType, String instanceId, List<GroupInstance> updatedGroupInstances) { + public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstances(Component component, String instanceId, List<GroupInstance> updatedGroupInstances) { Either<List<GroupInstance>, StorageOperationStatus> result = null; StorageOperationStatus status = null; @@ -267,7 +255,7 @@ public class GroupsOperation extends BaseOperation { public Either<GroupDefinition, StorageOperationStatus> updateGroup(Component component, GroupDefinition currentGroup) { StorageOperationStatus status = updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, currentGroup, JsonPresentationFields.NAME); if(status != StorageOperationStatus.OK){ - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update group {} of component {}. The status is}. ", currentGroup.getName(), component.getName(), status); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update group {} of component {}. The status is}. ", currentGroup.getName(), component.getName(), status); return Either.right(status); } return Either.left(currentGroup); @@ -276,7 +264,7 @@ public class GroupsOperation extends BaseOperation { public StorageOperationStatus deleteGroup(Component component, String currentGroupName) { StorageOperationStatus status = deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, currentGroupName, JsonPresentationFields.NAME); if(status != StorageOperationStatus.OK){ - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete group {} of component {}. The status is}. ", currentGroupName, component.getName(), status); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete group {} of component {}. The status is}. ", currentGroupName, component.getName(), status); } return status; } @@ -284,7 +272,7 @@ public class GroupsOperation extends BaseOperation { public Either<GroupDefinition, StorageOperationStatus> addGroup(Component component, GroupDefinition currentGroup) { StorageOperationStatus status = addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, currentGroup, JsonPresentationFields.NAME); if(status != StorageOperationStatus.OK){ - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update group {} of component {}. The status is}. ", currentGroup.getName(), component.getName(), status); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update group {} of component {}. The status is}. ", currentGroup.getName(), component.getName(), status); return Either.right(status); } return Either.left(currentGroup); @@ -294,7 +282,7 @@ public class GroupsOperation extends BaseOperation { Either<GraphVertex, TitanOperationStatus> getComponentVertex = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata); if (getComponentVertex.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch component {}. Status is {} ", componentId); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch component {}. Status is {} ", componentId); return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentVertex.right().value())); } @@ -310,7 +298,7 @@ public class GroupsOperation extends BaseOperation { pathKeys.add(instanceId); StorageOperationStatus updateDataRes = updateToscaDataDeepElementOfToscaElement(componentId, EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, groupInstanceDataDefinition, pathKeys, JsonPresentationFields.NAME); if (updateDataRes != StorageOperationStatus.OK) { - logger.debug("Failed to update properties for group instance {} error {}", oldGroupInstance.getName(), updateDataRes); + log.debug("Failed to update properties for group instance {} error {}", oldGroupInstance.getName(), updateDataRes); return Either.right(updateDataRes); } return Either.left(oldGroupInstance); 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 f59f097bdb..3dc39b3a99 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 @@ -28,11 +28,11 @@ import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; +import java.util.function.BiConsumer; +import java.util.function.BiPredicate; import java.util.Optional; import java.util.Set; import java.util.UUID; -import java.util.function.BiConsumer; -import java.util.function.BiPredicate; import java.util.stream.Collectors; import org.apache.commons.collections.CollectionUtils; @@ -69,22 +69,7 @@ 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.datatypes.tosca.ToscaDataDefinition; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.CapabilityDefinition; -import org.openecomp.sdc.be.model.CapabilityRequirementRelationship; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentInstanceInput; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.GroupDefinition; -import org.openecomp.sdc.be.model.GroupInstance; -import org.openecomp.sdc.be.model.RelationshipImpl; -import org.openecomp.sdc.be.model.RelationshipInfo; -import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; -import org.openecomp.sdc.be.model.RequirementDefinition; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.jsontitan.datamodel.NodeType; import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate; import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; @@ -539,6 +524,7 @@ public class NodeTemplateOperation extends BaseOperation { } } } + return updateAllAndCalculatedCapReqOnGraph(container.getUniqueId(), containerV, capResult, capFullResult, reqResult, reqFullResult); } } return StorageOperationStatus.OK; @@ -1000,35 +986,7 @@ public class NodeTemplateOperation extends BaseOperation { dataDefinition.setToscaComponentName((String) originToscaElement.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME)); if (dataDefinition.getOriginType() == null && originToscaElement != null) { ResourceTypeEnum resourceType = originToscaElement.getResourceType(); - OriginTypeEnum originType = null; - switch (resourceType) { - case VF: - originType = OriginTypeEnum.VF; - break; - 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; - case ServiceProxy: - originType = OriginTypeEnum.ServiceProxy; - break; - case Configuration: - originType = OriginTypeEnum.Configuration; - break; - default: - break; - } + OriginTypeEnum originType = OriginTypeEnum.findByValue(resourceType.name()); dataDefinition.setOriginType(originType); } if(dataDefinition.getOriginType() == OriginTypeEnum.ServiceProxy) @@ -1340,7 +1298,7 @@ public class NodeTemplateOperation extends BaseOperation { Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqFullResult = null; MapListRequirementDataDefinition reqMapOfLists = null; Optional<RequirementDataDefinition> foundRequirement; - RelationshipInfo relationshipInfo = foundRelation.getSingleRelationship().getRelation(); + RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation(); Either<GraphVertex, TitanOperationStatus> containerVEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll); if (containerVEither.isRight()) { TitanOperationStatus error = containerVEither.right().value(); @@ -1387,7 +1345,7 @@ public class NodeTemplateOperation extends BaseOperation { MapListCapabiltyDataDefinition capMapOfLists = null; Optional<CapabilityDataDefinition> foundRequirement; - RelationshipInfo relationshipInfo = foundRelation.getSingleRelationship().getRelation(); + RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation(); Either<GraphVertex, TitanOperationStatus> containerVEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll); if (containerVEither.isRight()) { TitanOperationStatus error = containerVEither.right().value(); @@ -1526,7 +1484,8 @@ public class NodeTemplateOperation extends BaseOperation { mapListCapaDataDef.put(hereIsTheKey, findByKey); } findByKey.add(cap); - relationship.setCapability(cap); + if(relationship!= null) + relationship.setCapability(cap); break; } } @@ -1574,7 +1533,8 @@ public class NodeTemplateOperation extends BaseOperation { mapListReqDataDef.put(hereIsTheKey, findByKey); } findByKey.add(req); - relationship.setRequirement(req); + if(relationship!= null) + relationship.setRequirement(req); break; } } @@ -1770,8 +1730,12 @@ public class NodeTemplateOperation extends BaseOperation { } } } + if (requirementForRelation == null) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch requirement for type {} for instance {} in container {}.", type, toInstId, containerId); + return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); + } 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, + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No macth for capability from type {} and requirement {} from {} to {} in container {}.", capabilityForRelation.getType(), requirementForRelation.getCapability(), fromInstId, toInstId, containerId); return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); } @@ -1985,6 +1949,10 @@ public class NodeTemplateOperation extends BaseOperation { return updateToscaDataDeepElementOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, property, pathKeys, JsonPresentationFields.NAME); } + public StorageOperationStatus overrideComponentCapabilitiesProperties(Component containerComponent, Map<String, MapCapabiltyProperty> capabilityPropertyMap) { + return overrideToscaDataOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, capabilityPropertyMap); + } + public StorageOperationStatus addComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) { List<String> pathKeys = new ArrayList<>(); pathKeys.add(componentInstanceId); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTypeOperation.java index d46743cfa9..59f4745537 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTypeOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTypeOperation.java @@ -41,6 +41,7 @@ import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition; import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition; import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/PolicyOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/PolicyOperation.java new file mode 100644 index 0000000000..06770318aa --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/PolicyOperation.java @@ -0,0 +1,63 @@ +package org.openecomp.sdc.be.model.jsontitan.operations; + +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.dao.utils.MapUtil; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +@org.springframework.stereotype.Component +public class PolicyOperation { + + private static final Logger log = LoggerFactory.getLogger(PolicyOperation.class); + private TopologyTemplateOperation topologyTemplateOperation; + private TitanDao titanDao; + + public PolicyOperation(TopologyTemplateOperation topologyTemplateOperation, TitanDao titanDao) { + this.topologyTemplateOperation = topologyTemplateOperation; + this.titanDao = titanDao; + } + + /** + * updates a list of policy properties by overriding the existing ones with the same name + * @param containerComponent the container of the policy of which its properties are to be updated + * @param policyId the id of the policy of which its properties are to be updated + * @param propertiesToUpdate the policy properties to update + * @return the update operation status + */ + public StorageOperationStatus updatePolicyProperties(Component containerComponent, String policyId, List<PropertyDataDefinition> propertiesToUpdate) { + log.debug("#updatePolicyProperties - updating the properties of policy {} in component {}", policyId, containerComponent.getUniqueId()); + PolicyDefinition policy = containerComponent.getPolicyById(policyId); + return titanDao.getVertexById(containerComponent.getUniqueId(), JsonParseFlagEnum.NoParse) + .either(containerVertex -> updatePolicyProperties(containerVertex, policy, propertiesToUpdate), + DaoStatusConverter::convertTitanStatusToStorageStatus); + } + + private StorageOperationStatus updatePolicyProperties(GraphVertex container, PolicyDefinition policy, List<PropertyDataDefinition> propertiesToUpdate) { + List<PropertyDataDefinition> policyProperties = policy.getProperties(); + List<PropertyDataDefinition> updatedPolicyProperties = updatePolicyProperties(policyProperties, propertiesToUpdate); + policy.setProperties(updatedPolicyProperties); + return topologyTemplateOperation.updatePolicyOfToscaElement(container, policy); + } + + private List<PropertyDataDefinition> updatePolicyProperties(List<PropertyDataDefinition> currentPolicyProperties, List<PropertyDataDefinition> toBeUpdatedProperties) { + Map<String, PropertyDataDefinition> currPropsByName = MapUtil.toMap(currentPolicyProperties, PropertyDataDefinition::getName); + overrideCurrentPropertiesWithUpdatedProperties(currPropsByName, toBeUpdatedProperties); + return new ArrayList<>(currPropsByName.values()); + } + + private void overrideCurrentPropertiesWithUpdatedProperties(Map<String, PropertyDataDefinition> currPropsByName, List<PropertyDataDefinition> toBeUpdatedProperties) { + toBeUpdatedProperties.forEach(prop -> currPropsByName.put(prop.getName(), prop)); + } + +} 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 b1d4f151d8..9ad3053d66 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 @@ -20,15 +20,8 @@ package org.openecomp.sdc.be.model.jsontitan.operations; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.stream.Collectors; - +import com.google.gson.reflect.TypeToken; +import fj.data.Either; import org.apache.commons.collections.MapUtils; import org.apache.tinkerpop.gremlin.structure.Direction; import org.apache.tinkerpop.gremlin.structure.Edge; @@ -37,24 +30,15 @@ import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapCapabiltyProperty; -import org.openecomp.sdc.be.datatypes.elements.MapGroupsDataDefinition; -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.*; 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.model.Component; 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.PolicyDefinition; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate; @@ -65,19 +49,31 @@ 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; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.jsongraph.util.CommonUtility; import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.gson.reflect.TypeToken; - -import fj.data.Either; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.stream.Collectors; @org.springframework.stereotype.Component("topology-template-operation") public class TopologyTemplateOperation extends ToscaElementOperation { + private static Logger log = LoggerFactory.getLogger(TopologyTemplateOperation.class.getName()); + @Override + public Either<ToscaElement, StorageOperationStatus> getToscaElement(String uniqueId) { + return super.getToscaElement(uniqueId); + } + public Either<TopologyTemplate, StorageOperationStatus> createTopologyTemplate(TopologyTemplate topologyTemplate) { Either<TopologyTemplate, StorageOperationStatus> result = null; @@ -125,6 +121,11 @@ public class TopologyTemplateOperation extends ToscaElementOperation { result = Either.right(associateGroups); return result; } + StorageOperationStatus associatePolicies = associatePoliciesToComponent(topologyTemplateVertex, topologyTemplate); + if (associatePolicies != StorageOperationStatus.OK) { + result = Either.right(associatePolicies); + return result; + } StorageOperationStatus associateInstAttr = associateInstAttributesToComponent(topologyTemplateVertex, topologyTemplate); if (associateInstAttr != StorageOperationStatus.OK) { result = Either.right(associateInstAttr); @@ -174,10 +175,40 @@ public class TopologyTemplateOperation extends ToscaElementOperation { result = Either.right(associateCapProperties); return result; } + StorageOperationStatus associatePathProperties = associateForwardingPathToResource(topologyTemplateVertex, topologyTemplate); + if (associateCapProperties != StorageOperationStatus.OK) { + result = Either.right(associatePathProperties); + return result; + } + + return Either.left(topologyTemplate); } + private StorageOperationStatus associatePoliciesToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { + return associatePoliciesToComponent(nodeTypeVertex, topologyTemplate.getPolicies()); + } + + private StorageOperationStatus associatePoliciesToComponent(GraphVertex nodeTypeVertex, Map<String, PolicyDataDefinition> policies) { + if (policies != null && !policies.isEmpty()) { + policies.values().stream().filter(p -> p.getUniqueId() == null).forEach(p -> { + String uid = UniqueIdBuilder.buildGroupingUid(nodeTypeVertex.getUniqueId(), p.getName()); + p.setUniqueId(uid); + }); + Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.POLICIES, EdgeLabelEnum.POLICIES, policies); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + private StorageOperationStatus associateForwardingPathToResource(GraphVertex topologyTemplateVertex, TopologyTemplate topologyTemplate) { + Map<String, ForwardingPathDataDefinition> forwardingPaths = topologyTemplate.getForwardingPaths(); + return associateForwardingPathToComponent(topologyTemplateVertex,forwardingPaths); + } + private StorageOperationStatus associateCapPropertiesToResource(GraphVertex topologyTemplateVertex, TopologyTemplate topologyTemplate) { Map<String, MapCapabiltyProperty> calculatedCapProperties = topologyTemplate.getCalculatedCapabilitiesProperties(); if (calculatedCapProperties != null && !calculatedCapProperties.isEmpty()) { @@ -405,6 +436,16 @@ public class TopologyTemplateOperation extends ToscaElementOperation { return associateInstAttributeToComponent(nodeTypeVertex, instAttr); } + public StorageOperationStatus associateForwardingPathToComponent(GraphVertex nodeTypeVertex, Map<String, ForwardingPathDataDefinition> forwardingPathMap) { + if (forwardingPathMap != null && !forwardingPathMap.isEmpty()) { + Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.FORWARDING_PATH, EdgeLabelEnum.FORWARDING_PATH, forwardingPathMap); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + public StorageOperationStatus associateInstAttributeToComponent(GraphVertex nodeTypeVertex, Map<String, MapPropertiesDataDefinition> instAttr) { if (instAttr != null && !instAttr.isEmpty()) { Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.INST_ATTRIBUTES, EdgeLabelEnum.INST_ATTRIBUTES, instAttr); @@ -509,8 +550,8 @@ public class TopologyTemplateOperation extends ToscaElementOperation { TopologyTemplate toscaElement; toscaElement = convertToTopologyTemplate(componentV); - TitanOperationStatus status = null; - if (false == componentParametersView.isIgnoreUsers()) { + TitanOperationStatus status; + if (!componentParametersView.isIgnoreUsers()) { status = setCreatorFromGraph(componentV, toscaElement); if (status != TitanOperationStatus.OK) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); @@ -521,72 +562,79 @@ public class TopologyTemplateOperation extends ToscaElementOperation { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); } } - if (false == componentParametersView.isIgnoreCategories()) { + if (!componentParametersView.isIgnoreCategories()) { status = setTopologyTempalteCategoriesFromGraph(componentV, toscaElement); if (status != TitanOperationStatus.OK) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); } } - if (false == componentParametersView.isIgnoreArtifacts()) { + if (!componentParametersView.isIgnoreArtifacts()) { TitanOperationStatus storageStatus = setAllArtifactsFromGraph(componentV, toscaElement); if (storageStatus != TitanOperationStatus.OK) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(storageStatus)); } } - if (false == componentParametersView.isIgnoreComponentInstancesProperties()) { + if (!componentParametersView.isIgnoreComponentInstancesProperties()) { status = setComponentInstancesPropertiesFromGraph(componentV, toscaElement); if (status != TitanOperationStatus.OK) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); } } - if (false == componentParametersView.isIgnoreCapabilities()) { + if (!componentParametersView.isIgnoreCapabilities()) { status = setCapabilitiesFromGraph(componentV, toscaElement); if (status != TitanOperationStatus.OK) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); } } - if (false == componentParametersView.isIgnoreRequirements()) { + if (!componentParametersView.isIgnoreRequirements()) { status = setRequirementsFromGraph(componentV, toscaElement); if (status != TitanOperationStatus.OK) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); } } - if (false == componentParametersView.isIgnoreAllVersions()) { + if (!componentParametersView.isIgnoreAllVersions()) { status = setAllVersions(componentV, toscaElement); if (status != TitanOperationStatus.OK) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); } } - if (false == componentParametersView.isIgnoreAdditionalInformation()) { + if (!componentParametersView.isIgnoreAdditionalInformation()) { status = setAdditionalInformationFromGraph(componentV, toscaElement); if (status != TitanOperationStatus.OK) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); } } - if (false == componentParametersView.isIgnoreGroups()) { + if (!componentParametersView.isIgnoreGroups()) { status = setGroupsFromGraph(componentV, toscaElement); if (status != TitanOperationStatus.OK) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); } } - if (false == componentParametersView.isIgnoreComponentInstances()) { + if (!componentParametersView.isIgnorePolicies()) { + status = setPoliciesFromGraph(componentV, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + + } + if (!componentParametersView.isIgnoreComponentInstances()) { status = setInstGroupsFromGraph(componentV, toscaElement); if (status != TitanOperationStatus.OK) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); } } - if (false == componentParametersView.isIgnoreInputs()) { + if (!componentParametersView.isIgnoreInputs()) { status = setInputsFromGraph(componentV, toscaElement); if (status != TitanOperationStatus.OK) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); } } - if (false == componentParametersView.isIgnoreProperties()) { + if (!componentParametersView.isIgnoreProperties()) { status = setPropertiesFromGraph(componentV, toscaElement); if (status != TitanOperationStatus.OK) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); @@ -594,7 +642,7 @@ public class TopologyTemplateOperation extends ToscaElementOperation { } - if (false == componentParametersView.isIgnoreComponentInstancesInputs()) { + if (!componentParametersView.isIgnoreComponentInstancesInputs()) { status = setComponentInstancesInputsFromGraph(componentV, toscaElement); if (status != TitanOperationStatus.OK) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); @@ -602,16 +650,49 @@ public class TopologyTemplateOperation extends ToscaElementOperation { } } - if (false == componentParametersView.isIgnoreCapabiltyProperties()) { + if (!componentParametersView.isIgnoreCapabiltyProperties()) { status = setComponentInstancesCapPropertiesFromGraph(componentV, toscaElement); if (status != TitanOperationStatus.OK) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); } } + + if (!componentParametersView.isIgnoreForwardingPath()) { + status = setForwardingGraphPropertiesFromGraph(componentV, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + + } + } return Either.left(toscaElement); } + private TitanOperationStatus setPoliciesFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) { + Either<Map<String, PolicyDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.POLICIES); + if (result.isLeft()) { + toscaElement.setPolicies(result.left().value()); + } else { + if (result.right().value() != TitanOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return TitanOperationStatus.OK; + } + + private TitanOperationStatus setForwardingGraphPropertiesFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) { + Either<Map<String, ForwardingPathDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.FORWARDING_PATH); + if (result.isLeft()) { + topologyTemplate.setForwardingPaths(result.left().value()); + } else { + if (result.right().value() != TitanOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return TitanOperationStatus.OK; + } + + private TitanOperationStatus setComponentInstancesCapPropertiesFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) { Either<Map<String, MapCapabiltyProperty>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES); if (result.isLeft()) { @@ -808,6 +889,7 @@ public class TopologyTemplateOperation extends ToscaElementOperation { return TitanOperationStatus.OK; } + @SuppressWarnings("unchecked") private TopologyTemplate convertToTopologyTemplate(GraphVertex componentV) { TopologyTemplate topologyTemplate = super.convertToComponent(componentV); @@ -901,6 +983,12 @@ public class TopologyTemplateOperation extends ToscaElementOperation { log.debug("Failed to disassociate service api artifacts for {} error {}", toscaElementVertex.getUniqueId(), status); Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); } + status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.FORWARDING_PATH); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to disassociate service api artifacts for {} error {}", toscaElementVertex.getUniqueId(), status); + Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INSTANCE_ARTIFACTS); toscaElementVertex.getVertex().remove(); log.trace("Tosca element vertex for {} was removed", toscaElementVertex.getUniqueId()); @@ -984,6 +1072,7 @@ public class TopologyTemplateOperation extends ToscaElementOperation { return Either.left(byCriteria.left().value()); } + @SuppressWarnings("unchecked") public boolean isInUse(GraphVertex elementV, List<GraphVertex> allNonDeleted) { for (GraphVertex containerV : allNonDeleted) { Map<String, CompositionDataDefinition> composition = (Map<String, CompositionDataDefinition>) containerV.getJson(); @@ -1004,6 +1093,7 @@ public class TopologyTemplateOperation extends ToscaElementOperation { return false; } + @SuppressWarnings("unchecked") public boolean isInUse(String componentId, List<GraphVertex> allNonDeleted) { for (GraphVertex containerV : allNonDeleted) { Map<String, CompositionDataDefinition> composition = (Map<String, CompositionDataDefinition>) containerV.getJson(); @@ -1074,14 +1164,15 @@ public class TopologyTemplateOperation extends ToscaElementOperation { return result; } /** - * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name and type + * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId * @param componentId * @param instanceId * @param capabilityName * @param capabilityType + * @param ownerId * @return */ - public Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityName, String capabilityType) { + public Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityName, String capabilityType, String ownerId) { Either<List<ComponentInstanceProperty>, StorageOperationStatus> result = null; Map<String, MapCapabiltyProperty> mapPropertiesDataDefinition = null; @@ -1098,21 +1189,26 @@ public class TopologyTemplateOperation extends ToscaElementOperation { } } if(isNotEmptyMapOfProperties(instanceId, mapPropertiesDataDefinition)){ - result = Either.left(findComponentInstanceCapabilityProperties(instanceId, capabilityName, capabilityType, mapPropertiesDataDefinition.get(instanceId).getMapToscaDataDefinition())); + result = Either.left(findComponentInstanceCapabilityProperties(instanceId, capabilityName, capabilityType, ownerId, mapPropertiesDataDefinition.get(instanceId).getMapToscaDataDefinition())); } - return result; + return result; + } + + public StorageOperationStatus updateComponentInstanceCapabilityProperties(Component containerComponent, String componentInstanceId, MapCapabiltyProperty instanceProperties) { + return updateToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, instanceProperties, componentInstanceId); } + private boolean isNotEmptyMapOfProperties(String instanceId, Map<String, MapCapabiltyProperty> mapPropertiesDataDefinition) { return MapUtils.isNotEmpty(mapPropertiesDataDefinition) && mapPropertiesDataDefinition.get(instanceId) != null && MapUtils.isNotEmpty(mapPropertiesDataDefinition.get(instanceId).getMapToscaDataDefinition()); } - private List<ComponentInstanceProperty> findComponentInstanceCapabilityProperties(String instanceId, String capabilityName, String capabilityType, Map<String, MapPropertiesDataDefinition> propertiesMap) { + private List<ComponentInstanceProperty> findComponentInstanceCapabilityProperties(String instanceId, String capabilityName, String capabilityType, String ownerId, Map<String, MapPropertiesDataDefinition> propertiesMap) { List<ComponentInstanceProperty> capPropsList = null; for(Entry<String, MapPropertiesDataDefinition> capProp : propertiesMap.entrySet()){ - if (isBelongingPropertyMap(instanceId, capabilityName, capabilityType, capProp)) { + if (isBelongingPropertyMap(instanceId, capabilityName, capabilityType, ownerId, capProp)) { Map<String, PropertyDataDefinition> capMap = capProp.getValue().getMapToscaDataDefinition(); if (capMap != null && !capMap.isEmpty()) { capPropsList = capMap.values().stream().map(o -> new ComponentInstanceProperty(o)).collect(Collectors.toList()); @@ -1126,16 +1222,48 @@ public class TopologyTemplateOperation extends ToscaElementOperation { return capPropsList; } - private boolean isBelongingPropertyMap(String instanceId, String capabilityName, String capabilityType, Entry<String, MapPropertiesDataDefinition> capProp) { + private boolean isBelongingPropertyMap(String instanceId, String capabilityName, String capabilityType, String ownerId, Entry<String, MapPropertiesDataDefinition> capProp) { if (capProp != null) { String[] path = capProp.getKey().split(ModelConverter.CAP_PROP_DELIM ); if (path.length < 4) { log.debug("wrong key format for capabilty, key {}", capProp); return false; } - return path[path.length - 2].equals(capabilityType) && path[path.length - 1].equals(capabilityName) && path[0].equals(instanceId); + return path[path.length - 2].equals(capabilityType) && path[path.length - 1].equals(capabilityName) && path[1].equals(ownerId) && path[0].equals(instanceId); } return false; } + public StorageOperationStatus addPolicyToToscaElement(GraphVertex componentV, PolicyDefinition policyDefinition, int counter) { + fillPolicyDefinition(componentV, policyDefinition, counter); + return addToscaDataToToscaElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policyDefinition, JsonPresentationFields.UNIQUE_ID); + } + + public StorageOperationStatus updatePolicyOfToscaElement(GraphVertex componentV, PolicyDefinition policyDefinition) { + return updateToscaDataOfToscaElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policyDefinition, JsonPresentationFields.UNIQUE_ID); + } + + public StorageOperationStatus updatePoliciesOfToscaElement(GraphVertex componentV, List<PolicyDefinition> policiesDefinitions) { + return updateToscaDataOfToscaElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policiesDefinitions, JsonPresentationFields.UNIQUE_ID); + } + + public StorageOperationStatus removePolicyFromToscaElement(GraphVertex componentV, String policyId) { + return deleteToscaDataElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policyId, JsonPresentationFields.UNIQUE_ID); + } + + private void fillPolicyDefinition(GraphVertex componentV, PolicyDefinition policyDefinition, int counter) { + String policyName = buildSubComponentName((String) componentV.getJsonMetadataField(JsonPresentationFields.NAME), policyDefinition.getPolicyTypeName(), counter); + policyDefinition.setName(policyName); + policyDefinition.setInvariantName(policyName); + policyDefinition.setComponentName((String) componentV.getJsonMetadataField(JsonPresentationFields.NAME)); + policyDefinition.setUniqueId(UniqueIdBuilder.buildPolicyUniqueId(componentV.getUniqueId(), policyName)); + policyDefinition.setInvariantUUID(UniqueIdBuilder.buildInvariantUUID()); + policyDefinition.setPolicyUUID(UniqueIdBuilder.generateUUID()); + } + + public static String buildSubComponentName(String componentName, String subComponentTypeName, int counter) { + String typeSuffix = subComponentTypeName.substring(subComponentTypeName.lastIndexOf('.') + 1, subComponentTypeName.length()); + return componentName + Constants.GROUP_POLICY_NAME_DELIMETER + typeSuffix + Constants.GROUP_POLICY_NAME_DELIMETER + counter; + } + } 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 f34975b073..86415de635 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 @@ -76,6 +76,8 @@ import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.thinkaurelius.titan.core.TitanVertex; + import fj.data.Either; @org.springframework.stereotype.Component("tosca-element-lifecycle-operation") @@ -223,29 +225,43 @@ public class ToscaElementLifecycleOperation extends BaseOperation { Either<GraphVertex, TitanOperationStatus> getToscaElementRes = null; Iterator<Edge> nextVersionComponentIter = null; ToscaElementOperation operation; + Vertex preVersionVertex = null; try { getToscaElementRes = titanDao.getVertexById(toscaElementId, JsonParseFlagEnum.ParseMetadata); if (getToscaElementRes.isRight()) { CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getToscaElementRes.right().value())); } - if (result == null && hasPreviousVersion(getToscaElementRes.left().value())) { + GraphVertex currVersionV = getToscaElementRes.left().value(); + if (result == null && hasPreviousVersion(currVersionV)) { // find previous version - nextVersionComponentIter = getToscaElementRes.left().value().getVertex().edges(Direction.IN, EdgeLabelEnum.VERSION.name()); + nextVersionComponentIter = currVersionV.getVertex().edges(Direction.IN, EdgeLabelEnum.VERSION.name()); if (nextVersionComponentIter == null || !nextVersionComponentIter.hasNext()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch previous version of tosca element with name {}. ", getToscaElementRes.left().value().getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME).toString()); + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch previous version of tosca element with name {}. ", currVersionV.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME).toString()); result = Either.right(StorageOperationStatus.NOT_FOUND); } if (result == null) { - StorageOperationStatus updateOldResourceResult = updateOldToscaElementBeforeUndoCheckout(nextVersionComponentIter.next().outVertex()); + preVersionVertex = nextVersionComponentIter.next().outVertex(); + StorageOperationStatus updateOldResourceResult = updateOldToscaElementBeforeUndoCheckout(preVersionVertex); if (updateOldResourceResult != StorageOperationStatus.OK) { result = Either.right(updateOldResourceResult); } } } if (result == null) { - operation = getToscaElementOperation(getToscaElementRes.left().value().getLabel()); - result = operation.deleteToscaElement(getToscaElementRes.left().value()); + GraphVertex prevVersionV = null; + if (preVersionVertex != null) { + prevVersionV = new GraphVertex(); + prevVersionV.setVertex((TitanVertex) preVersionVertex); + String uniqueIdPreVer = (String) titanDao.getProperty((TitanVertex) preVersionVertex, GraphPropertyEnum.UNIQUE_ID.getProperty()); + prevVersionV.setUniqueId(uniqueIdPreVer); + } + StorageOperationStatus updateCatalogRes = updateEdgeToCatalogRoot(prevVersionV, currVersionV); + if (updateCatalogRes != StorageOperationStatus.OK) { + return Either.right(updateCatalogRes); + } + operation = getToscaElementOperation(currVersionV.getLabel()); + result = operation.deleteToscaElement(currVersionV); } } catch (Exception e) { CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during undo checkout tosca element {}. {}", toscaElementId, e.getMessage()); @@ -539,11 +555,12 @@ public class ToscaElementLifecycleOperation extends BaseOperation { if (result == null) { TitanOperationStatus createVersionEdgeStatus = titanDao.createEdge(toscaElement, certifiedToscaElement, EdgeLabelEnum.VERSION, new HashMap<>()); if (createVersionEdgeStatus != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create version edge from last element {} to new certified element {}. status=", toscaElement.getUniqueId(),certifiedToscaElement.getUniqueId(), createVersionEdgeStatus); + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create version edge from last element {} to new certified element {}. status=", toscaElement.getUniqueId(), certifiedToscaElement.getUniqueId(), + createVersionEdgeStatus); result = DaoStatusConverter.convertTitanStatusToStorageStatus(createVersionEdgeStatus); } } - if(result == null){ + if (result == null) { while (certReqUserEdgeIter.hasNext()) { Edge edge = certReqUserEdgeIter.next(); @@ -698,6 +715,14 @@ public class ToscaElementLifecycleOperation extends BaseOperation { CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to set highest version of tosca element {} to [{}]. Status is {}", toscaElement.getUniqueId(), false, status); result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); } + // remove previous certified version from the catalog + GraphVertex lastCertifiedV = new GraphVertex(); + lastCertifiedV.setVertex((TitanVertex) lastCertifiedVertex); + lastCertifiedV.setUniqueId((String) titanDao.getProperty((TitanVertex) lastCertifiedVertex, GraphPropertyEnum.UNIQUE_ID.getProperty())); + StorageOperationStatus res = updateEdgeToCatalogRoot(null, lastCertifiedV); + if (res != StorageOperationStatus.OK) { + return res; + } } } if (result == null) { @@ -811,9 +836,9 @@ public class ToscaElementLifecycleOperation extends BaseOperation { Map<String, Object> propertiesToUpdate = new HashMap<>(); propertiesToUpdate.put(GraphPropertyEnum.IS_HIGHEST_VERSION.getProperty(), true); - Map<String, Object> jsonMetadataMap = JsonParserUtils.parseToJson((String) previousVersionToscaElement.property(GraphPropertyEnum.METADATA.getProperty()).value()); + Map<String, Object> jsonMetadataMap = JsonParserUtils.toMap((String) previousVersionToscaElement.property(GraphPropertyEnum.METADATA.getProperty()).value()); jsonMetadataMap.put(GraphPropertyEnum.IS_HIGHEST_VERSION.getProperty(), true); - propertiesToUpdate.put(GraphPropertyEnum.METADATA.getProperty(), JsonParserUtils.jsonToString(jsonMetadataMap)); + propertiesToUpdate.put(GraphPropertyEnum.METADATA.getProperty(), JsonParserUtils.toJson(jsonMetadataMap)); titanDao.setVertexProperties(previousVersionToscaElement, propertiesToUpdate); @@ -832,6 +857,7 @@ public class ToscaElementLifecycleOperation extends BaseOperation { result = DaoStatusConverter.convertTitanStatusToStorageStatus(replaceRes); } } + } } catch (Exception e) { CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during update previous tosca element {} before undo checkout. {} ", e.getMessage()); @@ -888,9 +914,9 @@ public class ToscaElementLifecycleOperation extends BaseOperation { // check if component with the next version doesn't exist. Iterator<Edge> nextVersionComponentIter = toscaElementVertex.getVertex().edges(Direction.OUT, EdgeLabelEnum.VERSION.name()); if (nextVersionComponentIter != null && nextVersionComponentIter.hasNext()) { - Vertex nextVersionVertex = nextVersionComponentIter.next().inVertex(); + Vertex nextVersionVertex = nextVersionComponentIter.next().inVertex(); String fetchedVersion = (String) nextVersionVertex.property(GraphPropertyEnum.VERSION.getProperty()).value(); - String fetchedName = (String)nextVersionVertex.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty()).value(); + String fetchedName = (String) nextVersionVertex.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty()).value(); CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to checkout component {} with version {}. The component with name {} and version {} was fetched from graph as existing following version. ", toscaElementVertex.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME).toString(), toscaElementVertex.getMetadataProperty(GraphPropertyEnum.VERSION).toString(), fetchedName, fetchedVersion); result = Either.right(StorageOperationStatus.ENTITY_ALREADY_EXISTS); @@ -912,16 +938,22 @@ public class ToscaElementLifecycleOperation extends BaseOperation { } } if (result == null) { + Boolean isHighest = (Boolean) toscaElementVertex.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION); + GraphVertex prevVersionInCatalog = (isHighest != null && isHighest) ? null : toscaElementVertex; + StorageOperationStatus updateCatalogRes = updateEdgeToCatalogRoot(clonedVertex, prevVersionInCatalog); + if (updateCatalogRes != StorageOperationStatus.OK) { + return Either.right(updateCatalogRes); + } result = operation.getToscaElement(cloneResult.left().value().getUniqueId()); if (result.isRight()) { return result; } - ToscaElement toscaElement = result.left().value(); if (toscaElement.getToscaType() == ToscaElementTypeEnum.TopologyTemplate) { result = handleFixTopologyTemplate(toscaElementVertex, result, operation, clonedVertex, toscaElement); } } + return result; } @@ -952,7 +984,7 @@ public class ToscaElementLifecycleOperation extends BaseOperation { collectInstanceInputAndGroups(instInputs, instGroups, instArtifactsMap, origCompMap, isAddInstGroup, vfInst, clonedVertex); } needUpdateComposition = needUpdateComposition || fixToscaComponentName(vfInst, origCompMap); - if(needUpdateComposition){ + if (needUpdateComposition) { instancesMap.put(vfInst.getUniqueId(), vfInst); } } @@ -1010,8 +1042,8 @@ public class ToscaElementLifecycleOperation extends BaseOperation { } return result; } - - //TODO remove after jsonModelMigration + + // TODO remove after jsonModelMigration public boolean resolveToscaComponentName(ComponentInstanceDataDefinition vfInst, Map<String, ToscaElement> origCompMap) { return fixToscaComponentName(vfInst, origCompMap); } @@ -1026,7 +1058,7 @@ public class ToscaElementLifecycleOperation extends BaseOperation { Either<ToscaElement, StorageOperationStatus> origCompEither; if (vfInst.getOriginType() == null || vfInst.getOriginType().name().equals(OriginTypeEnum.VF.name())) { origCompEither = topologyTemplateOperation.getToscaElement(origCompUid); - }else{ + } else { origCompEither = nodeTypeOperation.getToscaElement(origCompUid); } if (origCompEither.isRight()) { @@ -1088,7 +1120,6 @@ public class ToscaElementLifecycleOperation extends BaseOperation { CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "before create group instance. "); List<GroupDataDefinition> filteredGroups = null; - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "check vf groups before filter. Size is {} ", filteredGroups == null ? 0 : filteredGroups.size()); if (origComp.getGroups() != null && !origComp.getGroups().isEmpty()) { filteredGroups = origComp.getGroups().values().stream().filter(g -> g.getType().equals(VF_MODULE)).collect(Collectors.toList()); @@ -1097,39 +1128,38 @@ public class ToscaElementLifecycleOperation extends BaseOperation { CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "check vf groups after filter. Size is {} ", filteredGroups == null ? 0 : filteredGroups.size()); if (CollectionUtils.isNotEmpty(filteredGroups)) { MapArtifactDataDefinition instArifacts = null; - if(!instArtifactsMap.containsKey(ciUid)){ - - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "istance artifacts not found "); - - Map<String, ArtifactDataDefinition> deploymentArtifacts = origComp.getDeploymentArtifacts(); - - - instArifacts = new MapArtifactDataDefinition(deploymentArtifacts); - addToscaDataDeepElementsBlockToToscaElement(clonedVertex, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, instArifacts, ciUid); - - instArtifactsMap.put(ciUid, instArifacts); - - }else{ + if (!instArtifactsMap.containsKey(ciUid)) { + + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "istance artifacts not found "); + + Map<String, ArtifactDataDefinition> deploymentArtifacts = origComp.getDeploymentArtifacts(); + + instArifacts = new MapArtifactDataDefinition(deploymentArtifacts); + addToscaDataDeepElementsBlockToToscaElement(clonedVertex, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, instArifacts, ciUid); + + instArtifactsMap.put(ciUid, instArifacts); + + } else { instArifacts = instArtifactsMap.get(ciUid); } - - if(instArifacts != null){ + + if (instArifacts != null) { Map<String, ArtifactDataDefinition> instDeplArtifMap = instArifacts.getMapToscaDataDefinition(); - + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "check group dep artifacts. Size is {} ", instDeplArtifMap == null ? 0 : instDeplArtifMap.values().size()); Map<String, GroupInstanceDataDefinition> groupInstanceToCreate = new HashMap<>(); - for(GroupDataDefinition group:filteredGroups){ + for (GroupDataDefinition group : filteredGroups) { CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "create new groupInstance {} ", group.getName()); GroupInstanceDataDefinition groupInstance = buildGroupInstanceDataDefinition(group, vfInst, instDeplArtifMap); List<String> artifactsUid = new ArrayList<>(); List<String> artifactsId = new ArrayList<>(); for (ArtifactDataDefinition artifact : instDeplArtifMap.values()) { - //CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "create new groupInstance {} ", artifact.getA); + // CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "create new groupInstance {} ", artifact.getA); Optional<String> op = group.getArtifacts().stream().filter(p -> p.equals(artifact.getGeneratedFromId())).findAny(); if (op.isPresent()) { artifactsUid.add(artifact.getArtifactUUID()); artifactsId.add(artifact.getUniqueId()); - + } } groupInstance.setGroupInstanceArtifacts(artifactsId); @@ -1138,7 +1168,7 @@ public class ToscaElementLifecycleOperation extends BaseOperation { } if (MapUtils.isNotEmpty(groupInstanceToCreate)) { instGroups.put(vfInst.getUniqueId(), new MapGroupsDataDefinition(groupInstanceToCreate)); - + } } } @@ -1195,6 +1225,10 @@ public class ToscaElementLifecycleOperation extends BaseOperation { CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to clone tosca element {} for certification. Sattus is {}. ", toscaElementVertex.getUniqueId(), result.right().value()); } else { clonedToscaElement = result.left().value(); + StorageOperationStatus updateEdgeToCatalog = updateEdgeToCatalogRoot(clonedToscaElement, toscaElementVertex); + if (updateEdgeToCatalog != StorageOperationStatus.OK) { + return Either.right(updateEdgeToCatalog); + } deleteResult = deleteAllPreviousNotCertifiedVersions(toscaElementVertex); if (deleteResult.isRight()) { CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete all previous npt certified versions of tosca element {}. Status is {}. ", toscaElementVertex.getUniqueId(), deleteResult.right().value()); @@ -1229,6 +1263,7 @@ public class ToscaElementLifecycleOperation extends BaseOperation { result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); } } + } if (result == null) { result = Either.left(clonedToscaElement); @@ -1436,13 +1471,12 @@ public class ToscaElementLifecycleOperation extends BaseOperation { return verticesToGetParameters; } - private String getNextCertifiedVersion(String version) { String[] versionParts = version.split(VERSION_DELIMETER_REGEXP); Integer nextMajorVersion = Integer.parseInt(versionParts[0]) + 1; return nextMajorVersion + VERSION_DELIMETER + "0"; } - + private String getNextVersion(String currVersion) { String[] versionParts = currVersion.split(VERSION_DELIMETER_REGEXP); Integer minorVersion = Integer.parseInt(versionParts[1]) + 1; @@ -1466,7 +1500,7 @@ public class ToscaElementLifecycleOperation extends BaseOperation { return false; } - public Either<ToscaElement,StorageOperationStatus> forceCerificationOfToscaElement(String toscaElementId, String modifierId, String ownerId, String currVersion) { + public Either<ToscaElement, StorageOperationStatus> forceCerificationOfToscaElement(String toscaElementId, String modifierId, String ownerId, String currVersion) { Either<GraphVertex, StorageOperationStatus> resultUpdate = null; Either<ToscaElement, StorageOperationStatus> result = null; GraphVertex toscaElement = null; @@ -1514,23 +1548,55 @@ public class ToscaElementLifecycleOperation extends BaseOperation { 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); + 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) { - 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; + } + + private StorageOperationStatus updateEdgeToCatalogRoot(GraphVertex newVersionV, GraphVertex prevVersionV) { + Either<GraphVertex, TitanOperationStatus> catalog = titanDao.getVertexByLabel(VertexTypeEnum.CATALOG_ROOT); + if (catalog.isRight()) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch catalog vertex. error {}", catalog.right().value()); + return DaoStatusConverter.convertTitanStatusToStorageStatus(catalog.right().value()); + } + GraphVertex catalogV = catalog.left().value(); + if (newVersionV != null) { + Boolean isAbstract = (Boolean) newVersionV.getMetadataProperty(GraphPropertyEnum.IS_ABSTRACT); + if (isAbstract == null || !isAbstract) { + // no new vertex, only delete previous + TitanOperationStatus result = titanDao.createEdge(catalogV, newVersionV, EdgeLabelEnum.CATALOG_ELEMENT, null); + if (result != TitanOperationStatus.OK) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create edge from {} to catalog vertex. error {}", newVersionV.getUniqueId(), result); + return DaoStatusConverter.convertTitanStatusToStorageStatus(result); } } - if (result == null) { - result = StorageOperationStatus.OK; + } + if (prevVersionV != null) { + Boolean isAbstract = (Boolean) prevVersionV.getMetadataProperty(GraphPropertyEnum.IS_ABSTRACT); + if (isAbstract == null || !isAbstract) { + // if prev == null -> new resource was added + Either<Edge, TitanOperationStatus> deleteResult = titanDao.deleteEdge(catalogV, prevVersionV, EdgeLabelEnum.CATALOG_ELEMENT); + if (deleteResult.isRight()) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete edge from {} to catalog vertex. error {}", prevVersionV.getUniqueId(), deleteResult.right().value()); + return DaoStatusConverter.convertTitanStatusToStorageStatus(deleteResult.right().value()); + } } - return result; + } + return StorageOperationStatus.OK; } } 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 ec55ddaf3b..0cb71eeab3 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 @@ -33,12 +33,15 @@ import java.util.Set; import org.apache.tinkerpop.gremlin.structure.Direction; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.apache.tinkerpop.gremlin.structure.VertexProperty; import org.openecomp.sdc.be.config.ConfigurationManager; 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; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils; +import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; @@ -50,6 +53,7 @@ import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.catalog.CatalogComponent; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.category.SubCategoryDefinition; import org.openecomp.sdc.be.model.jsontitan.datamodel.NodeType; @@ -65,6 +69,7 @@ import org.openecomp.sdc.common.util.ValidationUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.util.StopWatch; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; @@ -72,1143 +77,1244 @@ import com.google.gson.reflect.TypeToken; import fj.data.Either; public abstract class ToscaElementOperation extends BaseOperation { - private static Logger log = LoggerFactory.getLogger(ToscaElementOperation.class.getName()); - - private static final Gson gson = new Gson(); - - protected Gson getGson() { - return gson; - } - - @Autowired - protected CategoryOperation categoryOperation; - - protected Either<GraphVertex, StorageOperationStatus> getComponentByLabelAndId(String uniqueId, ToscaElementTypeEnum nodeType, JsonParseFlagEnum parseFlag) { - - Map<GraphPropertyEnum, Object> propertiesToMatch = new HashMap<GraphPropertyEnum, Object>(); - propertiesToMatch.put(GraphPropertyEnum.UNIQUE_ID, uniqueId); - - VertexTypeEnum vertexType = ToscaElementTypeEnum.getVertexTypeByToscaType(nodeType); - Either<List<GraphVertex>, TitanOperationStatus> getResponse = titanDao.getByCriteria(vertexType, propertiesToMatch, parseFlag); - if (getResponse.isRight()) { - log.debug("Couldn't fetch component with type {} and unique id {}, error: {}", vertexType, uniqueId, getResponse.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getResponse.right().value())); - - } - List<GraphVertex> componentList = getResponse.left().value(); - if (componentList.isEmpty()) { - log.debug("Component with type {} and unique id {} was not found", vertexType, uniqueId); - return Either.right(StorageOperationStatus.NOT_FOUND); - } - GraphVertex vertexG = componentList.get(0); - return Either.left(vertexG); - } - - public Either<ToscaElement, StorageOperationStatus> getToscaElement(String uniqueId) { - return getToscaElement(uniqueId, new ComponentParametersView()); - } - - public Either<GraphVertex, StorageOperationStatus> markComponentToDelete(GraphVertex componentToDelete) { - Either<GraphVertex, StorageOperationStatus> result = null; - - Boolean isDeleted = (Boolean) componentToDelete.getMetadataProperty(GraphPropertyEnum.IS_DELETED); - if (isDeleted != null && isDeleted && !(Boolean) componentToDelete.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION)) { - // component already marked for delete - result = Either.left(componentToDelete); - return result; - } else { - - componentToDelete.addMetadataProperty(GraphPropertyEnum.IS_DELETED, Boolean.TRUE); - componentToDelete.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); - - Either<GraphVertex, TitanOperationStatus> updateNode = titanDao.updateVertex(componentToDelete); - - StorageOperationStatus updateComponent; - if (updateNode.isRight()) { - log.debug("Failed to update component {}. status is {}", componentToDelete.getUniqueId(), updateNode.right().value()); - updateComponent = DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value()); - result = Either.right(updateComponent); - return result; - } - - result = Either.left(componentToDelete); - return result; - } - } - - /** - * Performs a shadow clone of previousToscaElement - * - * @param previousToscaElement - * @param nextToscaElement - * @param user - * @return - */ - public Either<GraphVertex, StorageOperationStatus> cloneToscaElement(GraphVertex previousToscaElement, GraphVertex nextToscaElement, GraphVertex user) { - - Either<GraphVertex, StorageOperationStatus> result = null; - GraphVertex createdToscaElementVertex = null; - TitanOperationStatus status; - - Either<GraphVertex, TitanOperationStatus> createNextVersionRes = titanDao.createVertex(nextToscaElement); - if (createNextVersionRes.isRight()) { - status = createNextVersionRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create tosca element vertex {} with version {} on graph. Status is {}. ", previousToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), - previousToscaElement.getMetadataProperty(GraphPropertyEnum.VERSION), status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - if (result == null) { - createdToscaElementVertex = createNextVersionRes.left().value(); - Map<EdgePropertyEnum, Object> properties = new HashMap<EdgePropertyEnum, Object>(); - properties.put(EdgePropertyEnum.STATE, createdToscaElementVertex.getMetadataProperty(GraphPropertyEnum.STATE)); - status = titanDao.createEdge(user.getVertex(), createdToscaElementVertex.getVertex(), EdgeLabelEnum.STATE, properties); - if (status != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge with label {} from user vertex {} to tosca element vertex {} on graph. Status is {}. ", EdgeLabelEnum.STATE, user.getUniqueId(), - previousToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - if (result == null) { - status = titanDao.createEdge(user.getVertex(), createdToscaElementVertex.getVertex(), EdgeLabelEnum.LAST_MODIFIER, new HashMap<>()); - if (status != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge with label {} from user vertex {} to tosca element vertex {} on graph. Status is {}. ", EdgeLabelEnum.LAST_MODIFIER, user.getUniqueId(), - nextToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - if (result == null) { - status = titanDao.createEdge(user.getVertex(), createdToscaElementVertex.getVertex(), EdgeLabelEnum.CREATOR, new HashMap<>()); - if (status != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge with label {} from user vertex {} to tosca element vertex {} on graph. Status is {}. ", EdgeLabelEnum.CREATOR, user.getUniqueId(), - nextToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - if (result == null) { - Iterator<Edge> edgesToCopyIter = previousToscaElement.getVertex().edges(Direction.OUT); - while (edgesToCopyIter.hasNext()) { - Edge currEdge = edgesToCopyIter.next(); - Vertex currVertex = currEdge.inVertex(); - // if(EdgeLabelEnum.getEdgeLabelEnum(currEdge.label()).equals(EdgeLabelEnum.VERSION)){ - // continue; - // } - status = titanDao.createEdge(createdToscaElementVertex.getVertex(), currVertex, EdgeLabelEnum.getEdgeLabelEnum(currEdge.label()), currEdge); - if (status != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge with label {} from tosca element vertex {} to vertex with label {} on graph. Status is {}. ", currEdge.label(), createdToscaElementVertex.getUniqueId(), - currVertex.property(GraphPropertyEnum.LABEL.getProperty()), status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - break; - } - } - } - - if (result == null) { - result = Either.left(createdToscaElementVertex); - } else { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to clone tosca element {} with the name {}. ", previousToscaElement.getUniqueId(), previousToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME)); - } - return result; - } - - protected TitanOperationStatus setLastModifierFromGraph(GraphVertex componentV, ToscaElement toscaElement) { - Either<GraphVertex, TitanOperationStatus> parentVertex = titanDao.getParentVertex(componentV, EdgeLabelEnum.LAST_MODIFIER, JsonParseFlagEnum.NoParse); - if (parentVertex.isRight()) { - log.debug("Failed to fetch last modifier for tosca element with id {} error {}", componentV.getUniqueId(), parentVertex.right().value()); - return parentVertex.right().value(); - } - GraphVertex userV = parentVertex.left().value(); - String userId = (String) userV.getMetadataProperty(GraphPropertyEnum.USERID); - toscaElement.setLastUpdaterUserId(userId); - toscaElement.setLastUpdaterFullName(buildFullName(userV)); - return TitanOperationStatus.OK; - } - - public String buildFullName(GraphVertex userV) { - - String fullName = (String) userV.getMetadataProperty(GraphPropertyEnum.FIRST_NAME); - if (fullName == null) { - fullName = ""; - } else { - fullName = fullName + " "; - } - String lastName = (String) userV.getMetadataProperty(GraphPropertyEnum.LAST_NAME); - if (lastName != null) { - fullName += lastName; - } - return fullName; - } - - protected TitanOperationStatus setCreatorFromGraph(GraphVertex componentV, ToscaElement toscaElement) { - Either<GraphVertex, TitanOperationStatus> parentVertex = titanDao.getParentVertex(componentV, EdgeLabelEnum.CREATOR, JsonParseFlagEnum.NoParse); - if (parentVertex.isRight()) { - log.debug("Failed to fetch creator for tosca element with id {} error {}", componentV.getUniqueId(), parentVertex.right().value()); - return parentVertex.right().value(); - } - GraphVertex userV = parentVertex.left().value(); - String creatorUserId = (String) userV.getMetadataProperty(GraphPropertyEnum.USERID); - toscaElement.setCreatorUserId(creatorUserId); - toscaElement.setCreatorFullName(buildFullName(userV)); - - return TitanOperationStatus.OK; - } - - protected <T extends ToscaElement> T getResourceMetaDataFromResource(T toscaElement) { - if (toscaElement.getNormalizedName() == null || toscaElement.getNormalizedName().isEmpty()) { - toscaElement.setNormalizedName(ValidationUtils.normaliseComponentName(toscaElement.getName())); - } - if (toscaElement.getSystemName() == null || toscaElement.getSystemName().isEmpty()) { - toscaElement.setSystemName(ValidationUtils.convertToSystemName(toscaElement.getName())); - } - - LifecycleStateEnum lifecycleStateEnum = toscaElement.getLifecycleState(); - if (lifecycleStateEnum == null) { - toscaElement.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - } - long currentDate = System.currentTimeMillis(); - if (toscaElement.getCreationDate() == null) { - toscaElement.setCreationDate(currentDate); - } - toscaElement.setLastUpdateDate(currentDate); - - return toscaElement; - } - - protected void fillCommonMetadata(GraphVertex nodeTypeVertex, ToscaElement toscaElement) { - if (toscaElement.isHighestVersion() == null) { - toscaElement.setHighestVersion(true); - } - nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_DELETED, toscaElement.getMetadataValue(JsonPresentationFields.IS_DELETED)); - nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION, toscaElement.getMetadataValueOrDefault(JsonPresentationFields.HIGHEST_VERSION, Boolean.TRUE)); - nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.STATE, toscaElement.getMetadataValue(JsonPresentationFields.LIFECYCLE_STATE)); - nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.RESOURCE_TYPE, toscaElement.getMetadataValue(JsonPresentationFields.RESOURCE_TYPE)); - nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.VERSION, toscaElement.getMetadataValue(JsonPresentationFields.VERSION)); - nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME, toscaElement.getMetadataValue(JsonPresentationFields.NORMALIZED_NAME)); - nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, toscaElement.getMetadataValue(JsonPresentationFields.UNIQUE_ID)); - nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaElement.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME)); - nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.UUID, toscaElement.getMetadataValue(JsonPresentationFields.UUID)); - nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_ABSTRACT, toscaElement.getMetadataValue(JsonPresentationFields.IS_ABSTRACT)); - nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.INVARIANT_UUID, toscaElement.getMetadataValue(JsonPresentationFields.INVARIANT_UUID)); - nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.NAME, toscaElement.getMetadataValue(JsonPresentationFields.NAME)); - nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.SYSTEM_NAME, toscaElement.getMetadataValue(JsonPresentationFields.SYSTEM_NAME)); - toscaElement.getMetadata().entrySet().stream().filter(e -> e.getValue() != null).forEach(e -> nodeTypeVertex.setJsonMetadataField(JsonPresentationFields.getByPresentation(e.getKey()), e.getValue())); - - nodeTypeVertex.setUniqueId(toscaElement.getUniqueId()); - nodeTypeVertex.setType(toscaElement.getComponentType()); - - } - - protected StorageOperationStatus assosiateToUsers(GraphVertex nodeTypeVertex, ToscaElement toscaElement) { - // handle user - String userId = toscaElement.getCreatorUserId(); - - Either<GraphVertex, TitanOperationStatus> findUser = findUserVertex(userId); - - if (findUser.isRight()) { - TitanOperationStatus status = findUser.right().value(); - log.error("Cannot find user {} in the graph. status is {}", userId, status); - return DaoStatusConverter.convertTitanStatusToStorageStatus(status); - - } - GraphVertex creatorVertex = findUser.left().value(); - GraphVertex updaterVertex = creatorVertex; - String updaterId = toscaElement.getLastUpdaterUserId(); - if (updaterId != null && !updaterId.equals(userId)) { - findUser = findUserVertex(updaterId); - if (findUser.isRight()) { - TitanOperationStatus status = findUser.right().value(); - log.error("Cannot find user {} in the graph. status is {}", userId, status); - return DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } else { - updaterVertex = findUser.left().value(); - } - } - Map<EdgePropertyEnum, Object> props = new HashMap<EdgePropertyEnum, Object>(); - props.put(EdgePropertyEnum.STATE, (String) toscaElement.getMetadataValue(JsonPresentationFields.LIFECYCLE_STATE)); - - TitanOperationStatus result = titanDao.createEdge(updaterVertex, nodeTypeVertex, EdgeLabelEnum.STATE, props); - log.debug("After associating user {} to resource {}. Edge type is {}", updaterVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.STATE); - if (TitanOperationStatus.OK != result) { - return DaoStatusConverter.convertTitanStatusToStorageStatus(result); - } - result = titanDao.createEdge(updaterVertex, nodeTypeVertex, EdgeLabelEnum.LAST_MODIFIER, null); - log.debug("After associating user {} to resource {}. Edge type is {}", updaterVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER); - if (!result.equals(TitanOperationStatus.OK)) { - log.error("Failed to associate user {} to resource {}. Edge type is {}", updaterVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER); - return DaoStatusConverter.convertTitanStatusToStorageStatus(result); - } - - toscaElement.setLastUpdaterUserId(toscaElement.getCreatorUserId()); - toscaElement.setLastUpdaterFullName(toscaElement.getCreatorFullName()); - - result = titanDao.createEdge(creatorVertex, nodeTypeVertex, EdgeLabelEnum.CREATOR, null); - log.debug("After associating user {} to resource {}. Edge type is {} ", creatorVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.CREATOR); - if (!result.equals(TitanOperationStatus.OK)) { - log.error("Failed to associate user {} to resource {}. Edge type is {} ", creatorVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.CREATOR); - return DaoStatusConverter.convertTitanStatusToStorageStatus(result); - } - return StorageOperationStatus.OK; - } - - protected StorageOperationStatus assosiateResourceMetadataToCategory(GraphVertex nodeTypeVertex, ToscaElement nodeType) { - String subcategoryName = nodeType.getCategories().get(0).getSubcategories().get(0).getName(); - String categoryName = nodeType.getCategories().get(0).getName(); - Either<GraphVertex, StorageOperationStatus> getCategoryVertex = getResourceCategoryVertex(nodeType.getUniqueId(), subcategoryName, categoryName); - - if (getCategoryVertex.isRight()) { - return getCategoryVertex.right().value(); - } - - GraphVertex subCategoryV = getCategoryVertex.left().value(); - - TitanOperationStatus createEdge = titanDao.createEdge(nodeTypeVertex, subCategoryV, EdgeLabelEnum.CATEGORY, new HashMap<>()); - if (createEdge != TitanOperationStatus.OK) { - log.trace("Failed to associate resource {} to category {} with id {}", nodeType.getUniqueId(), subcategoryName, subCategoryV.getUniqueId()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge); - } - return StorageOperationStatus.OK; - } - - protected Either<GraphVertex, StorageOperationStatus> getResourceCategoryVertex(String elementId, String subcategoryName, String categoryName) { - Either<GraphVertex, StorageOperationStatus> category = categoryOperation.getCategory(categoryName, VertexTypeEnum.RESOURCE_CATEGORY); - if (category.isRight()) { - log.trace("Failed to fetch category {} for resource {} error {}", categoryName, elementId, category.right().value()); - return Either.right(category.right().value()); - } - GraphVertex categoryV = category.left().value(); - - if (subcategoryName != null) { - Either<GraphVertex, StorageOperationStatus> subCategory = categoryOperation.getSubCategoryForCategory(categoryV, subcategoryName); - if (subCategory.isRight()) { - log.trace("Failed to fetch subcategory {} of category for resource {} error {}", subcategoryName, categoryName, elementId, subCategory.right().value()); - return Either.right(subCategory.right().value()); - } - - GraphVertex subCategoryV = subCategory.left().value(); - return Either.left(subCategoryV); - } - return Either.left(categoryV); - } - - private StorageOperationStatus associateArtifactsToResource(GraphVertex nodeTypeVertex, ToscaElement toscaElement) { - Map<String, ArtifactDataDefinition> artifacts = toscaElement.getArtifacts(); - Either<GraphVertex, StorageOperationStatus> status; - if (artifacts != null) { - artifacts.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> { - String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase()); - a.setUniqueId(uniqueId); - }); - status = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.ARTIFACTS, EdgeLabelEnum.ARTIFACTS, artifacts); - if (status.isRight()) { - return status.right().value(); - } - } - Map<String, ArtifactDataDefinition> toscaArtifacts = toscaElement.getToscaArtifacts(); - if (toscaArtifacts != null) { - toscaArtifacts.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> { - String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase()); - a.setUniqueId(uniqueId); - }); - status = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.TOSCA_ARTIFACTS, EdgeLabelEnum.TOSCA_ARTIFACTS, toscaArtifacts); - if (status.isRight()) { - return status.right().value(); - } - } - Map<String, ArtifactDataDefinition> deploymentArtifacts = toscaElement.getDeploymentArtifacts(); - if (deploymentArtifacts != null) { - deploymentArtifacts.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> { - String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase()); - a.setUniqueId(uniqueId); - }); - status = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.DEPLOYMENT_ARTIFACTS, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS, deploymentArtifacts); - if (status.isRight()) { - return status.right().value(); - } - } - return StorageOperationStatus.OK; - } - - protected TitanOperationStatus disassociateAndDeleteCommonElements(GraphVertex toscaElementVertex) { - TitanOperationStatus status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ARTIFACTS); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disaccociate artifact for {} error {}", toscaElementVertex.getUniqueId(), status); - return status; - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.TOSCA_ARTIFACTS); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disaccociate tosca artifact for {} error {}", toscaElementVertex.getUniqueId(), status); - return status; - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to deployment artifact for {} error {}", toscaElementVertex.getUniqueId(), status); - return status; - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.PROPERTIES); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disaccociate properties for {} error {}", toscaElementVertex.getUniqueId(), status); - return status; - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ATTRIBUTES); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disaccociate attributes for {} error {}", toscaElementVertex.getUniqueId(), status); - return status; - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ADDITIONAL_INFORMATION); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disaccociate additional information for {} error {}", toscaElementVertex.getUniqueId(), status); - return status; - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CAPABILITIES); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disaccociate capabilities for {} error {}", toscaElementVertex.getUniqueId(), status); - return status; - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.REQUIREMENTS); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disaccociate requirements for {} error {}", toscaElementVertex.getUniqueId(), status); - return status; - } - return TitanOperationStatus.OK; - } - - protected StorageOperationStatus assosiateCommonForToscaElement(GraphVertex nodeTypeVertex, ToscaElement toscaElement, List<GraphVertex> derivedResources) { - - StorageOperationStatus associateUsers = assosiateToUsers(nodeTypeVertex, toscaElement); - if (associateUsers != StorageOperationStatus.OK) { - return associateUsers; - } - StorageOperationStatus associateArtifacts = associateArtifactsToResource(nodeTypeVertex, toscaElement); - if (associateArtifacts != StorageOperationStatus.OK) { - return associateArtifacts; - } - StorageOperationStatus associateProperties = associatePropertiesToResource(nodeTypeVertex, toscaElement, derivedResources); - if (associateProperties != StorageOperationStatus.OK) { - return associateProperties; - } - StorageOperationStatus associateAdditionaInfo = associateAdditionalInfoToResource(nodeTypeVertex, toscaElement); - if (associateAdditionaInfo != StorageOperationStatus.OK) { - return associateAdditionaInfo; - } - - return StorageOperationStatus.OK; - } - - protected StorageOperationStatus associatePropertiesToResource(GraphVertex nodeTypeVertex, ToscaElement nodeType, List<GraphVertex> derivedResources) { - // Note : currently only one derived supported!!!! - Either<Map<String, PropertyDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.PROPERTIES); - if (dataFromDerived.isRight()) { - return dataFromDerived.right().value(); - } - Map<String, PropertyDataDefinition> propertiesAll = dataFromDerived.left().value(); - - Map<String, PropertyDataDefinition> properties = nodeType.getProperties(); - - if (properties != null) { - properties.values().stream().filter(p -> p.getUniqueId() == null).forEach(p -> { - String uid = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId(), p.getName()); - p.setUniqueId(uid); - }); - - Either<Map<String, PropertyDataDefinition>, String> eitherMerged = ToscaDataDefinition.mergeDataMaps(propertiesAll, properties); - if (eitherMerged.isRight()) { - // TODO re-factor error handling - moving BL to operation resulted in loss of info about the invalid property - log.debug("property {} cannot be overriden", eitherMerged.right().value()); - return StorageOperationStatus.INVALID_PROPERTY; - } - } - if (!propertiesAll.isEmpty()) { - Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.PROPERTIES, EdgeLabelEnum.PROPERTIES, propertiesAll); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus associateAdditionalInfoToResource(GraphVertex nodeTypeVertex, ToscaElement nodeType) { - Map<String, AdditionalInfoParameterDataDefinition> additionalInformation = nodeType.getAdditionalInformation(); - if (additionalInformation != null) { - Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.ADDITIONAL_INFORMATION, EdgeLabelEnum.ADDITIONAL_INFORMATION, additionalInformation); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - protected <T extends ToscaDataDefinition> Either<Map<String, T>, StorageOperationStatus> getDataFromDerived(List<GraphVertex> derivedResources, EdgeLabelEnum edge) { - Map<String, T> propertiesAll = new HashMap<>(); - - if (derivedResources != null && !derivedResources.isEmpty()) { - for (GraphVertex derived : derivedResources) { - Either<List<GraphVertex>, TitanOperationStatus> derivedProperties = titanDao.getChildrenVertecies(derived, edge, JsonParseFlagEnum.ParseJson); - if (derivedProperties.isRight()) { - if (derivedProperties.right().value() != TitanOperationStatus.NOT_FOUND) { - log.debug("Failed to get properties for derived from {} error {}", derived.getUniqueId(), derivedProperties.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(derivedProperties.right().value())); - } else { - continue; - } - } - List<GraphVertex> propList = derivedProperties.left().value(); - for (GraphVertex propV : propList) { - Map<String, T> propertiesFromDerived = (Map<String, T>) propV.getJson(); - if (propertiesFromDerived != null) { - propertiesFromDerived.entrySet().forEach(x -> x.getValue().setOwnerIdIfEmpty(derived.getUniqueId())); - propertiesAll.putAll(propertiesFromDerived); - } - } - } - } - return Either.left(propertiesAll); - } - - protected TitanOperationStatus setArtifactsFromGraph(GraphVertex componentV, ToscaElement toscaElement) { - Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.ARTIFACTS); - if (result.isLeft()) { - toscaElement.setArtifacts(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - result = getDataFromGraph(componentV, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS); - if (result.isLeft()) { - toscaElement.setDeploymentArtifacts(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - result = getDataFromGraph(componentV, EdgeLabelEnum.TOSCA_ARTIFACTS); - if (result.isLeft()) { - toscaElement.setToscaArtifacts(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - return TitanOperationStatus.OK; - } - - protected TitanOperationStatus setAllVersions(GraphVertex componentV, ToscaElement toscaElement) { - Map<String, String> allVersion = new HashMap<>(); - - allVersion.put((String) componentV.getMetadataProperty(GraphPropertyEnum.VERSION), componentV.getUniqueId()); - ArrayList<GraphVertex> allChildrenAndParants = new ArrayList<GraphVertex>(); - Either<GraphVertex, TitanOperationStatus> childResourceRes = titanDao.getChildVertex(componentV, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); - while (childResourceRes.isLeft()) { - GraphVertex child = childResourceRes.left().value(); - allChildrenAndParants.add(child); - childResourceRes = titanDao.getChildVertex(child, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); - } - TitanOperationStatus operationStatus = childResourceRes.right().value(); - - if (operationStatus != TitanOperationStatus.NOT_FOUND) { - return operationStatus; - } else { - Either<GraphVertex, TitanOperationStatus> parentResourceRes = titanDao.getParentVertex(componentV, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); - while (parentResourceRes.isLeft()) { - GraphVertex parent = parentResourceRes.left().value(); - allChildrenAndParants.add(parent); - parentResourceRes = titanDao.getParentVertex(parent, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); - } - operationStatus = parentResourceRes.right().value(); - if (operationStatus != TitanOperationStatus.NOT_FOUND) { - return operationStatus; - } else { - allChildrenAndParants.stream().filter(vertex -> { - Boolean isDeleted = (Boolean) vertex.getMetadataProperty(GraphPropertyEnum.IS_DELETED); - return (isDeleted == null || isDeleted == false); - }).forEach(vertex -> allVersion.put((String) vertex.getMetadataProperty(GraphPropertyEnum.VERSION), vertex.getUniqueId())); - - toscaElement.setAllVersions(allVersion); - return TitanOperationStatus.OK; - } - } - } - - protected <T extends ToscaElement> Either<List<T>, StorageOperationStatus> getFollowedComponent(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, ComponentTypeEnum neededType) { - - Either<List<T>, StorageOperationStatus> result = null; - - Map<GraphPropertyEnum, Object> props = null; - - if (userId != null) { - props = new HashMap<>(); - // for Designer retrieve specific user - props.put(GraphPropertyEnum.USERID, userId); - } - // in case of user id == null -> get all users by label - // for Tester and Admin retrieve all users - Either<List<GraphVertex>, TitanOperationStatus> usersByCriteria = titanDao.getByCriteria(VertexTypeEnum.USER, props, JsonParseFlagEnum.NoParse); - if (usersByCriteria.isRight()) { - log.debug("Failed to fetch users by criteria {} error {}", props, usersByCriteria.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(usersByCriteria.right().value())); - } - List<GraphVertex> users = usersByCriteria.left().value(); - - List<T> components = new ArrayList<>(); - List<T> componentsPerUser; - for (GraphVertex userV : users) { - - HashSet<String> ids = new HashSet<String>(); - Either<List<GraphVertex>, TitanOperationStatus> childrenVertecies = titanDao.getChildrenVertecies(userV, EdgeLabelEnum.STATE, JsonParseFlagEnum.NoParse); - if (childrenVertecies.isRight() && childrenVertecies.right().value() != TitanOperationStatus.NOT_FOUND) { - log.debug("Failed to fetch children vertices for user {} by edge {} error {}", userV.getMetadataProperty(GraphPropertyEnum.USERID), EdgeLabelEnum.STATE, childrenVertecies.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(childrenVertecies.right().value())); - } - - // get all resource with current state - if (childrenVertecies.isLeft()) { - componentsPerUser = fetchComponents(lifecycleStates, childrenVertecies.left().value(), neededType, EdgeLabelEnum.STATE); - - if (componentsPerUser != null) { - for (T comp : componentsPerUser) { - ids.add(comp.getUniqueId()); - components.add(comp); - } - } - } - if (lastStateStates != null && !lastStateStates.isEmpty()) { - // get all resource with last state - childrenVertecies = titanDao.getChildrenVertecies(userV, EdgeLabelEnum.LAST_STATE, JsonParseFlagEnum.NoParse); - if (childrenVertecies.isRight() && childrenVertecies.right().value() != TitanOperationStatus.NOT_FOUND) { - log.debug("Failed to fetch children vertices for user {} by edge {} error {}", userV.getMetadataProperty(GraphPropertyEnum.USERID), EdgeLabelEnum.LAST_STATE, childrenVertecies.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(childrenVertecies.right().value())); - } - if (childrenVertecies.isLeft()) { - boolean isFirst; - componentsPerUser = fetchComponents(lastStateStates, childrenVertecies.left().value(), neededType, EdgeLabelEnum.LAST_STATE); - if (componentsPerUser != null) { - for (T comp : componentsPerUser) { - isFirst = true; - - if (ids.contains(comp.getUniqueId())) { - isFirst = false; - } - if (isFirst == true) { - components.add(comp); - } - - } - } - } - } - - } // whlile users - ; - result = Either.left(components); - return result; - - } - - private <T extends ToscaElement> List<T> fetchComponents(Set<LifecycleStateEnum> lifecycleStates, List<GraphVertex> vertices, ComponentTypeEnum neededType, EdgeLabelEnum edgelabel) { - List<T> components = new ArrayList<>(); - for (GraphVertex node : vertices) { - - Iterator<Edge> edges = node.getVertex().edges(Direction.IN, edgelabel.name()); - while (edges.hasNext()) { - Edge edge = edges.next(); - String stateStr = (String) titanDao.getProperty(edge, EdgePropertyEnum.STATE); - - LifecycleStateEnum nodeState = LifecycleStateEnum.findState(stateStr); - if (nodeState == null) { - log.debug("no supported STATE {} for element {}", stateStr, node.getUniqueId()); - continue; - } - if (lifecycleStates != null && lifecycleStates.contains(nodeState)) { - - Boolean isDeleted = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_DELETED); - if (isDeleted != null && isDeleted) { - log.trace("Deleted element {}, discard", node.getUniqueId()); - continue; - } - - Boolean isHighest = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION); - if (isHighest) { - - ComponentTypeEnum componentType = node.getType(); - // get only latest versions - - if (componentType == null) { - log.debug("No supported type {} for vertex {}", componentType, node.getUniqueId()); - continue; - } - if (neededType == componentType) { - switch (componentType) { - case SERVICE: - case PRODUCT: - handleNode(components, node, componentType); - break; - case RESOURCE: - Boolean isAbtract = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_ABSTRACT); - if (isAbtract == null || false == isAbtract) { - handleNode(components, node, componentType); - } // if not abstract - break; - default: - log.debug("not supported node type {}", componentType); - break; - }// case - } // needed type - } - } // if - } // while edges - } // while resources - return components; - } - - protected <T extends ToscaElement> void handleNode(List<T> components, GraphVertex vertexComponent, ComponentTypeEnum nodeType) { - - Either<T, StorageOperationStatus> component = getLightComponent(vertexComponent, nodeType, new ComponentParametersView(true)); - if (component.isRight()) { - log.debug("Failed to get component for id = {} error : {} skip resource", vertexComponent.getUniqueId(), component.right().value()); - } else { - components.add(component.left().value()); - } - } - - protected <T extends ToscaElement> Either<T, StorageOperationStatus> getLightComponent(String componentUid, ComponentTypeEnum nodeType, ComponentParametersView parametersFilter) { - Either<GraphVertex, TitanOperationStatus> getVertexRes = titanDao.getVertexById(componentUid); - if (getVertexRes.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexRes.right().value())); - } - return getLightComponent(getVertexRes.left().value(), nodeType, parametersFilter); - } - - protected <T extends ToscaElement> Either<T, StorageOperationStatus> getLightComponent(GraphVertex vertexComponent, ComponentTypeEnum nodeType, ComponentParametersView parametersFilter) { - - log.trace("Starting to build light component of type {}, id {}", nodeType, vertexComponent.getUniqueId()); - - titanDao.parseVertexProperties(vertexComponent, JsonParseFlagEnum.ParseMetadata); - - T toscaElement = convertToComponent(vertexComponent); - - TitanOperationStatus status = setCreatorFromGraph(vertexComponent, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - - status = setLastModifierFromGraph(vertexComponent, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = setCategoriesFromGraph(vertexComponent, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - if (!parametersFilter.isIgnoreAllVersions()) { - status = setAllVersions(vertexComponent, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - if (!parametersFilter.isIgnoreCapabilities()) { - status = setCapabilitiesFromGraph(vertexComponent, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - if (!parametersFilter.isIgnoreRequirements()) { - status = setRequirementsFromGraph(vertexComponent, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - log.debug("Ended to build light component of type {}, id {}", nodeType, vertexComponent.getUniqueId()); - return Either.left(toscaElement); - } - - @SuppressWarnings("unchecked") - protected <T extends ToscaElement> T convertToComponent(GraphVertex componentV) { - ToscaElement toscaElement = null; - VertexTypeEnum label = componentV.getLabel(); - switch (label) { - case NODE_TYPE: - toscaElement = new NodeType(); - break; - case TOPOLOGY_TEMPLATE: - toscaElement = new TopologyTemplate(); - break; - default: - log.debug("Not supported tosca type {}", label); - break; - } - - Map<String, Object> jsonMetada = componentV.getMetadataJson(); - if (toscaElement != null) { - toscaElement.setMetadata(jsonMetada); - } - return (T) toscaElement; - } - - protected TitanOperationStatus setResourceCategoryFromGraph(GraphVertex componentV, ToscaElement toscaElement) { - List<CategoryDefinition> categories = new ArrayList<>(); - SubCategoryDefinition subcategory; - - Either<GraphVertex, TitanOperationStatus> childVertex = titanDao.getChildVertex(componentV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse); - if (childVertex.isRight()) { - log.debug("failed to fetch {} for tosca element with id {}, error {}", EdgeLabelEnum.CATEGORY, componentV.getUniqueId(), childVertex.right().value()); - return childVertex.right().value(); - } - GraphVertex subCategoryV = childVertex.left().value(); - Map<GraphPropertyEnum, Object> metadataProperties = subCategoryV.getMetadataProperties(); - subcategory = new SubCategoryDefinition(); - subcategory.setUniqueId(subCategoryV.getUniqueId()); - subcategory.setNormalizedName((String) metadataProperties.get(GraphPropertyEnum.NORMALIZED_NAME)); - subcategory.setName((String) metadataProperties.get(GraphPropertyEnum.NAME)); - - Type listTypeSubcat = new TypeToken<List<String>>() { - }.getType(); - List<String> iconsfromJsonSubcat = getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.ICONS), listTypeSubcat); - subcategory.setIcons(iconsfromJsonSubcat); - - Either<GraphVertex, TitanOperationStatus> parentVertex = titanDao.getParentVertex(subCategoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse); - if (parentVertex.isRight()) { - log.debug("failed to fetch {} for category with id {}, error {}", EdgeLabelEnum.SUB_CATEGORY, subCategoryV.getUniqueId(), parentVertex.right().value()); - return childVertex.right().value(); - } - GraphVertex categoryV = parentVertex.left().value(); - metadataProperties = categoryV.getMetadataProperties(); - - CategoryDefinition category = new CategoryDefinition(); - 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(); - List<String> iconsfromJsonCat = getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.ICONS), listTypeCat); - category.setIcons(iconsfromJsonCat); - - category.addSubCategory(subcategory); - categories.add(category); - toscaElement.setCategories(categories); - - return TitanOperationStatus.OK; - } - - public <T extends ToscaElement> Either<T, StorageOperationStatus> updateToscaElement(T toscaElementToUpdate, GraphVertex elementV, ComponentParametersView filterResult) { - Either<T, StorageOperationStatus> result = null; - - log.debug("In updateToscaElement. received component uid = {}", (toscaElementToUpdate == null ? null : toscaElementToUpdate.getUniqueId())); - if (toscaElementToUpdate == null) { - log.error("Service object is null"); - result = Either.right(StorageOperationStatus.BAD_REQUEST); - return result; - } - - String modifierUserId = toscaElementToUpdate.getLastUpdaterUserId(); - if (modifierUserId == null || modifierUserId.isEmpty()) { - log.error("UserId is missing in the request."); - result = Either.right(StorageOperationStatus.BAD_REQUEST); - return result; - } - Either<GraphVertex, TitanOperationStatus> findUser = findUserVertex(modifierUserId); - - if (findUser.isRight()) { - TitanOperationStatus status = findUser.right().value(); - log.error("Cannot find user {} in the graph. status is {}", modifierUserId, status); - return result; - } - - GraphVertex modifierV = findUser.left().value(); - // UserData modifierUserData = findUser.left().value(); - String toscaElementId = toscaElementToUpdate.getUniqueId(); - - Either<GraphVertex, TitanOperationStatus> parentVertex = titanDao.getParentVertex(elementV, EdgeLabelEnum.LAST_MODIFIER, JsonParseFlagEnum.NoParse); - if (parentVertex.isRight()) { - log.debug("Failed to fetch last modifier for tosca element with id {} error {}", toscaElementId, parentVertex.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentVertex.right().value())); - } - GraphVertex userV = parentVertex.left().value(); - String currentModifier = (String) userV.getMetadataProperty(GraphPropertyEnum.USERID); - - String prevSystemName = (String) elementV.getMetadataProperty(GraphPropertyEnum.SYSTEM_NAME); - - if (currentModifier.equals(modifierUserId)) { - log.debug("Graph LAST MODIFIER edge should not be changed since the modifier is the same as the last modifier."); - } else { - log.debug("Going to update the last modifier user of the resource from {} to {}", currentModifier, modifierUserId); - StorageOperationStatus status = moveLastModifierEdge(elementV, modifierV); - log.debug("Finish to update the last modifier user of the resource from {} to {}. status is {}", currentModifier, modifierUserId, status); - if (status != StorageOperationStatus.OK) { - result = Either.right(status); - return result; - } - } - - final long currentTimeMillis = System.currentTimeMillis(); - log.debug("Going to update the last Update Date of the resource from {} to {}", elementV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE), currentTimeMillis); - elementV.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, currentTimeMillis); - - StorageOperationStatus checkCategories = validateCategories(toscaElementToUpdate, elementV); - if (checkCategories != StorageOperationStatus.OK) { - result = Either.right(checkCategories); - return result; - } - - // update all data on vertex - fillToscaElementVertexData(elementV, toscaElementToUpdate, JsonParseFlagEnum.ParseMetadata); - - Either<GraphVertex, TitanOperationStatus> updateElement = titanDao.updateVertex(elementV); - - if (updateElement.isRight()) { - log.error("Failed to update resource {}. status is {}", toscaElementId, updateElement.right().value()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value())); - return result; - } - GraphVertex updateElementV = updateElement.left().value(); - - // DE230195 in case resource name changed update TOSCA artifacts - // file names accordingly - String newSystemName = (String) updateElementV.getMetadataProperty(GraphPropertyEnum.SYSTEM_NAME); - if (newSystemName != null && !newSystemName.equals(prevSystemName)) { - Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> resultToscaArt = getDataFromGraph(updateElementV, EdgeLabelEnum.TOSCA_ARTIFACTS); - if (resultToscaArt.isRight()) { - log.debug("Failed to get tosca artifact from graph for tosca element {} error {}", toscaElementId, resultToscaArt.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resultToscaArt.right().value())); - } - - Map<String, ArtifactDataDefinition> toscaArtifacts = resultToscaArt.left().value(); - if (toscaArtifacts != null) { - for (Entry<String, ArtifactDataDefinition> artifact : toscaArtifacts.entrySet()) { - generateNewToscaFileName(toscaElementToUpdate.getComponentType().getValue().toLowerCase(), newSystemName, artifact.getValue()); - } - // TODO call to new Artifact operation in order to update list of artifacts - - } - // US833308 VLI in service - specific network_role property value logic - if (ComponentTypeEnum.SERVICE == toscaElementToUpdate.getComponentType()) { - // update method logs success/error and returns boolean (true if nothing fails) - // TODO!!!! - // updateServiceNameInVLIsNetworkRolePropertyValues(component, prevSystemName, newSystemName); - } - } - - if (toscaElementToUpdate.getComponentType() == ComponentTypeEnum.RESOURCE) { - StorageOperationStatus resultDerived = updateDerived(toscaElementToUpdate, updateElementV); - if (resultDerived != StorageOperationStatus.OK) { - log.debug("Failed to update from derived data for element {} error {}", toscaElementId, resultDerived); - return Either.right(resultDerived); - } - } - - Either<T, StorageOperationStatus> updatedResource = getToscaElement(updateElementV, filterResult); - if (updatedResource.isRight()) { - log.error("Failed to fetch tosca element {} after update , error {}", toscaElementId, updatedResource.right().value()); - result = Either.right(StorageOperationStatus.BAD_REQUEST); - return result; - } - - T updatedResourceValue = updatedResource.left().value(); - result = Either.left(updatedResourceValue); - - return result; - } - - protected StorageOperationStatus moveLastModifierEdge(GraphVertex elementV, GraphVertex modifierV) { - return DaoStatusConverter.convertTitanStatusToStorageStatus(titanDao.moveEdge(elementV, modifierV, EdgeLabelEnum.LAST_MODIFIER, Direction.IN)); - } - - protected StorageOperationStatus moveCategoryEdge(GraphVertex elementV, GraphVertex categoryV) { - return DaoStatusConverter.convertTitanStatusToStorageStatus(titanDao.moveEdge(elementV, categoryV, EdgeLabelEnum.CATEGORY, Direction.OUT)); - } - - private void generateNewToscaFileName(String componentType, String componentName, ArtifactDataDefinition artifactInfo) { - Map<String, Object> getConfig = (Map<String, Object>) ConfigurationManager.getConfigurationManager().getConfiguration().getToscaArtifacts().entrySet().stream().filter(p -> p.getKey().equalsIgnoreCase(artifactInfo.getArtifactLabel())) - .findAny().get().getValue(); - artifactInfo.setArtifactName(componentType + "-" + componentName + getConfig.get("artifactName")); - } - - protected <T extends ToscaElement> StorageOperationStatus validateResourceCategory(T toscaElementToUpdate, GraphVertex elementV) { - StorageOperationStatus status = StorageOperationStatus.OK; - List<CategoryDefinition> newCategoryList = toscaElementToUpdate.getCategories(); - CategoryDefinition newCategory = newCategoryList.get(0); - - Either<GraphVertex, TitanOperationStatus> childVertex = titanDao.getChildVertex(elementV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse); - if (childVertex.isRight()) { - log.debug("failed to fetch {} for tosca element with id {}, error {}", EdgeLabelEnum.CATEGORY, elementV.getUniqueId(), childVertex.right().value()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(childVertex.right().value()); - } - GraphVertex subCategoryV = childVertex.left().value(); - Map<GraphPropertyEnum, Object> metadataProperties = subCategoryV.getMetadataProperties(); - String subCategoryNameCurrent = (String) metadataProperties.get(GraphPropertyEnum.NAME); - - Either<GraphVertex, TitanOperationStatus> parentVertex = titanDao.getParentVertex(subCategoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse); - if (parentVertex.isRight()) { - log.debug("failed to fetch {} for category with id {}, error {}", EdgeLabelEnum.SUB_CATEGORY, subCategoryV.getUniqueId(), parentVertex.right().value()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(childVertex.right().value()); - } - GraphVertex categoryV = parentVertex.left().value(); - metadataProperties = categoryV.getMetadataProperties(); - String categoryNameCurrent = (String) metadataProperties.get(GraphPropertyEnum.NAME); - - boolean categoryWasChanged = false; - - String newCategoryName = newCategory.getName(); - SubCategoryDefinition newSubcategory = newCategory.getSubcategories().get(0); - String newSubCategoryName = newSubcategory.getName(); - if (newCategoryName != null && false == newCategoryName.equals(categoryNameCurrent)) { - // the category was changed - categoryWasChanged = true; - } else { - // the sub-category was changed - if (newSubCategoryName != null && false == newSubCategoryName.equals(subCategoryNameCurrent)) { - log.debug("Going to update the category of the resource from {} to {}", categoryNameCurrent, newCategory); - categoryWasChanged = true; - } - } - if (categoryWasChanged) { - Either<GraphVertex, StorageOperationStatus> getCategoryVertex = getResourceCategoryVertex(elementV.getUniqueId(), newSubCategoryName, newCategoryName); - - if (getCategoryVertex.isRight()) { - return getCategoryVertex.right().value(); - } - GraphVertex newCategoryV = getCategoryVertex.left().value(); - status = moveCategoryEdge(elementV, newCategoryV); - log.debug("Going to update the category of the resource from {} to {}. status is {}", categoryNameCurrent, newCategory, status); - } - return status; - } - - 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, excludeTypes, JsonParseFlagEnum.NoParse); - } - else { - listOfComponents = getListOfHighestAndAllCertifiedComponents(componentType, excludeTypes); - } - - if (listOfComponents.isRight() && listOfComponents.right().value() != TitanOperationStatus.NOT_FOUND) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(listOfComponents.right().value())); - } - List<T> result = new ArrayList<>(); - if (listOfComponents.isLeft()) { - List<GraphVertex> highestAndAllCertified = listOfComponents.left().value(); - if (highestAndAllCertified != null && false == highestAndAllCertified.isEmpty()) { - for (GraphVertex vertexComponent : highestAndAllCertified) { - Either<T, StorageOperationStatus> component = getLightComponent(vertexComponent, componentType, new ComponentParametersView(true)); - if (component.isRight()) { - 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()); - } - } - } - } - return Either.left(result); - } - - private Either<List<GraphVertex>, TitanOperationStatus> getListOfHighestComponents(ComponentTypeEnum componentType, List<ResourceTypeEnum> excludeTypes, JsonParseFlagEnum parseFlag) { - 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); - } - propertiesHasNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); - - return titanDao.getByCriteria(null, propertiesToMatch, propertiesHasNotToMatch, parseFlag); - } - - // 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, JsonParseFlagEnum.ParseMetadata); - - 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); - } - - propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_DELETED, true); - propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - - Either<List<GraphVertex>, TitanOperationStatus> certifiedNotHighestNodes = titanDao.getByCriteria(null, propertiesToMatchCertified, propertiesHasNotToMatchCertified, - JsonParseFlagEnum.ParseMetadata); - 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 (certifiedNotHighestNodes.isLeft()) { - allNodes.addAll(certifiedNotHighestNodes.left().value()); - } - if (highestNodes.isLeft()) { - allNodes.addAll(highestNodes.left().value()); - } - - log.debug("Fetch catalog {}s all states from graph took {} ms", componentType, endFetchAllStates - startFetchAllStates); - return Either.left(allNodes); - } - - protected Either<List<GraphVertex>, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) { - - // get all components marked for delete - Map<GraphPropertyEnum, Object> props = new HashMap<GraphPropertyEnum, Object>(); - props.put(GraphPropertyEnum.IS_DELETED, true); - props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); - - Either<List<GraphVertex>, TitanOperationStatus> componentsToDelete = titanDao.getByCriteria(null, props, JsonParseFlagEnum.NoParse); - - if (componentsToDelete.isRight()) { - TitanOperationStatus error = componentsToDelete.right().value(); - if (error.equals(TitanOperationStatus.NOT_FOUND)) { - log.trace("no components to delete"); - return Either.left(new ArrayList<>()); - } else { - log.info("failed to find components to delete. error : {}", error.name()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error)); - } - } - return Either.left(componentsToDelete.left().value()); - } - - protected TitanOperationStatus setAdditionalInformationFromGraph(GraphVertex componentV, ToscaElement toscaElement) { - Either<Map<String, AdditionalInfoParameterDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.ADDITIONAL_INFORMATION); - if (result.isLeft()) { - toscaElement.setAdditionalInformation(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - return TitanOperationStatus.OK; - } - - // -------------------------------------------- - public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> getToscaElement(String uniqueId, ComponentParametersView componentParametersView); - - public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> getToscaElement(GraphVertex toscaElementVertex, ComponentParametersView componentParametersView); - - public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> deleteToscaElement(GraphVertex toscaElementVertex); - - public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> createToscaElement(ToscaElement toscaElement); - - protected abstract <T extends ToscaElement> TitanOperationStatus setCategoriesFromGraph(GraphVertex vertexComponent, T toscaElement); - - protected abstract <T extends ToscaElement> TitanOperationStatus setCapabilitiesFromGraph(GraphVertex componentV, T toscaElement); - - protected abstract <T extends ToscaElement> TitanOperationStatus setRequirementsFromGraph(GraphVertex componentV, T toscaElement); - - protected abstract <T extends ToscaElement> StorageOperationStatus validateCategories(T toscaElementToUpdate, GraphVertex elementV); - - protected abstract <T extends ToscaElement> StorageOperationStatus updateDerived(T toscaElementToUpdate, GraphVertex updateElementV); + private static Logger log = LoggerFactory.getLogger(ToscaElementOperation.class.getName()); + + private static final Gson gson = new Gson(); + + protected Gson getGson() { + return gson; + } + + @Autowired + protected CategoryOperation categoryOperation; + + protected Either<GraphVertex, StorageOperationStatus> getComponentByLabelAndId(String uniqueId, ToscaElementTypeEnum nodeType, JsonParseFlagEnum parseFlag) { + + Map<GraphPropertyEnum, Object> propertiesToMatch = new HashMap<GraphPropertyEnum, Object>(); + propertiesToMatch.put(GraphPropertyEnum.UNIQUE_ID, uniqueId); + + VertexTypeEnum vertexType = ToscaElementTypeEnum.getVertexTypeByToscaType(nodeType); + Either<List<GraphVertex>, TitanOperationStatus> getResponse = titanDao.getByCriteria(vertexType, propertiesToMatch, parseFlag); + if (getResponse.isRight()) { + log.debug("Couldn't fetch component with type {} and unique id {}, error: {}", vertexType, uniqueId, getResponse.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getResponse.right().value())); + + } + List<GraphVertex> componentList = getResponse.left().value(); + if (componentList.isEmpty()) { + log.debug("Component with type {} and unique id {} was not found", vertexType, uniqueId); + return Either.right(StorageOperationStatus.NOT_FOUND); + } + GraphVertex vertexG = componentList.get(0); + return Either.left(vertexG); + } + + public Either<ToscaElement, StorageOperationStatus> getToscaElement(String uniqueId) { + return getToscaElement(uniqueId, new ComponentParametersView()); + } + + public Either<GraphVertex, StorageOperationStatus> markComponentToDelete(GraphVertex componentToDelete) { + Either<GraphVertex, StorageOperationStatus> result = null; + + Boolean isDeleted = (Boolean) componentToDelete.getMetadataProperty(GraphPropertyEnum.IS_DELETED); + if (isDeleted != null && isDeleted && !(Boolean) componentToDelete.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION)) { + // component already marked for delete + result = Either.left(componentToDelete); + return result; + } else { + + componentToDelete.addMetadataProperty(GraphPropertyEnum.IS_DELETED, Boolean.TRUE); + componentToDelete.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); + + Either<GraphVertex, TitanOperationStatus> updateNode = titanDao.updateVertex(componentToDelete); + + StorageOperationStatus updateComponent; + if (updateNode.isRight()) { + log.debug("Failed to update component {}. status is {}", componentToDelete.getUniqueId(), updateNode.right().value()); + updateComponent = DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value()); + result = Either.right(updateComponent); + return result; + } + + result = Either.left(componentToDelete); + return result; + } + } + + /** + * Performs a shadow clone of previousToscaElement + * + * @param previousToscaElement + * @param nextToscaElement + * @param user + * @return + */ + public Either<GraphVertex, StorageOperationStatus> cloneToscaElement(GraphVertex previousToscaElement, GraphVertex nextToscaElement, GraphVertex user) { + + Either<GraphVertex, StorageOperationStatus> result = null; + GraphVertex createdToscaElementVertex = null; + TitanOperationStatus status; + + Either<GraphVertex, TitanOperationStatus> createNextVersionRes = titanDao.createVertex(nextToscaElement); + if (createNextVersionRes.isRight()) { + status = createNextVersionRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create tosca element vertex {} with version {} on graph. Status is {}. ", previousToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), + previousToscaElement.getMetadataProperty(GraphPropertyEnum.VERSION), status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + if (result == null) { + createdToscaElementVertex = createNextVersionRes.left().value(); + Map<EdgePropertyEnum, Object> properties = new HashMap<EdgePropertyEnum, Object>(); + properties.put(EdgePropertyEnum.STATE, createdToscaElementVertex.getMetadataProperty(GraphPropertyEnum.STATE)); + status = titanDao.createEdge(user.getVertex(), createdToscaElementVertex.getVertex(), EdgeLabelEnum.STATE, properties); + if (status != TitanOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge with label {} from user vertex {} to tosca element vertex {} on graph. Status is {}. ", EdgeLabelEnum.STATE, user.getUniqueId(), + previousToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + } + if (result == null) { + status = titanDao.createEdge(user.getVertex(), createdToscaElementVertex.getVertex(), EdgeLabelEnum.LAST_MODIFIER, new HashMap<>()); + if (status != TitanOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge with label {} from user vertex {} to tosca element vertex {} on graph. Status is {}. ", EdgeLabelEnum.LAST_MODIFIER, user.getUniqueId(), + nextToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + } + if (result == null) { + status = titanDao.createEdge(user.getVertex(), createdToscaElementVertex.getVertex(), EdgeLabelEnum.CREATOR, new HashMap<>()); + if (status != TitanOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge with label {} from user vertex {} to tosca element vertex {} on graph. Status is {}. ", EdgeLabelEnum.CREATOR, user.getUniqueId(), + nextToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + } + if (result == null) { + Iterator<Edge> edgesToCopyIter = previousToscaElement.getVertex().edges(Direction.OUT); + while (edgesToCopyIter.hasNext()) { + Edge currEdge = edgesToCopyIter.next(); + Vertex currVertex = currEdge.inVertex(); + // if(EdgeLabelEnum.getEdgeLabelEnum(currEdge.label()).equals(EdgeLabelEnum.VERSION)){ + // continue; + // } + status = titanDao.createEdge(createdToscaElementVertex.getVertex(), currVertex, EdgeLabelEnum.getEdgeLabelEnum(currEdge.label()), currEdge); + if (status != TitanOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge with label {} from tosca element vertex {} to vertex with label {} on graph. Status is {}. ", currEdge.label(), createdToscaElementVertex.getUniqueId(), + currVertex.property(GraphPropertyEnum.LABEL.getProperty()), status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + break; + } + } + } + + if (result == null) { + result = Either.left(createdToscaElementVertex); + } else { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to clone tosca element {} with the name {}. ", previousToscaElement.getUniqueId(), previousToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME)); + } + return result; + } + + protected TitanOperationStatus setLastModifierFromGraph(GraphVertex componentV, ToscaElement toscaElement) { + Either<GraphVertex, TitanOperationStatus> parentVertex = titanDao.getParentVertex(componentV, EdgeLabelEnum.LAST_MODIFIER, JsonParseFlagEnum.NoParse); + if (parentVertex.isRight()) { + log.debug("Failed to fetch last modifier for tosca element with id {} error {}", componentV.getUniqueId(), parentVertex.right().value()); + return parentVertex.right().value(); + } + GraphVertex userV = parentVertex.left().value(); + String userId = (String) userV.getMetadataProperty(GraphPropertyEnum.USERID); + toscaElement.setLastUpdaterUserId(userId); + toscaElement.setLastUpdaterFullName(buildFullName(userV)); + return TitanOperationStatus.OK; + } + + public String buildFullName(GraphVertex userV) { + + String fullName = (String) userV.getMetadataProperty(GraphPropertyEnum.FIRST_NAME); + if (fullName == null) { + fullName = ""; + } else { + fullName = fullName + " "; + } + String lastName = (String) userV.getMetadataProperty(GraphPropertyEnum.LAST_NAME); + if (lastName != null) { + fullName += lastName; + } + return fullName; + } + + protected TitanOperationStatus setCreatorFromGraph(GraphVertex componentV, ToscaElement toscaElement) { + Either<GraphVertex, TitanOperationStatus> parentVertex = titanDao.getParentVertex(componentV, EdgeLabelEnum.CREATOR, JsonParseFlagEnum.NoParse); + if (parentVertex.isRight()) { + log.debug("Failed to fetch creator for tosca element with id {} error {}", componentV.getUniqueId(), parentVertex.right().value()); + return parentVertex.right().value(); + } + GraphVertex userV = parentVertex.left().value(); + String creatorUserId = (String) userV.getMetadataProperty(GraphPropertyEnum.USERID); + toscaElement.setCreatorUserId(creatorUserId); + toscaElement.setCreatorFullName(buildFullName(userV)); + + return TitanOperationStatus.OK; + } + + protected <T extends ToscaElement> T getResourceMetaDataFromResource(T toscaElement) { + if (toscaElement.getNormalizedName() == null || toscaElement.getNormalizedName().isEmpty()) { + toscaElement.setNormalizedName(ValidationUtils.normaliseComponentName(toscaElement.getName())); + } + if (toscaElement.getSystemName() == null || toscaElement.getSystemName().isEmpty()) { + toscaElement.setSystemName(ValidationUtils.convertToSystemName(toscaElement.getName())); + } + + LifecycleStateEnum lifecycleStateEnum = toscaElement.getLifecycleState(); + if (lifecycleStateEnum == null) { + toscaElement.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + long currentDate = System.currentTimeMillis(); + if (toscaElement.getCreationDate() == null) { + toscaElement.setCreationDate(currentDate); + } + toscaElement.setLastUpdateDate(currentDate); + + return toscaElement; + } + + protected void fillCommonMetadata(GraphVertex nodeTypeVertex, ToscaElement toscaElement) { + if (toscaElement.isHighestVersion() == null) { + toscaElement.setHighestVersion(true); + } + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_DELETED, toscaElement.getMetadataValue(JsonPresentationFields.IS_DELETED)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION, toscaElement.getMetadataValueOrDefault(JsonPresentationFields.HIGHEST_VERSION, Boolean.TRUE)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.STATE, toscaElement.getMetadataValue(JsonPresentationFields.LIFECYCLE_STATE)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.RESOURCE_TYPE, toscaElement.getMetadataValue(JsonPresentationFields.RESOURCE_TYPE)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.VERSION, toscaElement.getMetadataValue(JsonPresentationFields.VERSION)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME, toscaElement.getMetadataValue(JsonPresentationFields.NORMALIZED_NAME)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, toscaElement.getMetadataValue(JsonPresentationFields.UNIQUE_ID)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaElement.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.UUID, toscaElement.getMetadataValue(JsonPresentationFields.UUID)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_ABSTRACT, toscaElement.getMetadataValue(JsonPresentationFields.IS_ABSTRACT)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.INVARIANT_UUID, toscaElement.getMetadataValue(JsonPresentationFields.INVARIANT_UUID)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.NAME, toscaElement.getMetadataValue(JsonPresentationFields.NAME)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.SYSTEM_NAME, toscaElement.getMetadataValue(JsonPresentationFields.SYSTEM_NAME)); + toscaElement.getMetadata().entrySet().stream().filter(e -> e.getValue() != null).forEach(e -> nodeTypeVertex.setJsonMetadataField(JsonPresentationFields.getByPresentation(e.getKey()), e.getValue())); + + nodeTypeVertex.setUniqueId(toscaElement.getUniqueId()); + nodeTypeVertex.setType(toscaElement.getComponentType()); + + } + + protected StorageOperationStatus assosiateToUsers(GraphVertex nodeTypeVertex, ToscaElement toscaElement) { + // handle user + String userId = toscaElement.getCreatorUserId(); + + Either<GraphVertex, TitanOperationStatus> findUser = findUserVertex(userId); + + if (findUser.isRight()) { + TitanOperationStatus status = findUser.right().value(); + log.error("Cannot find user {} in the graph. status is {}", userId, status); + return DaoStatusConverter.convertTitanStatusToStorageStatus(status); + + } + GraphVertex creatorVertex = findUser.left().value(); + GraphVertex updaterVertex = creatorVertex; + String updaterId = toscaElement.getLastUpdaterUserId(); + if (updaterId != null && !updaterId.equals(userId)) { + findUser = findUserVertex(updaterId); + if (findUser.isRight()) { + TitanOperationStatus status = findUser.right().value(); + log.error("Cannot find user {} in the graph. status is {}", userId, status); + return DaoStatusConverter.convertTitanStatusToStorageStatus(status); + } else { + updaterVertex = findUser.left().value(); + } + } + Map<EdgePropertyEnum, Object> props = new HashMap<EdgePropertyEnum, Object>(); + props.put(EdgePropertyEnum.STATE, (String) toscaElement.getMetadataValue(JsonPresentationFields.LIFECYCLE_STATE)); + + TitanOperationStatus result = titanDao.createEdge(updaterVertex, nodeTypeVertex, EdgeLabelEnum.STATE, props); + log.debug("After associating user {} to resource {}. Edge type is {}", updaterVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.STATE); + if (TitanOperationStatus.OK != result) { + return DaoStatusConverter.convertTitanStatusToStorageStatus(result); + } + result = titanDao.createEdge(updaterVertex, nodeTypeVertex, EdgeLabelEnum.LAST_MODIFIER, null); + log.debug("After associating user {} to resource {}. Edge type is {}", updaterVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER); + if (!result.equals(TitanOperationStatus.OK)) { + log.error("Failed to associate user {} to resource {}. Edge type is {}", updaterVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER); + return DaoStatusConverter.convertTitanStatusToStorageStatus(result); + } + + toscaElement.setLastUpdaterUserId(toscaElement.getCreatorUserId()); + toscaElement.setLastUpdaterFullName(toscaElement.getCreatorFullName()); + + result = titanDao.createEdge(creatorVertex, nodeTypeVertex, EdgeLabelEnum.CREATOR, null); + log.debug("After associating user {} to resource {}. Edge type is {} ", creatorVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.CREATOR); + if (!result.equals(TitanOperationStatus.OK)) { + log.error("Failed to associate user {} to resource {}. Edge type is {} ", creatorVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.CREATOR); + return DaoStatusConverter.convertTitanStatusToStorageStatus(result); + } + return StorageOperationStatus.OK; + } + + protected StorageOperationStatus assosiateResourceMetadataToCategory(GraphVertex nodeTypeVertex, ToscaElement nodeType) { + String subcategoryName = nodeType.getCategories().get(0).getSubcategories().get(0).getName(); + String categoryName = nodeType.getCategories().get(0).getName(); + Either<GraphVertex, StorageOperationStatus> getCategoryVertex = getResourceCategoryVertex(nodeType.getUniqueId(), subcategoryName, categoryName); + + if (getCategoryVertex.isRight()) { + return getCategoryVertex.right().value(); + } + + GraphVertex subCategoryV = getCategoryVertex.left().value(); + + TitanOperationStatus createEdge = titanDao.createEdge(nodeTypeVertex, subCategoryV, EdgeLabelEnum.CATEGORY, new HashMap<>()); + if (createEdge != TitanOperationStatus.OK) { + log.trace("Failed to associate resource {} to category {} with id {}", nodeType.getUniqueId(), subcategoryName, subCategoryV.getUniqueId()); + return DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge); + } + return StorageOperationStatus.OK; + } + + protected Either<GraphVertex, StorageOperationStatus> getResourceCategoryVertex(String elementId, String subcategoryName, String categoryName) { + Either<GraphVertex, StorageOperationStatus> category = categoryOperation.getCategory(categoryName, VertexTypeEnum.RESOURCE_CATEGORY); + if (category.isRight()) { + log.trace("Failed to fetch category {} for resource {} error {}", categoryName, elementId, category.right().value()); + return Either.right(category.right().value()); + } + GraphVertex categoryV = category.left().value(); + + if (subcategoryName != null) { + Either<GraphVertex, StorageOperationStatus> subCategory = categoryOperation.getSubCategoryForCategory(categoryV, subcategoryName); + if (subCategory.isRight()) { + log.trace("Failed to fetch subcategory {} of category for resource {} error {}", subcategoryName, categoryName, elementId, subCategory.right().value()); + return Either.right(subCategory.right().value()); + } + + GraphVertex subCategoryV = subCategory.left().value(); + return Either.left(subCategoryV); + } + return Either.left(categoryV); + } + + private StorageOperationStatus associateArtifactsToResource(GraphVertex nodeTypeVertex, ToscaElement toscaElement) { + Map<String, ArtifactDataDefinition> artifacts = toscaElement.getArtifacts(); + Either<GraphVertex, StorageOperationStatus> status; + if (artifacts != null) { + artifacts.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> { + String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase()); + a.setUniqueId(uniqueId); + }); + status = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.ARTIFACTS, EdgeLabelEnum.ARTIFACTS, artifacts); + if (status.isRight()) { + return status.right().value(); + } + } + Map<String, ArtifactDataDefinition> toscaArtifacts = toscaElement.getToscaArtifacts(); + if (toscaArtifacts != null) { + toscaArtifacts.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> { + String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase()); + a.setUniqueId(uniqueId); + }); + status = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.TOSCA_ARTIFACTS, EdgeLabelEnum.TOSCA_ARTIFACTS, toscaArtifacts); + if (status.isRight()) { + return status.right().value(); + } + } + Map<String, ArtifactDataDefinition> deploymentArtifacts = toscaElement.getDeploymentArtifacts(); + if (deploymentArtifacts != null) { + deploymentArtifacts.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> { + String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase()); + a.setUniqueId(uniqueId); + }); + status = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.DEPLOYMENT_ARTIFACTS, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS, deploymentArtifacts); + if (status.isRight()) { + return status.right().value(); + } + } + return StorageOperationStatus.OK; + } + + protected TitanOperationStatus disassociateAndDeleteCommonElements(GraphVertex toscaElementVertex) { + TitanOperationStatus status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ARTIFACTS); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to disaccociate artifact for {} error {}", toscaElementVertex.getUniqueId(), status); + return status; + } + status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.TOSCA_ARTIFACTS); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to disaccociate tosca artifact for {} error {}", toscaElementVertex.getUniqueId(), status); + return status; + } + status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to deployment artifact for {} error {}", toscaElementVertex.getUniqueId(), status); + return status; + } + status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.PROPERTIES); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to disaccociate properties for {} error {}", toscaElementVertex.getUniqueId(), status); + return status; + } + status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ATTRIBUTES); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to disaccociate attributes for {} error {}", toscaElementVertex.getUniqueId(), status); + return status; + } + status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ADDITIONAL_INFORMATION); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to disaccociate additional information for {} error {}", toscaElementVertex.getUniqueId(), status); + return status; + } + status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CAPABILITIES); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to disaccociate capabilities for {} error {}", toscaElementVertex.getUniqueId(), status); + return status; + } + status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.REQUIREMENTS); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to disaccociate requirements for {} error {}", toscaElementVertex.getUniqueId(), status); + return status; + } + status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.FORWARDING_PATH); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to disaccociate requirements for {} error {}", toscaElementVertex.getUniqueId(), status); + return status; + } + return TitanOperationStatus.OK; + } + + protected StorageOperationStatus assosiateCommonForToscaElement(GraphVertex nodeTypeVertex, ToscaElement toscaElement, List<GraphVertex> derivedResources) { + + StorageOperationStatus associateUsers = assosiateToUsers(nodeTypeVertex, toscaElement); + if (associateUsers != StorageOperationStatus.OK) { + return associateUsers; + } + StorageOperationStatus associateArtifacts = associateArtifactsToResource(nodeTypeVertex, toscaElement); + if (associateArtifacts != StorageOperationStatus.OK) { + return associateArtifacts; + } + StorageOperationStatus associateProperties = associatePropertiesToResource(nodeTypeVertex, toscaElement, derivedResources); + if (associateProperties != StorageOperationStatus.OK) { + return associateProperties; + } + StorageOperationStatus associateAdditionaInfo = associateAdditionalInfoToResource(nodeTypeVertex, toscaElement); + if (associateAdditionaInfo != StorageOperationStatus.OK) { + return associateAdditionaInfo; + } + if (needConnectToCatalog(toscaElement)) { + StorageOperationStatus associateToCatalog = associateToCatalogRoot(nodeTypeVertex); + if (associateToCatalog != StorageOperationStatus.OK) { + return associateToCatalog; + } + } + return StorageOperationStatus.OK; + } + + private boolean needConnectToCatalog(ToscaElement toscaElement) { + Boolean isAbstract = (Boolean) toscaElement.getMetadataValue(JsonPresentationFields.IS_ABSTRACT); + if (isAbstract != null && isAbstract) { + return false; + } + return toscaElement.isHighestVersion(); + } + + private StorageOperationStatus associateToCatalogRoot(GraphVertex nodeTypeVertex) { + Either<GraphVertex, TitanOperationStatus> catalog = titanDao.getVertexByLabel(VertexTypeEnum.CATALOG_ROOT); + if (catalog.isRight()) { + log.debug("Failed to fetch catalog vertex. error {}", catalog.right().value()); + return DaoStatusConverter.convertTitanStatusToStorageStatus(catalog.right().value()); + } + TitanOperationStatus createEdge = titanDao.createEdge(catalog.left().value(), nodeTypeVertex, EdgeLabelEnum.CATALOG_ELEMENT, null); + + return DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge); + } + + protected StorageOperationStatus associatePropertiesToResource(GraphVertex nodeTypeVertex, ToscaElement nodeType, List<GraphVertex> derivedResources) { + // Note : currently only one derived supported!!!! + Either<Map<String, PropertyDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.PROPERTIES); + if (dataFromDerived.isRight()) { + return dataFromDerived.right().value(); + } + Map<String, PropertyDataDefinition> propertiesAll = dataFromDerived.left().value(); + + Map<String, PropertyDataDefinition> properties = nodeType.getProperties(); + + if (properties != null) { + properties.values().stream().filter(p -> p.getUniqueId() == null).forEach(p -> { + String uid = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId(), p.getName()); + p.setUniqueId(uid); + }); + + Either<Map<String, PropertyDataDefinition>, String> eitherMerged = ToscaDataDefinition.mergeDataMaps(propertiesAll, properties); + if (eitherMerged.isRight()) { + // TODO re-factor error handling - moving BL to operation resulted in loss of info about the invalid property + log.debug("property {} cannot be overriden", eitherMerged.right().value()); + return StorageOperationStatus.INVALID_PROPERTY; + } + } + if (!propertiesAll.isEmpty()) { + Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.PROPERTIES, EdgeLabelEnum.PROPERTIES, propertiesAll); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + private StorageOperationStatus associateAdditionalInfoToResource(GraphVertex nodeTypeVertex, ToscaElement nodeType) { + Map<String, AdditionalInfoParameterDataDefinition> additionalInformation = nodeType.getAdditionalInformation(); + if (additionalInformation != null) { + Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.ADDITIONAL_INFORMATION, EdgeLabelEnum.ADDITIONAL_INFORMATION, additionalInformation); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + protected <T extends ToscaDataDefinition> Either<Map<String, T>, StorageOperationStatus> getDataFromDerived(List<GraphVertex> derivedResources, EdgeLabelEnum edge) { + Map<String, T> propertiesAll = new HashMap<>(); + + if (derivedResources != null && !derivedResources.isEmpty()) { + for (GraphVertex derived : derivedResources) { + Either<List<GraphVertex>, TitanOperationStatus> derivedProperties = titanDao.getChildrenVertecies(derived, edge, JsonParseFlagEnum.ParseJson); + if (derivedProperties.isRight()) { + if (derivedProperties.right().value() != TitanOperationStatus.NOT_FOUND) { + log.debug("Failed to get properties for derived from {} error {}", derived.getUniqueId(), derivedProperties.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(derivedProperties.right().value())); + } else { + continue; + } + } + List<GraphVertex> propList = derivedProperties.left().value(); + for (GraphVertex propV : propList) { + Map<String, T> propertiesFromDerived = (Map<String, T>) propV.getJson(); + if (propertiesFromDerived != null) { + propertiesFromDerived.entrySet().forEach(x -> x.getValue().setOwnerIdIfEmpty(derived.getUniqueId())); + propertiesAll.putAll(propertiesFromDerived); + } + } + } + } + return Either.left(propertiesAll); + } + + protected TitanOperationStatus setArtifactsFromGraph(GraphVertex componentV, ToscaElement toscaElement) { + Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.ARTIFACTS); + if (result.isLeft()) { + toscaElement.setArtifacts(result.left().value()); + } else { + if (result.right().value() != TitanOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + result = getDataFromGraph(componentV, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS); + if (result.isLeft()) { + toscaElement.setDeploymentArtifacts(result.left().value()); + } else { + if (result.right().value() != TitanOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + result = getDataFromGraph(componentV, EdgeLabelEnum.TOSCA_ARTIFACTS); + if (result.isLeft()) { + toscaElement.setToscaArtifacts(result.left().value()); + } else { + if (result.right().value() != TitanOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return TitanOperationStatus.OK; + } + + protected TitanOperationStatus setAllVersions(GraphVertex componentV, ToscaElement toscaElement) { + Map<String, String> allVersion = new HashMap<>(); + + allVersion.put((String) componentV.getMetadataProperty(GraphPropertyEnum.VERSION), componentV.getUniqueId()); + ArrayList<GraphVertex> allChildrenAndParants = new ArrayList<GraphVertex>(); + Either<GraphVertex, TitanOperationStatus> childResourceRes = titanDao.getChildVertex(componentV, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); + while (childResourceRes.isLeft()) { + GraphVertex child = childResourceRes.left().value(); + allChildrenAndParants.add(child); + childResourceRes = titanDao.getChildVertex(child, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); + } + TitanOperationStatus operationStatus = childResourceRes.right().value(); + + if (operationStatus != TitanOperationStatus.NOT_FOUND) { + return operationStatus; + } else { + Either<GraphVertex, TitanOperationStatus> parentResourceRes = titanDao.getParentVertex(componentV, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); + while (parentResourceRes.isLeft()) { + GraphVertex parent = parentResourceRes.left().value(); + allChildrenAndParants.add(parent); + parentResourceRes = titanDao.getParentVertex(parent, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); + } + operationStatus = parentResourceRes.right().value(); + if (operationStatus != TitanOperationStatus.NOT_FOUND) { + return operationStatus; + } else { + allChildrenAndParants.stream().filter(vertex -> { + Boolean isDeleted = (Boolean) vertex.getMetadataProperty(GraphPropertyEnum.IS_DELETED); + return (isDeleted == null || isDeleted == false); + }).forEach(vertex -> allVersion.put((String) vertex.getMetadataProperty(GraphPropertyEnum.VERSION), vertex.getUniqueId())); + + toscaElement.setAllVersions(allVersion); + return TitanOperationStatus.OK; + } + } + } + + protected <T extends ToscaElement> Either<List<T>, StorageOperationStatus> getFollowedComponent(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, ComponentTypeEnum neededType) { + + Either<List<T>, StorageOperationStatus> result = null; + + Map<GraphPropertyEnum, Object> props = null; + + if (userId != null) { + props = new HashMap<>(); + // for Designer retrieve specific user + props.put(GraphPropertyEnum.USERID, userId); + } + // in case of user id == null -> get all users by label + // for Tester and Admin retrieve all users + Either<List<GraphVertex>, TitanOperationStatus> usersByCriteria = titanDao.getByCriteria(VertexTypeEnum.USER, props, JsonParseFlagEnum.NoParse); + if (usersByCriteria.isRight()) { + log.debug("Failed to fetch users by criteria {} error {}", props, usersByCriteria.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(usersByCriteria.right().value())); + } + List<GraphVertex> users = usersByCriteria.left().value(); + + List<T> components = new ArrayList<>(); + List<T> componentsPerUser; + for (GraphVertex userV : users) { + + HashSet<String> ids = new HashSet<String>(); + Either<List<GraphVertex>, TitanOperationStatus> childrenVertecies = titanDao.getChildrenVertecies(userV, EdgeLabelEnum.STATE, JsonParseFlagEnum.NoParse); + if (childrenVertecies.isRight() && childrenVertecies.right().value() != TitanOperationStatus.NOT_FOUND) { + log.debug("Failed to fetch children vertices for user {} by edge {} error {}", userV.getMetadataProperty(GraphPropertyEnum.USERID), EdgeLabelEnum.STATE, childrenVertecies.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(childrenVertecies.right().value())); + } + + // get all resource with current state + if (childrenVertecies.isLeft()) { + componentsPerUser = fetchComponents(lifecycleStates, childrenVertecies.left().value(), neededType, EdgeLabelEnum.STATE); + + if (componentsPerUser != null) { + for (T comp : componentsPerUser) { + ids.add(comp.getUniqueId()); + components.add(comp); + } + } + } + if (lastStateStates != null && !lastStateStates.isEmpty()) { + // get all resource with last state + childrenVertecies = titanDao.getChildrenVertecies(userV, EdgeLabelEnum.LAST_STATE, JsonParseFlagEnum.NoParse); + if (childrenVertecies.isRight() && childrenVertecies.right().value() != TitanOperationStatus.NOT_FOUND) { + log.debug("Failed to fetch children vertices for user {} by edge {} error {}", userV.getMetadataProperty(GraphPropertyEnum.USERID), EdgeLabelEnum.LAST_STATE, childrenVertecies.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(childrenVertecies.right().value())); + } + if (childrenVertecies.isLeft()) { + boolean isFirst; + componentsPerUser = fetchComponents(lastStateStates, childrenVertecies.left().value(), neededType, EdgeLabelEnum.LAST_STATE); + if (componentsPerUser != null) { + for (T comp : componentsPerUser) { + isFirst = true; + + if (ids.contains(comp.getUniqueId())) { + isFirst = false; + } + if (isFirst == true) { + components.add(comp); + } + + } + } + } + } + + } // whlile users + ; + result = Either.left(components); + return result; + + } + + private <T extends ToscaElement> List<T> fetchComponents(Set<LifecycleStateEnum> lifecycleStates, List<GraphVertex> vertices, ComponentTypeEnum neededType, EdgeLabelEnum edgelabel) { + List<T> components = new ArrayList<>(); + for (GraphVertex node : vertices) { + + Iterator<Edge> edges = node.getVertex().edges(Direction.IN, edgelabel.name()); + while (edges.hasNext()) { + Edge edge = edges.next(); + String stateStr = (String) titanDao.getProperty(edge, EdgePropertyEnum.STATE); + + LifecycleStateEnum nodeState = LifecycleStateEnum.findState(stateStr); + if (nodeState == null) { + log.debug("no supported STATE {} for element {}", stateStr, node.getUniqueId()); + continue; + } + if (lifecycleStates != null && lifecycleStates.contains(nodeState)) { + + Boolean isDeleted = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_DELETED); + if (isDeleted != null && isDeleted) { + log.trace("Deleted element {}, discard", node.getUniqueId()); + continue; + } + + Boolean isHighest = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION); + if (isHighest) { + + ComponentTypeEnum componentType = node.getType(); + // get only latest versions + + if (componentType == null) { + log.debug("No supported type {} for vertex {}", componentType, node.getUniqueId()); + continue; + } + if (neededType == componentType) { + switch (componentType) { + case SERVICE: + case PRODUCT: + handleNode(components, node, componentType); + break; + case RESOURCE: + Boolean isAbtract = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_ABSTRACT); + if (isAbtract == null || false == isAbtract) { + handleNode(components, node, componentType); + } // if not abstract + break; + default: + log.debug("not supported node type {}", componentType); + break; + }// case + } // needed type + } + } // if + } // while edges + } // while resources + return components; + } + + protected <T extends ToscaElement> void handleNode(List<T> components, GraphVertex vertexComponent, ComponentTypeEnum nodeType) { + + Either<T, StorageOperationStatus> component = getLightComponent(vertexComponent, nodeType, new ComponentParametersView(true)); + if (component.isRight()) { + log.debug("Failed to get component for id = {} error : {} skip resource", vertexComponent.getUniqueId(), component.right().value()); + } else { + components.add(component.left().value()); + } + } + + protected <T extends ToscaElement> Either<T, StorageOperationStatus> getLightComponent(String componentUid, ComponentTypeEnum nodeType, ComponentParametersView parametersFilter) { + Either<GraphVertex, TitanOperationStatus> getVertexRes = titanDao.getVertexById(componentUid); + if (getVertexRes.isRight()) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexRes.right().value())); + } + return getLightComponent(getVertexRes.left().value(), nodeType, parametersFilter); + } + + protected <T extends ToscaElement> Either<T, StorageOperationStatus> getLightComponent(GraphVertex vertexComponent, ComponentTypeEnum nodeType, ComponentParametersView parametersFilter) { + + log.trace("Starting to build light component of type {}, id {}", nodeType, vertexComponent.getUniqueId()); + + titanDao.parseVertexProperties(vertexComponent, JsonParseFlagEnum.ParseMetadata); + + T toscaElement = convertToComponent(vertexComponent); + + TitanOperationStatus status = setCreatorFromGraph(vertexComponent, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + + status = setLastModifierFromGraph(vertexComponent, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + status = setCategoriesFromGraph(vertexComponent, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + if (!parametersFilter.isIgnoreAllVersions()) { + status = setAllVersions(vertexComponent, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + } + if (!parametersFilter.isIgnoreCapabilities()) { + status = setCapabilitiesFromGraph(vertexComponent, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + } + if (!parametersFilter.isIgnoreRequirements()) { + status = setRequirementsFromGraph(vertexComponent, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + } + log.debug("Ended to build light component of type {}, id {}", nodeType, vertexComponent.getUniqueId()); + return Either.left(toscaElement); + } + + @SuppressWarnings("unchecked") + protected <T extends ToscaElement> T convertToComponent(GraphVertex componentV) { + ToscaElement toscaElement = null; + VertexTypeEnum label = componentV.getLabel(); + switch (label) { + case NODE_TYPE: + toscaElement = new NodeType(); + break; + case TOPOLOGY_TEMPLATE: + toscaElement = new TopologyTemplate(); + break; + default: + log.debug("Not supported tosca type {}", label); + break; + } + + Map<String, Object> jsonMetada = componentV.getMetadataJson(); + if (toscaElement != null) { + toscaElement.setMetadata(jsonMetada); + } + return (T) toscaElement; + } + + protected TitanOperationStatus setServiceCategoryFromGraphV(Vertex vertex, CatalogComponent catalogComponent) { + Either<Vertex, TitanOperationStatus> childVertex = titanDao.getChildVertex(vertex, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse); + if (childVertex.isRight()) { + log.debug("failed to fetch {} for tosca element with id {}, error {}", EdgeLabelEnum.CATEGORY, catalogComponent.getUniqueId(), childVertex.right().value()); + return childVertex.right().value(); + } + Vertex categoryV = childVertex.left().value(); + catalogComponent.setCategoryNormalizedName((String) categoryV.property(JsonPresentationFields.NORMALIZED_NAME.getPresentation()).value()); + + return TitanOperationStatus.OK; + } + + protected TitanOperationStatus setResourceCategoryFromGraphV(Vertex vertex, CatalogComponent catalogComponent) { + + Either<Vertex, TitanOperationStatus> childVertex = titanDao.getChildVertex(vertex, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse); + if (childVertex.isRight()) { + log.debug("failed to fetch {} for tosca element with id {}, error {}", EdgeLabelEnum.CATEGORY, catalogComponent.getUniqueId(), childVertex.right().value()); + return childVertex.right().value(); + } + Vertex subCategoryV = childVertex.left().value(); + catalogComponent.setSubCategoryNormalizedName((String) subCategoryV.property(JsonPresentationFields.NORMALIZED_NAME.getPresentation()).value()); + Either<Vertex, TitanOperationStatus> parentVertex = titanDao.getParentVertex(subCategoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse); + Vertex categoryV = parentVertex.left().value(); + catalogComponent.setCategoryNormalizedName((String) categoryV.property(JsonPresentationFields.NORMALIZED_NAME.getPresentation()).value()); + + return TitanOperationStatus.OK; + } + + protected TitanOperationStatus setResourceCategoryFromGraph(GraphVertex componentV, ToscaElement toscaElement) { + List<CategoryDefinition> categories = new ArrayList<>(); + SubCategoryDefinition subcategory; + + Either<GraphVertex, TitanOperationStatus> childVertex = titanDao.getChildVertex(componentV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse); + if (childVertex.isRight()) { + log.debug("failed to fetch {} for tosca element with id {}, error {}", EdgeLabelEnum.CATEGORY, componentV.getUniqueId(), childVertex.right().value()); + return childVertex.right().value(); + } + GraphVertex subCategoryV = childVertex.left().value(); + Map<GraphPropertyEnum, Object> metadataProperties = subCategoryV.getMetadataProperties(); + subcategory = new SubCategoryDefinition(); + subcategory.setUniqueId(subCategoryV.getUniqueId()); + subcategory.setNormalizedName((String) metadataProperties.get(GraphPropertyEnum.NORMALIZED_NAME)); + subcategory.setName((String) metadataProperties.get(GraphPropertyEnum.NAME)); + + Type listTypeSubcat = new TypeToken<List<String>>() { + }.getType(); + List<String> iconsfromJsonSubcat = getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.ICONS), listTypeSubcat); + subcategory.setIcons(iconsfromJsonSubcat); + + Either<GraphVertex, TitanOperationStatus> parentVertex = titanDao.getParentVertex(subCategoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse); + if (parentVertex.isRight()) { + log.debug("failed to fetch {} for category with id {}, error {}", EdgeLabelEnum.SUB_CATEGORY, subCategoryV.getUniqueId(), parentVertex.right().value()); + return childVertex.right().value(); + } + GraphVertex categoryV = parentVertex.left().value(); + metadataProperties = categoryV.getMetadataProperties(); + + CategoryDefinition category = new CategoryDefinition(); + 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(); + List<String> iconsfromJsonCat = getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.ICONS), listTypeCat); + category.setIcons(iconsfromJsonCat); + + category.addSubCategory(subcategory); + categories.add(category); + toscaElement.setCategories(categories); + + return TitanOperationStatus.OK; + } + + public <T extends ToscaElement> Either<T, StorageOperationStatus> updateToscaElement(T toscaElementToUpdate, GraphVertex elementV, ComponentParametersView filterResult) { + Either<T, StorageOperationStatus> result = null; + + log.debug("In updateToscaElement. received component uid = {}", (toscaElementToUpdate == null ? null : toscaElementToUpdate.getUniqueId())); + if (toscaElementToUpdate == null) { + log.error("Service object is null"); + result = Either.right(StorageOperationStatus.BAD_REQUEST); + return result; + } + + String modifierUserId = toscaElementToUpdate.getLastUpdaterUserId(); + if (modifierUserId == null || modifierUserId.isEmpty()) { + log.error("UserId is missing in the request."); + result = Either.right(StorageOperationStatus.BAD_REQUEST); + return result; + } + Either<GraphVertex, TitanOperationStatus> findUser = findUserVertex(modifierUserId); + + if (findUser.isRight()) { + TitanOperationStatus status = findUser.right().value(); + log.error("Cannot find user {} in the graph. status is {}", modifierUserId, status); + return result; + } + + GraphVertex modifierV = findUser.left().value(); + // UserData modifierUserData = findUser.left().value(); + String toscaElementId = toscaElementToUpdate.getUniqueId(); + + Either<GraphVertex, TitanOperationStatus> parentVertex = titanDao.getParentVertex(elementV, EdgeLabelEnum.LAST_MODIFIER, JsonParseFlagEnum.NoParse); + if (parentVertex.isRight()) { + log.debug("Failed to fetch last modifier for tosca element with id {} error {}", toscaElementId, parentVertex.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentVertex.right().value())); + } + GraphVertex userV = parentVertex.left().value(); + String currentModifier = (String) userV.getMetadataProperty(GraphPropertyEnum.USERID); + + String prevSystemName = (String) elementV.getMetadataProperty(GraphPropertyEnum.SYSTEM_NAME); + + if (currentModifier.equals(modifierUserId)) { + log.debug("Graph LAST MODIFIER edge should not be changed since the modifier is the same as the last modifier."); + } else { + log.debug("Going to update the last modifier user of the resource from {} to {}", currentModifier, modifierUserId); + StorageOperationStatus status = moveLastModifierEdge(elementV, modifierV); + log.debug("Finish to update the last modifier user of the resource from {} to {}. status is {}", currentModifier, modifierUserId, status); + if (status != StorageOperationStatus.OK) { + result = Either.right(status); + return result; + } + } + + final long currentTimeMillis = System.currentTimeMillis(); + log.debug("Going to update the last Update Date of the resource from {} to {}", elementV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE), currentTimeMillis); + elementV.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, currentTimeMillis); + + StorageOperationStatus checkCategories = validateCategories(toscaElementToUpdate, elementV); + if (checkCategories != StorageOperationStatus.OK) { + result = Either.right(checkCategories); + return result; + } + + // update all data on vertex + fillToscaElementVertexData(elementV, toscaElementToUpdate, JsonParseFlagEnum.ParseMetadata); + + Either<GraphVertex, TitanOperationStatus> updateElement = titanDao.updateVertex(elementV); + + if (updateElement.isRight()) { + log.error("Failed to update resource {}. status is {}", toscaElementId, updateElement.right().value()); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value())); + return result; + } + GraphVertex updateElementV = updateElement.left().value(); + + // DE230195 in case resource name changed update TOSCA artifacts + // file names accordingly + String newSystemName = (String) updateElementV.getMetadataProperty(GraphPropertyEnum.SYSTEM_NAME); + if (newSystemName != null && !newSystemName.equals(prevSystemName)) { + Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> resultToscaArt = getDataFromGraph(updateElementV, EdgeLabelEnum.TOSCA_ARTIFACTS); + if (resultToscaArt.isRight()) { + log.debug("Failed to get tosca artifact from graph for tosca element {} error {}", toscaElementId, resultToscaArt.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resultToscaArt.right().value())); + } + + Map<String, ArtifactDataDefinition> toscaArtifacts = resultToscaArt.left().value(); + if (toscaArtifacts != null) { + for (Entry<String, ArtifactDataDefinition> artifact : toscaArtifacts.entrySet()) { + generateNewToscaFileName(toscaElementToUpdate.getComponentType().getValue().toLowerCase(), newSystemName, artifact.getValue()); + } + // TODO call to new Artifact operation in order to update list of artifacts + + } + // US833308 VLI in service - specific network_role property value logic + if (ComponentTypeEnum.SERVICE == toscaElementToUpdate.getComponentType()) { + // update method logs success/error and returns boolean (true if nothing fails) + // TODO!!!! + // updateServiceNameInVLIsNetworkRolePropertyValues(component, prevSystemName, newSystemName); + } + } + + if (toscaElementToUpdate.getComponentType() == ComponentTypeEnum.RESOURCE) { + StorageOperationStatus resultDerived = updateDerived(toscaElementToUpdate, updateElementV); + if (resultDerived != StorageOperationStatus.OK) { + log.debug("Failed to update from derived data for element {} error {}", toscaElementId, resultDerived); + return Either.right(resultDerived); + } + } + + Either<T, StorageOperationStatus> updatedResource = getToscaElement(updateElementV, filterResult); + if (updatedResource.isRight()) { + log.error("Failed to fetch tosca element {} after update , error {}", toscaElementId, updatedResource.right().value()); + result = Either.right(StorageOperationStatus.BAD_REQUEST); + return result; + } + + T updatedResourceValue = updatedResource.left().value(); + result = Either.left(updatedResourceValue); + + return result; + } + + protected StorageOperationStatus moveLastModifierEdge(GraphVertex elementV, GraphVertex modifierV) { + return DaoStatusConverter.convertTitanStatusToStorageStatus(titanDao.moveEdge(elementV, modifierV, EdgeLabelEnum.LAST_MODIFIER, Direction.IN)); + } + + protected StorageOperationStatus moveCategoryEdge(GraphVertex elementV, GraphVertex categoryV) { + return DaoStatusConverter.convertTitanStatusToStorageStatus(titanDao.moveEdge(elementV, categoryV, EdgeLabelEnum.CATEGORY, Direction.OUT)); + } + + private void generateNewToscaFileName(String componentType, String componentName, ArtifactDataDefinition artifactInfo) { + Map<String, Object> getConfig = (Map<String, Object>) ConfigurationManager.getConfigurationManager().getConfiguration().getToscaArtifacts().entrySet().stream().filter(p -> p.getKey().equalsIgnoreCase(artifactInfo.getArtifactLabel())) + .findAny().get().getValue(); + artifactInfo.setArtifactName(componentType + "-" + componentName + getConfig.get("artifactName")); + } + + protected <T extends ToscaElement> StorageOperationStatus validateResourceCategory(T toscaElementToUpdate, GraphVertex elementV) { + StorageOperationStatus status = StorageOperationStatus.OK; + List<CategoryDefinition> newCategoryList = toscaElementToUpdate.getCategories(); + CategoryDefinition newCategory = newCategoryList.get(0); + + Either<GraphVertex, TitanOperationStatus> childVertex = titanDao.getChildVertex(elementV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse); + if (childVertex.isRight()) { + log.debug("failed to fetch {} for tosca element with id {}, error {}", EdgeLabelEnum.CATEGORY, elementV.getUniqueId(), childVertex.right().value()); + return DaoStatusConverter.convertTitanStatusToStorageStatus(childVertex.right().value()); + } + GraphVertex subCategoryV = childVertex.left().value(); + Map<GraphPropertyEnum, Object> metadataProperties = subCategoryV.getMetadataProperties(); + String subCategoryNameCurrent = (String) metadataProperties.get(GraphPropertyEnum.NAME); + + Either<GraphVertex, TitanOperationStatus> parentVertex = titanDao.getParentVertex(subCategoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse); + if (parentVertex.isRight()) { + log.debug("failed to fetch {} for category with id {}, error {}", EdgeLabelEnum.SUB_CATEGORY, subCategoryV.getUniqueId(), parentVertex.right().value()); + return DaoStatusConverter.convertTitanStatusToStorageStatus(childVertex.right().value()); + } + GraphVertex categoryV = parentVertex.left().value(); + metadataProperties = categoryV.getMetadataProperties(); + String categoryNameCurrent = (String) metadataProperties.get(GraphPropertyEnum.NAME); + + boolean categoryWasChanged = false; + + String newCategoryName = newCategory.getName(); + SubCategoryDefinition newSubcategory = newCategory.getSubcategories().get(0); + String newSubCategoryName = newSubcategory.getName(); + if (newCategoryName != null && false == newCategoryName.equals(categoryNameCurrent)) { + // the category was changed + categoryWasChanged = true; + } else { + // the sub-category was changed + if (newSubCategoryName != null && false == newSubCategoryName.equals(subCategoryNameCurrent)) { + log.debug("Going to update the category of the resource from {} to {}", categoryNameCurrent, newCategory); + categoryWasChanged = true; + } + } + if (categoryWasChanged) { + Either<GraphVertex, StorageOperationStatus> getCategoryVertex = getResourceCategoryVertex(elementV.getUniqueId(), newSubCategoryName, newCategoryName); + + if (getCategoryVertex.isRight()) { + return getCategoryVertex.right().value(); + } + GraphVertex newCategoryV = getCategoryVertex.left().value(); + status = moveCategoryEdge(elementV, newCategoryV); + log.debug("Going to update the category of the resource from {} to {}. status is {}", categoryNameCurrent, newCategory, status); + } + return status; + } + + 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, excludeTypes, JsonParseFlagEnum.NoParse); + } else { + listOfComponents = getListOfHighestAndAllCertifiedComponents(componentType, excludeTypes); + } + + if (listOfComponents.isRight() && listOfComponents.right().value() != TitanOperationStatus.NOT_FOUND) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(listOfComponents.right().value())); + } + List<T> result = new ArrayList<>(); + if (listOfComponents.isLeft()) { + List<GraphVertex> highestAndAllCertified = listOfComponents.left().value(); + if (highestAndAllCertified != null && false == highestAndAllCertified.isEmpty()) { + for (GraphVertex vertexComponent : highestAndAllCertified) { + Either<T, StorageOperationStatus> component = getLightComponent(vertexComponent, componentType, new ComponentParametersView(true)); + if (component.isRight()) { + 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()); + } + } + } + } + return Either.left(result); + } + + public Either<List<CatalogComponent>, StorageOperationStatus> getElementCatalogData() { + List<CatalogComponent> results = new ArrayList<>(); + StopWatch stopWatch = new StopWatch(); + stopWatch.start(); + + Either<Iterator<Vertex>, TitanOperationStatus> verticesEither = titanDao.getCatalogVerticies(); + if (verticesEither.isRight()) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(verticesEither.right().value())); + } + Iterator<Vertex> vertices = verticesEither.left().value(); + while (vertices.hasNext()) { + Vertex vertex = vertices.next(); + VertexProperty<Object> property = vertex.property(GraphPropertiesDictionary.METADATA.getProperty()); + String json = (String) property.value(); + + CatalogComponent catalogComponent = new CatalogComponent(); + Map<String, Object> metadatObj = JsonParserUtils.toMap(json); + + catalogComponent.setComponentType(ComponentTypeEnum.valueOf((String) metadatObj.get(JsonPresentationFields.COMPONENT_TYPE.getPresentation()))); + catalogComponent.setVersion((String) metadatObj.get(JsonPresentationFields.VERSION.getPresentation())); + catalogComponent.setName((String) metadatObj.get(JsonPresentationFields.NAME.getPresentation())); + catalogComponent.setIcon((String) metadatObj.get(JsonPresentationFields.ICON.getPresentation())); + catalogComponent.setUniqueId((String) metadatObj.get(JsonPresentationFields.UNIQUE_ID.getPresentation())); + catalogComponent.setLifecycleState((String) metadatObj.get(JsonPresentationFields.LIFECYCLE_STATE.getPresentation())); + catalogComponent.setLastUpdateDate((Long) metadatObj.get(JsonPresentationFields.LAST_UPDATE_DATE.getPresentation())); + catalogComponent.setDistributionStatus((String) metadatObj.get(JsonPresentationFields.DISTRIBUTION_STATUS.getPresentation())); + Object resourceType = metadatObj.get(JsonPresentationFields.RESOURCE_TYPE.getPresentation()); + if (resourceType != null) { + catalogComponent.setResourceType((String) resourceType); + } + + if (catalogComponent.getComponentType() == ComponentTypeEnum.SERVICE) { + setServiceCategoryFromGraphV(vertex, catalogComponent); + + } else { + setResourceCategoryFromGraphV(vertex, catalogComponent); + } + results.add(catalogComponent); + + } + stopWatch.stop(); + String timeToFetchElements = stopWatch.prettyPrint(); + log.info("time to fetch all catalog elements: {}", timeToFetchElements); + return Either.left(results); + } + + public Either<List<GraphVertex>, TitanOperationStatus> getListOfHighestComponents(ComponentTypeEnum componentType, List<ResourceTypeEnum> excludeTypes, JsonParseFlagEnum parseFlag) { + 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); + } + propertiesHasNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); + + return titanDao.getByCriteria(null, propertiesToMatch, propertiesHasNotToMatch, parseFlag); + } + + // 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, JsonParseFlagEnum.ParseMetadata); + + 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); + } + + propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_DELETED, true); + propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + + Either<List<GraphVertex>, TitanOperationStatus> certifiedNotHighestNodes = titanDao.getByCriteria(null, propertiesToMatchCertified, propertiesHasNotToMatchCertified, JsonParseFlagEnum.ParseMetadata); + 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 (certifiedNotHighestNodes.isLeft()) { + allNodes.addAll(certifiedNotHighestNodes.left().value()); + } + if (highestNodes.isLeft()) { + allNodes.addAll(highestNodes.left().value()); + } + + log.debug("Fetch catalog {}s all states from graph took {} ms", componentType, endFetchAllStates - startFetchAllStates); + return Either.left(allNodes); + } + + protected Either<List<GraphVertex>, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) { + + // get all components marked for delete + Map<GraphPropertyEnum, Object> props = new HashMap<GraphPropertyEnum, Object>(); + props.put(GraphPropertyEnum.IS_DELETED, true); + props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); + + Either<List<GraphVertex>, TitanOperationStatus> componentsToDelete = titanDao.getByCriteria(null, props, JsonParseFlagEnum.NoParse); + + if (componentsToDelete.isRight()) { + TitanOperationStatus error = componentsToDelete.right().value(); + if (error.equals(TitanOperationStatus.NOT_FOUND)) { + log.trace("no components to delete"); + return Either.left(new ArrayList<>()); + } else { + log.info("failed to find components to delete. error : {}", error.name()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error)); + } + } + return Either.left(componentsToDelete.left().value()); + } + + protected TitanOperationStatus setAdditionalInformationFromGraph(GraphVertex componentV, ToscaElement toscaElement) { + Either<Map<String, AdditionalInfoParameterDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.ADDITIONAL_INFORMATION); + if (result.isLeft()) { + toscaElement.setAdditionalInformation(result.left().value()); + } else { + if (result.right().value() != TitanOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return TitanOperationStatus.OK; + } + + // -------------------------------------------- + public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> getToscaElement(String uniqueId, ComponentParametersView componentParametersView); + + public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> getToscaElement(GraphVertex toscaElementVertex, ComponentParametersView componentParametersView); + + public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> deleteToscaElement(GraphVertex toscaElementVertex); + + public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> createToscaElement(ToscaElement toscaElement); + + protected abstract <T extends ToscaElement> TitanOperationStatus setCategoriesFromGraph(GraphVertex vertexComponent, T toscaElement); + + protected abstract <T extends ToscaElement> TitanOperationStatus setCapabilitiesFromGraph(GraphVertex componentV, T toscaElement); + + protected abstract <T extends ToscaElement> TitanOperationStatus setRequirementsFromGraph(GraphVertex componentV, T toscaElement); + + protected abstract <T extends ToscaElement> StorageOperationStatus validateCategories(T toscaElementToUpdate, GraphVertex elementV); + + protected abstract <T extends ToscaElement> StorageOperationStatus updateDerived(T toscaElementToUpdate, GraphVertex updateElementV); - public abstract <T extends ToscaElement> void fillToscaElementVertexData(GraphVertex elementV, T toscaElementToUpdate, JsonParseFlagEnum flag); + public abstract <T extends ToscaElement> void fillToscaElementVertexData(GraphVertex elementV, T toscaElementToUpdate, JsonParseFlagEnum flag); } 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 15fb63f14c..647234d892 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 @@ -20,21 +20,7 @@ package org.openecomp.sdc.be.model.jsontitan.operations; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.Set; -import java.util.function.BiPredicate; -import java.util.stream.Collectors; - +import fj.data.Either; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; @@ -45,43 +31,14 @@ import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -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.elements.*; 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.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.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.RelationshipInfo; -import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; -import org.openecomp.sdc.be.model.RequirementDefinition; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.Service; -import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.*; +import org.openecomp.sdc.be.model.catalog.CatalogComponent; 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.utils.ModelConverter; @@ -96,7 +53,10 @@ 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.function.BiPredicate; +import java.util.stream.Collectors; @org.springframework.stereotype.Component("tosca-operation-facade") public class ToscaOperationFacade { @@ -128,7 +88,7 @@ public class ToscaOperationFacade { public <T extends Component> Either<T, StorageOperationStatus> getToscaFullElement(String componentId) { ComponentParametersView filters = new ComponentParametersView(); filters.setIgnoreCapabiltyProperties(false); - + filters.setIgnoreForwardingPath(false); return getToscaElement(componentId, filters); } @@ -202,7 +162,7 @@ public class ToscaOperationFacade { String componentId = componentV.getUniqueId(); if (toscaOperation != null) { log.debug("Need to fetch tosca element for id {}", componentId); - toscaElement = toscaOperation.getToscaElement(componentV, filters); + toscaElement = toscaOperation.getToscaElement(componentV, filters); } else { log.debug("not supported tosca type {} for id {}", label, componentId); toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST); @@ -328,7 +288,10 @@ public class ToscaOperationFacade { } public <T extends Component> Either<T, StorageOperationStatus> getFullLatestComponentByToscaResourceName(String toscaResourceName) { - return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName, JsonParseFlagEnum.ParseAll); + ComponentParametersView fetchAllFilter = new ComponentParametersView(); + fetchAllFilter.setIgnoreForwardingPath(true); + fetchAllFilter.setIgnoreCapabiltyProperties(false); + return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName, JsonParseFlagEnum.ParseAll, fetchAllFilter); } public <T extends Component> Either<T, StorageOperationStatus> getLatestByName(String resourceName) { @@ -448,7 +411,7 @@ public class ToscaOperationFacade { public Either<CapabilityDataDefinition, StorageOperationStatus> getFulfilledCapabilityByRelation(String componentId, String instanceId, RequirementCapabilityRelDef relation, BiPredicate<RelationshipInfo, CapabilityDataDefinition> predicate) { return nodeTemplateOperation.getFulfilledCapabilityByRelation(componentId, instanceId, relation, predicate); } - + public StorageOperationStatus associateResourceInstances(String componentId, List<RequirementCapabilityRelDef> relations) { Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> status = nodeTemplateOperation.associateResourceInstances(componentId, relations); if (status.isRight()) { @@ -495,7 +458,7 @@ public class ToscaOperationFacade { * * @param newComponent * @param oldComponent - * @return + * @return vendor */ public Either<Resource, StorageOperationStatus> overrideComponent(Resource newComponent, Resource oldComponent) { @@ -504,8 +467,6 @@ public class ToscaOperationFacade { newComponent.setArtifacts(oldComponent.getArtifacts()); newComponent.setDeploymentArtifacts(oldComponent.getDeploymentArtifacts()); newComponent.setGroups(oldComponent.getGroups()); - List<InputDefinition> newInputs = getNewInputsByResourceType(oldComponent); - newComponent.setInputs(newInputs); newComponent.setLastUpdateDate(null); newComponent.setHighestVersion(true); @@ -584,6 +545,10 @@ public class ToscaOperationFacade { } private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName, JsonParseFlagEnum parseFlag) { + return getLatestByName(property, nodeName, parseFlag, new ComponentParametersView()); + } + + private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName, JsonParseFlagEnum parseFlag, ComponentParametersView filter) { Either<T, StorageOperationStatus> result; Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); @@ -613,7 +578,7 @@ public class ToscaOperationFacade { highestResource = vertex; } } - return getToscaElementByOperation(highestResource); + return getToscaElementByOperation(highestResource, filter); } // endregion @@ -688,6 +653,9 @@ public class ToscaOperationFacade { } return getToscaElementByOperation(getResourceRes.left().value().get(0)); } + public Either<List<CatalogComponent>, StorageOperationStatus> getCatalogComponents() { + return topologyTemplateOperation.getElementCatalogData(); + } // endregion public <T extends Component> Either<List<T>, StorageOperationStatus> getCatalogComponents(ComponentTypeEnum componentType, List<OriginTypeEnum> excludeTypes, boolean isHighestVersions) { @@ -804,7 +772,7 @@ public class ToscaOperationFacade { if (StringUtils.isEmpty(componentInstance.getIcon())) { componentInstance.setIcon(origComponent.getIcon()); } - String nameToFindForCounter = componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy ? PROXY_SUFFIX : origComponent.getName(); + String nameToFindForCounter = componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy ? componentInstance.getSourceModelName() + PROXY_SUFFIX : origComponent.getName(); String nextComponentInstanceCounter = getNextComponentInstanceCounter(containerComponent, nameToFindForCounter); Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addResult = nodeTemplateOperation.addComponentInstanceToTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), ModelConverter.convertToToscaElement(origComponent), nextComponentInstanceCounter, componentInstance, allowDeleted, user); @@ -1413,8 +1381,6 @@ public class ToscaOperationFacade { // exclude props states.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - states.add(LifecycleStateEnum.READY_FOR_CERTIFICATION); - states.add(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); hasNotProps.put(GraphPropertyEnum.STATE, states); hasNotProps.put(GraphPropertyEnum.IS_DELETED, true); return fetchServicesByCriteria(services, hasProps, hasNotProps); @@ -1611,6 +1577,7 @@ public class ToscaOperationFacade { break; case "service": case "pnf": + case "cr": hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, Arrays.asList(ResourceTypeEnum.VFC.name(), ResourceTypeEnum.VFCMT.name())); break; case "vl": @@ -1685,13 +1652,37 @@ public class ToscaOperationFacade { } - public Either<List<Component>, StorageOperationStatus> getLatestComponentListByUuid(String componentUuid) { + private Either<List<Component>, StorageOperationStatus> getLatestComponentListByUuid(String componentUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) { Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + if (additionalPropertiesToMatch != null) { + propertiesToMatch.putAll(additionalPropertiesToMatch); + } propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); Either<List<Component>, StorageOperationStatus> componentListByUuid = getComponentListByUuid(componentUuid, propertiesToMatch); return componentListByUuid; } + public Either<Component, StorageOperationStatus> getComponentByUuidAndVersion(String componentUuid, String version) { + Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + + propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid); + propertiesToMatch.put(GraphPropertyEnum.VERSION, version); + + 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); + if (vertexEither.isRight()) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value())); + } + + List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null; + if (vertexList == null || vertexList.isEmpty() || vertexList.size() > 1) { + return Either.right(StorageOperationStatus.NOT_FOUND); + } + + return getToscaElementByOperation(vertexList.get(0)); + } + public Either<List<Component>, StorageOperationStatus> getComponentListByUuid(String componentUuid, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) { Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); @@ -1743,9 +1734,19 @@ public class ToscaOperationFacade { return Either.left(latestComponents); } + public Either<Component, StorageOperationStatus> getLatestServiceByUuid(String serviceUuid) { + Map<GraphPropertyEnum, Object> propertiesToMatch = new HashMap<>(); + propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); + return getLatestComponentByUuid(serviceUuid, propertiesToMatch); + } + public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid) { + return getLatestComponentByUuid(componentUuid, null); + } + + public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid, Map<GraphPropertyEnum, Object> propertiesToMatch) { - Either<List<Component>, StorageOperationStatus> latestVersionListEither = getLatestComponentListByUuid(componentUuid); + Either<List<Component>, StorageOperationStatus> latestVersionListEither = getLatestComponentListByUuid(componentUuid, propertiesToMatch); if (latestVersionListEither.isRight()) { return Either.right(latestVersionListEither.right().value()); @@ -1927,7 +1928,9 @@ public class ToscaOperationFacade { 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, JsonParseFlagEnum.ParseMetadata); + Map<GraphPropertyEnum, Object> propsHasNotToMatch = new HashMap<>(); + propsHasNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); + Either<List<GraphVertex>, TitanOperationStatus> resourcesByTypeEither = titanDao.getByCriteria(null, props, propsHasNotToMatch, JsonParseFlagEnum.ParseMetadata); if (resourcesByTypeEither.isRight()) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resourcesByTypeEither.right().value())); @@ -2311,12 +2314,12 @@ public class ToscaOperationFacade { 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<GroupDefinition>, StorageOperationStatus> updateGroupsOnComponent(Component component, List<GroupDataDefinition> updatedGroups) { + return groupsOperation.updateGroups(component, updatedGroups); } public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstancesOnComponent(Component component, ComponentTypeEnum componentType, String instanceId, List<GroupInstance> updatedGroupInstances) { - return groupsOperation.updateGroupInstances(component, componentType, instanceId, updatedGroupInstances); + return groupsOperation.updateGroupInstances(component, instanceId, updatedGroupInstances); } public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupInstance> groupInstances) { @@ -2368,6 +2371,17 @@ public class ToscaOperationFacade { return nodeTemplateOperation.updateComponentInstanceCapabilityProperty(containerComponent, componentInstanceUniqueId, capabilityUniqueId, property); } + public StorageOperationStatus updateComponentInstanceCapabilityProperties(Component containerComponent, String componentInstanceUniqueId) { + return convertComponentInstanceProperties(containerComponent, componentInstanceUniqueId) + .map(instanceCapProps -> topologyTemplateOperation.updateComponentInstanceCapabilityProperties(containerComponent, componentInstanceUniqueId, instanceCapProps)) + .orElse(StorageOperationStatus.NOT_FOUND); + } + + public StorageOperationStatus updateComponentCalculatedCapabilitiesProperties(Component containerComponent) { + Map<String, MapCapabiltyProperty> mapCapabiltyPropertyMap = convertComponentCapabilitiesProperties(containerComponent); + return nodeTemplateOperation.overrideComponentCapabilitiesProperties(containerComponent, mapCapabiltyPropertyMap); + } + public StorageOperationStatus deleteAllCalculatedCapabilitiesRequirements(String topologyTemplateId) { StorageOperationStatus status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES); if (status == StorageOperationStatus.OK) { @@ -2402,15 +2416,94 @@ public class ToscaOperationFacade { return Either.left(clonedResource); } /** - * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name and type + * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId * @param componentId * @param instanceId * @param capabilityName * @param capabilityType + * @param ownerId * @return */ - public Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityName, String capabilityType) { - return topologyTemplateOperation.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType); + public Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityName, String capabilityType, String ownerId) { + return topologyTemplateOperation.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId); + } + + private Map<String, MapCapabiltyProperty> convertComponentCapabilitiesProperties(Component currComponent) { + return currComponent.getComponentInstances() + .stream() + .collect(Collectors.toMap(ComponentInstanceDataDefinition::getUniqueId, + ci -> ModelConverter.convertToMapOfMapCapabiltyProperties(ci.getCapabilities(), ci.getUniqueId(), true))); + } + + private Optional<MapCapabiltyProperty> convertComponentInstanceProperties(Component component, String instanceId) { + return component.fetchInstanceById(instanceId) + .map(ci -> ModelConverter.convertToMapOfMapCapabiltyProperties(ci.getCapabilities(),instanceId)); } + public Either<PolicyDefinition, StorageOperationStatus> associatePolicyToComponent(String componentId, PolicyDefinition policyDefinition, int counter) { + Either<PolicyDefinition, StorageOperationStatus> result = null; + Either<GraphVertex, TitanOperationStatus> getVertexEither; + getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata); + if (getVertexEither.isRight()) { + log.error("Couldn't fetch a component with and UniqueId {}, error: {}", componentId, getVertexEither.right().value()); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); + } else { + if(getVertexEither.left().value().getLabel() != VertexTypeEnum.TOPOLOGY_TEMPLATE){ + log.error("Policy association to component of Tosca type {} is not allowed. ", getVertexEither.left().value().getLabel()); + result = Either.right(StorageOperationStatus.BAD_REQUEST); + } + } + if(result == null){ + StorageOperationStatus status = topologyTemplateOperation.addPolicyToToscaElement(getVertexEither.left().value(), policyDefinition, counter); + if(status != StorageOperationStatus.OK){ + return Either.right(status); + } + } + if(result == null){ + result = Either.left(policyDefinition); + } + return result; + } + + public Either<PolicyDefinition, StorageOperationStatus> updatePolicyOfComponent(String componentId, PolicyDefinition policyDefinition) { + Either<PolicyDefinition, StorageOperationStatus> result = null; + Either<GraphVertex, TitanOperationStatus> getVertexEither; + getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + log.error("Couldn't fetch a component with and UniqueId {}, error: {}", componentId, getVertexEither.right().value()); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); + } + if(result == null){ + StorageOperationStatus status = topologyTemplateOperation.updatePolicyOfToscaElement(getVertexEither.left().value(), policyDefinition); + if(status != StorageOperationStatus.OK){ + return Either.right(status); + } + } + if(result == null){ + result = Either.left(policyDefinition); + } + return result; + } + + public StorageOperationStatus updatePoliciesOfComponent(String componentId, List<PolicyDefinition> policyDefinition) { + log.debug("#updatePoliciesOfComponent - updating policies for component {}", componentId); + return titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse) + .right() + .map(DaoStatusConverter::convertTitanStatusToStorageStatus) + .either(containerVertex -> topologyTemplateOperation.updatePoliciesOfToscaElement(containerVertex, policyDefinition), + err -> err); + } + + public StorageOperationStatus removePolicyFromComponent(String componentId, String policyId) { + StorageOperationStatus status = null; + Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + log.error("Couldn't fetch a component with and UniqueId {}, error: {}", componentId, getVertexEither.right().value()); + status = DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()); + } + if(status == null){ + status = topologyTemplateOperation.removePolicyFromToscaElement(getVertexEither.left().value(), policyId); + } + return status; + } } |