diff options
Diffstat (limited to 'catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan')
26 files changed, 13289 insertions, 12447 deletions
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/NodeType.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/NodeType.java index c6157ba252..7ac941e5e2 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/NodeType.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/NodeType.java @@ -20,89 +20,79 @@ package org.openecomp.sdc.be.model.jsontitan.datamodel; +import org.openecomp.sdc.be.datatypes.elements.*; + import java.util.List; import java.util.Map; -import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; - public class NodeType extends ToscaElement{ - public NodeType() { - super(ToscaElementTypeEnum.NodeType); - } - - private List<String> derivedFrom; - private List<String> derivedList; - - private Map<String, PropertyDataDefinition> attributes; - private Map<String, ListCapabilityDataDefinition> capabilties; - private Map<String, MapPropertiesDataDefinition> capabiltiesProperties; - private Map<String, ListRequirementDataDefinition> requirements; - private Map<String, InterfaceDataDefinition> interfaceArtifacts; - - - // will be used in future - // private Map<String, Map<String, Object>> other; - - - public List<String> getDerivedList() { - return derivedList; - } - - public void setDerivedList(List<String> derivedList) { - this.derivedList = derivedList; - } - - public List<String> getDerivedFrom() { - return derivedFrom; - } - - public void setDerivedFrom(List<String> derivedFrom) { - this.derivedFrom = derivedFrom; - } - - public Map<String, PropertyDataDefinition> getAttributes() { - return attributes; - } - - public void setAttributes(Map<String, PropertyDataDefinition> attributes) { - this.attributes = attributes; - } - - public Map<String, ListCapabilityDataDefinition> getCapabilties() { - return capabilties; - } - - public void setCapabilties(Map<String, ListCapabilityDataDefinition> capabilties) { - this.capabilties = capabilties; - } - - public Map<String, ListRequirementDataDefinition> getRequirements() { - return requirements; - } - - public void setRequirements(Map<String, ListRequirementDataDefinition> requirements) { - this.requirements = requirements; - } - - public Map<String, MapPropertiesDataDefinition> getCapabiltiesProperties() { - return capabiltiesProperties; - } - - public void setCapabiltiesProperties(Map<String, MapPropertiesDataDefinition> capabiltiesProperties) { - this.capabiltiesProperties = capabiltiesProperties; - } - - public Map<String, InterfaceDataDefinition> getInterfaceArtifacts() { - return interfaceArtifacts; - } - - public void setInterfaceArtifacts(Map<String, InterfaceDataDefinition> interfaceArtifacts) { - this.interfaceArtifacts = interfaceArtifacts; - } + public NodeType() { + super(ToscaElementTypeEnum.NODE_TYPE); + } + + private List<String> derivedFrom; + private List<String> derivedList; + private Map<String, PropertyDataDefinition> attributes; + private Map<String, ListCapabilityDataDefinition> capabilties; + private Map<String, MapPropertiesDataDefinition> capabiltiesProperties; + private Map<String, ListRequirementDataDefinition> requirements; + private Map<String, InterfaceDataDefinition> interfaceArtifacts; + + public List<String> getDerivedList() { + return derivedList; + } + + public void setDerivedList(List<String> derivedList) { + this.derivedList = derivedList; + } + + public List<String> getDerivedFrom() { + return derivedFrom; + } + + public void setDerivedFrom(List<String> derivedFrom) { + this.derivedFrom = derivedFrom; + } + + public Map<String, PropertyDataDefinition> getAttributes() { + return attributes; + } + + public void setAttributes(Map<String, PropertyDataDefinition> attributes) { + this.attributes = attributes; + } + + public Map<String, ListCapabilityDataDefinition> getCapabilties() { + return capabilties; + } + + public void setCapabilties(Map<String, ListCapabilityDataDefinition> capabilties) { + this.capabilties = capabilties; + } + + public Map<String, ListRequirementDataDefinition> getRequirements() { + return requirements; + } + + public void setRequirements(Map<String, ListRequirementDataDefinition> requirements) { + this.requirements = requirements; + } + + public Map<String, MapPropertiesDataDefinition> getCapabiltiesProperties() { + return capabiltiesProperties; + } + + public void setCapabiltiesProperties(Map<String, MapPropertiesDataDefinition> capabiltiesProperties) { + this.capabiltiesProperties = capabiltiesProperties; + } + + public Map<String, InterfaceDataDefinition> getInterfaceArtifacts() { + return interfaceArtifacts; + } + + public void setInterfaceArtifacts(Map<String, InterfaceDataDefinition> interfaceArtifacts) { + this.interfaceArtifacts = interfaceArtifacts; + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/TopologyTemplate.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/TopologyTemplate.java index 567258d0d5..36d597e7be 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/TopologyTemplate.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/TopologyTemplate.java @@ -20,239 +20,217 @@ package org.openecomp.sdc.be.model.jsontitan.datamodel; -import java.util.HashMap; -import java.util.Map; - import org.apache.commons.collections.MapUtils; -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.ForwardingPathDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapCapabiltyProperty; -import org.openecomp.sdc.be.datatypes.elements.MapComponentInstanceExternalRefs; -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.PolicyDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.RelationshipInstDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.*; +import org.openecomp.sdc.be.datatypes.elements.MapCapabilityProperty; +import org.openecomp.sdc.be.datatypes.elements.MapListCapabilityDataDefinition; import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; import org.openecomp.sdc.be.model.jsontitan.enums.JsonConstantKeysEnum; +import java.util.HashMap; +import java.util.Map; + public class TopologyTemplate extends ToscaElement{ - public TopologyTemplate() { - super(ToscaElementTypeEnum.TopologyTemplate); - } - private Map<String, PropertyDataDefinition> inputs; - private Map<String, MapPropertiesDataDefinition> instInputs; - private Map<String, ? extends ToscaDataDefinition> heatParameters; - private Map<String, MapPropertiesDataDefinition> instAttributes; - private Map<String, MapPropertiesDataDefinition> instProperties; - private Map<String, GroupDataDefinition> groups; - private Map<String, PolicyDataDefinition> policies; - private Map<String, MapGroupsDataDefinition> instGroups; - private Map<String, ArtifactDataDefinition> serviceApiArtifacts; - private Map<String, ForwardingPathDataDefinition> forwardingPaths; - private Map<String, CompositionDataDefinition> compositions; + public TopologyTemplate() { + super(ToscaElementTypeEnum.TOPOLOGY_TEMPLATE); + } + private Map<String, PropertyDataDefinition> inputs; + private Map<String, MapPropertiesDataDefinition> instInputs; + private Map<String, ? extends ToscaDataDefinition> heatParameters; + private Map<String, MapPropertiesDataDefinition> instAttributes; + private Map<String, MapPropertiesDataDefinition> instProperties; + private Map<String, GroupDataDefinition> groups; + private Map<String, PolicyDataDefinition> policies; + private Map<String, MapGroupsDataDefinition> instGroups; + private Map<String, ArtifactDataDefinition> serviceApiArtifacts; + private Map<String, ForwardingPathDataDefinition> forwardingPaths; + private Map<String, CompositionDataDefinition> compositions; + private Map<String, MapListCapabilityDataDefinition> calculatedCapabilities; + private Map<String, MapListRequirementDataDefinition> calculatedRequirements; + private Map<String, MapListCapabilityDataDefinition> fullfilledCapabilities; + private Map<String, MapListRequirementDataDefinition> fullfilledRequirements; + private Map<String, MapCapabilityProperty> calculatedCapabilitiesProperties; + private Map<String, MapArtifactDataDefinition> instDeploymentArtifacts; + private Map<String, MapArtifactDataDefinition> instanceArtifacts; + + //Component Instances External References (instanceId -> ExternalRefsMap) + //----------------------------------------------------------------------- + private Map<String, MapComponentInstanceExternalRefs> mapComponentInstancesExternalRefs; + + public Map<String, MapComponentInstanceExternalRefs> getMapComponentInstancesExternalRefs() { + return this.mapComponentInstancesExternalRefs; + } + + public void setComponentInstancesExternalRefs(Map<String, MapComponentInstanceExternalRefs> mapComponentInstancesExternalRefs) { + this.mapComponentInstancesExternalRefs = mapComponentInstancesExternalRefs; + } + //----------------------------------------------------------------------- + + + public Map<String, PropertyDataDefinition> getInputs() { + return inputs; + } + public void setInputs(Map<String, PropertyDataDefinition> inputs) { + this.inputs = inputs; + } + public Map<String, MapPropertiesDataDefinition> getInstInputs() { + return instInputs; + } + public void setInstInputs(Map<String, MapPropertiesDataDefinition> instInputs) { + this.instInputs = instInputs; + } + public Map<String, ? extends ToscaDataDefinition> getHeatParameters() { + return heatParameters; + } + public void setHeatParameters(Map<String, ? extends ToscaDataDefinition> heatParameters) { + this.heatParameters = heatParameters; + } + public Map<String, MapPropertiesDataDefinition> getInstAttributes() { + return instAttributes; + } + public void setInstAttributes(Map<String, MapPropertiesDataDefinition> instAttributes) { + this.instAttributes = instAttributes; + } + public Map<String, MapPropertiesDataDefinition> getInstProperties() { + return instProperties; + } + public void setInstProperties(Map<String, MapPropertiesDataDefinition> instProperties) { + this.instProperties = instProperties; + } + public Map<String, GroupDataDefinition> getGroups() { + return groups; + } + public void setGroups(Map<String, GroupDataDefinition> groups) { + this.groups = groups; + } + public Map<String, PolicyDataDefinition> getPolicies() { + return policies; + } + public void setPolicies(Map<String, PolicyDataDefinition> policies) { + this.policies = policies; + } + public Map<String, MapGroupsDataDefinition> getInstGroups() { + return instGroups; + } + public void setInstGroups(Map<String, MapGroupsDataDefinition> instGroups) { + this.instGroups = instGroups; + } + public Map<String, ArtifactDataDefinition> getServiceApiArtifacts() { + return serviceApiArtifacts; + } + public void setServiceApiArtifacts(Map<String, ArtifactDataDefinition> serviceApiArtifacts) { + this.serviceApiArtifacts = serviceApiArtifacts; + } + public Map<String, CompositionDataDefinition> getCompositions() { + return compositions; + } + public void setCompositions(Map<String, CompositionDataDefinition> compositions) { + this.compositions = compositions; + } + public Map<String, MapListCapabilityDataDefinition> getCalculatedCapabilities() { + return calculatedCapabilities; + } + public void setCalculatedCapabilities(Map<String, MapListCapabilityDataDefinition> calculatedCapabilities) { + this.calculatedCapabilities = calculatedCapabilities; + } + public Map<String, MapListRequirementDataDefinition> getCalculatedRequirements() { + return calculatedRequirements; + } + public void setCalculatedRequirements(Map<String, MapListRequirementDataDefinition> calculatedRequirements) { + this.calculatedRequirements = calculatedRequirements; + } + public Map<String, MapListCapabilityDataDefinition> getFullfilledCapabilities() { + return fullfilledCapabilities; + } + public void setFullfilledCapabilities(Map<String, MapListCapabilityDataDefinition> fullfilledCapabilities) { + this.fullfilledCapabilities = fullfilledCapabilities; + } + public Map<String, MapListRequirementDataDefinition> getFullfilledRequirements() { + return fullfilledRequirements; + } + public void setFullfilledRequirements(Map<String, MapListRequirementDataDefinition> fullfilledRequirements) { + this.fullfilledRequirements = fullfilledRequirements; + } - private Map<String, MapListCapabiltyDataDefinition> calculatedCapabilities; - private Map<String, MapListRequirementDataDefinition> calculatedRequirements; - private Map<String, MapListCapabiltyDataDefinition> fullfilledCapabilities; - private Map<String, MapListRequirementDataDefinition> fullfilledRequirements; - - private Map<String, MapCapabiltyProperty> calculatedCapabilitiesProperties; - - private Map<String, MapArtifactDataDefinition> instDeploymentArtifacts; - private Map<String, MapArtifactDataDefinition> instanceArtifacts; - private Map<String, InterfaceDataDefinition> interfaces; + public Map<String, MapArtifactDataDefinition> getInstDeploymentArtifacts() { + return instDeploymentArtifacts; + } + public void setInstDeploymentArtifacts(Map<String, MapArtifactDataDefinition> instDeploymentArtifacts) { + this.instDeploymentArtifacts = instDeploymentArtifacts; + } - //Component Instances External References (instanceId -> ExternalRefsMap) - //----------------------------------------------------------------------- - private Map<String, MapComponentInstanceExternalRefs> mapComponentInstancesExternalRefs; - public Map<String, MapComponentInstanceExternalRefs> getMapComponentInstancesExternalRefs() { - return this.mapComponentInstancesExternalRefs; - } - public void setComponentInstancesExternalRefs(Map<String, MapComponentInstanceExternalRefs> mapComponentInstancesExternalRefs) { - this.mapComponentInstancesExternalRefs = mapComponentInstancesExternalRefs; - } - //----------------------------------------------------------------------- + public Map<String, MapCapabilityProperty> getCalculatedCapabilitiesProperties() { + return calculatedCapabilitiesProperties; + } + public void setCalculatedCapabilitiesProperties(Map<String, MapCapabilityProperty> calculatedCapabilitiesProperties) { + this.calculatedCapabilitiesProperties = calculatedCapabilitiesProperties; + } - public Map<String, InterfaceDataDefinition> getInterfaces() { - return interfaces; - } + public Map<String, MapArtifactDataDefinition> getInstanceArtifacts() { + return instanceArtifacts; + } + public void setInstanceArtifacts(Map<String, MapArtifactDataDefinition> instanceArtifacts) { + this.instanceArtifacts = instanceArtifacts; + } - public void setInterfaces(Map<String, InterfaceDataDefinition> interfaces) { - this.interfaces = interfaces; - } + public Map<String, ForwardingPathDataDefinition> getForwardingPaths() { + return forwardingPaths; + } - public Map<String, PropertyDataDefinition> getInputs() { - return inputs; - } - public void setInputs(Map<String, PropertyDataDefinition> inputs) { - this.inputs = inputs; - } - public Map<String, MapPropertiesDataDefinition> getInstInputs() { - return instInputs; - } - public void setInstInputs(Map<String, MapPropertiesDataDefinition> instInputs) { - this.instInputs = instInputs; - } - public Map<String, ? extends ToscaDataDefinition> getHeatParameters() { - return heatParameters; - } - public void setHeatParameters(Map<String, ? extends ToscaDataDefinition> heatParameters) { - this.heatParameters = heatParameters; - } - public Map<String, MapPropertiesDataDefinition> getInstAttributes() { - return instAttributes; - } - public void setInstAttributes(Map<String, MapPropertiesDataDefinition> instAttributes) { - this.instAttributes = instAttributes; - } - public Map<String, MapPropertiesDataDefinition> getInstProperties() { - return instProperties; - } - public void setInstProperties(Map<String, MapPropertiesDataDefinition> instProperties) { - this.instProperties = instProperties; - } - public Map<String, GroupDataDefinition> getGroups() { - return groups; - } - public void setGroups(Map<String, GroupDataDefinition> groups) { - this.groups = groups; - } - public Map<String, PolicyDataDefinition> getPolicies() { - return policies; - } - public void setPolicies(Map<String, PolicyDataDefinition> policies) { - this.policies = policies; - } - public Map<String, MapGroupsDataDefinition> getInstGroups() { - return instGroups; - } - public void setInstGroups(Map<String, MapGroupsDataDefinition> instGroups) { - this.instGroups = instGroups; - } - public Map<String, ArtifactDataDefinition> getServiceApiArtifacts() { - return serviceApiArtifacts; - } - public void setServiceApiArtifacts(Map<String, ArtifactDataDefinition> serviceApiArtifacts) { - this.serviceApiArtifacts = serviceApiArtifacts; - } - public Map<String, CompositionDataDefinition> getCompositions() { - return compositions; - } - public void setCompositions(Map<String, CompositionDataDefinition> compositions) { - this.compositions = compositions; - } - public Map<String, MapListCapabiltyDataDefinition> getCalculatedCapabilities() { - return calculatedCapabilities; - } - public void setCalculatedCapabilities(Map<String, MapListCapabiltyDataDefinition> calculatedCapabilities) { - this.calculatedCapabilities = calculatedCapabilities; - } - public Map<String, MapListRequirementDataDefinition> getCalculatedRequirements() { - return calculatedRequirements; - } - public void setCalculatedRequirements(Map<String, MapListRequirementDataDefinition> calculatedRequirements) { - this.calculatedRequirements = calculatedRequirements; - } - public Map<String, MapListCapabiltyDataDefinition> getFullfilledCapabilities() { - return fullfilledCapabilities; - } - public void setFullfilledCapabilities(Map<String, MapListCapabiltyDataDefinition> fullfilledCapabilities) { - this.fullfilledCapabilities = fullfilledCapabilities; - } - public Map<String, MapListRequirementDataDefinition> getFullfilledRequirements() { - return fullfilledRequirements; - } - public void setFullfilledRequirements(Map<String, MapListRequirementDataDefinition> fullfilledRequirements) { - this.fullfilledRequirements = fullfilledRequirements; - } - - public Map<String, MapArtifactDataDefinition> getInstDeploymentArtifacts() { - return instDeploymentArtifacts; - } - public void setInstDeploymentArtifacts(Map<String, MapArtifactDataDefinition> instDeploymentArtifacts) { - this.instDeploymentArtifacts = instDeploymentArtifacts; - } - - public Map<String, MapCapabiltyProperty> getCalculatedCapabilitiesProperties() { - return calculatedCapabilitiesProperties; - } - public void setCalculatedCapabilitiesProperties(Map<String, MapCapabiltyProperty> calculatedCapabilitiesProperties) { - this.calculatedCapabilitiesProperties = calculatedCapabilitiesProperties; - } - - public Map<String, MapArtifactDataDefinition> getInstanceArtifacts() { - return instanceArtifacts; - } - public void setInstanceArtifacts(Map<String, MapArtifactDataDefinition> instanceArtifacts) { - this.instanceArtifacts = instanceArtifacts; - } + public void setForwardingPaths(Map<String, ForwardingPathDataDefinition> forwardingPaths) { + this.forwardingPaths = forwardingPaths; + } - public Map<String, ForwardingPathDataDefinition> getForwardingPaths() { - return forwardingPaths; - } + /** + * Adds component instance to composition of topology template + * Note that component instance will be overrided in case if the topology template already contains a component instance with the same name + * @param componentInstance + */ + public void addComponentInstance(ComponentInstanceDataDefinition componentInstance){ + if(getCompositions() == null){ + compositions = new HashMap<>(); + } + if(MapUtils.isEmpty(getCompositions())){ + compositions.put(JsonConstantKeysEnum.COMPOSITION.getValue(), new CompositionDataDefinition()); + } + if(MapUtils.isEmpty(getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()).getComponentInstances())){ + getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()).setComponentInstances(new HashMap<>()); + } + getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()).getComponentInstances().put(componentInstance.getUniqueId(), componentInstance); + } + /** + * Returns map of component instances from composition + * @return + */ + public Map<String, ComponentInstanceDataDefinition> getComponentInstances() { + Map<String, ComponentInstanceDataDefinition> instances = null; + if(getCompositions() != null && getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()) != null ){ + instances = getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()).getComponentInstances(); + } + return instances; + } - public void setForwardingPaths(Map<String, ForwardingPathDataDefinition> forwardingPaths) { - this.forwardingPaths = forwardingPaths; - } - /** - * Adds component instance to composition of topology template - * Note that component instance will be overrided in case if the topology template already contains a component instance with the same name - * @param componentInstance - */ - public void addComponentInstance(ComponentInstanceDataDefinition componentInstance){ - if(getCompositions() == null){ - compositions = new HashMap<>(); - } - if(MapUtils.isEmpty(getCompositions())){ - compositions.put(JsonConstantKeysEnum.COMPOSITION.getValue(), new CompositionDataDefinition()); - } - if(MapUtils.isEmpty(getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()).getComponentInstances())){ - getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()).setComponentInstances(new HashMap<>()); - } - getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()).getComponentInstances().put(componentInstance.getUniqueId(), componentInstance); - } - /** - * Returns map of component instances from composition - * @return - */ - public Map<String, ComponentInstanceDataDefinition> getComponentInstances() { - Map<String, ComponentInstanceDataDefinition> instances = null; - if(getCompositions() != null && getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()) != null ){ - instances = getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()).getComponentInstances(); - } - return instances; - } - - - /** - * Sets map of component instances to composition of topology template - * Note that component instances will be overrided in case if the topology template already contains a component instances - * @param instances - */ - public void setComponentInstances(Map<String, ComponentInstanceDataDefinition> instances) { - if(getCompositions() == null){ - compositions = new HashMap<>(); - } - if(MapUtils.isEmpty(getCompositions())){ - compositions.put(JsonConstantKeysEnum.COMPOSITION.getValue(), new CompositionDataDefinition()); - } - getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()).setComponentInstances(instances); - } - public Map<String, RelationshipInstDataDefinition> getRelations() { - Map<String, RelationshipInstDataDefinition> relations = null; - if( getCompositions() != null && getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()) != null ){ - relations = getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()).getRelations(); - } - return relations; - } + /** + * Sets map of component instances to composition of topology template + * Note that component instances will be overrided in case if the topology template already contains a component instances + * @param instances + */ + public void setComponentInstances(Map<String, ComponentInstanceDataDefinition> instances) { + if(getCompositions() == null){ + compositions = new HashMap<>(); + } + if(MapUtils.isEmpty(getCompositions())){ + compositions.put(JsonConstantKeysEnum.COMPOSITION.getValue(), new CompositionDataDefinition()); + } + getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()).setComponentInstances(instances); + } + public Map<String, RelationshipInstDataDefinition> getRelations() { + Map<String, RelationshipInstDataDefinition> relations = null; + if( getCompositions() != null && getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()) != null ){ + relations = getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()).getRelations(); + } + return relations; + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/ToscaElement.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/ToscaElement.java index 90b32c6165..0f0c63f7fb 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/ToscaElement.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/ToscaElement.java @@ -20,11 +20,6 @@ package org.openecomp.sdc.be.model.jsontitan.datamodel; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; @@ -36,262 +31,284 @@ import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.jsontitan.operations.NodeTypeOperation; import org.slf4j.MDC; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + public abstract class ToscaElement { - - protected Map<String, Object> metadata; - protected List<CategoryDefinition> categories; - protected Map<String, ArtifactDataDefinition> toscaArtifacts; - private Map<String, ArtifactDataDefinition> artifacts; - private Map<String, ArtifactDataDefinition> deploymentArtifacts; - private Map<String, AdditionalInfoParameterDataDefinition> additionalInformation; - private Map<String, PropertyDataDefinition> properties; - - protected ToscaElementTypeEnum toscaType; - // User - private String creatorUserId; - private String creatorFullName; - private String lastUpdaterUserId; - private String lastUpdaterFullName; - - private Map<String, String> allVersions; - - public ToscaElement(ToscaElementTypeEnum toscaType){ - this.toscaType = toscaType; - } - - public Map<String, Object> getMetadata() { - return metadata; - } - - public void setMetadata(Map<String, Object> metadata) { - this.metadata = metadata; - } - - public List<CategoryDefinition> getCategories() { - return categories; - } - - public void setCategories(List<CategoryDefinition> categories) { - this.categories = categories; - } - public Map<String, ArtifactDataDefinition> getToscaArtifacts() { - return toscaArtifacts; - } - - public void setToscaArtifacts(Map<String, ArtifactDataDefinition> toscaArtifacts) { - this.toscaArtifacts = toscaArtifacts; - } - - public ToscaElementTypeEnum getToscaType() { - return toscaType; - } - - public void setToscaType(ToscaElementTypeEnum toscaType) { - this.toscaType = toscaType; - } - public Map<String, ArtifactDataDefinition> getArtifacts() { - return artifacts; - } - - public void setArtifacts(Map<String, ArtifactDataDefinition> artifacts) { - this.artifacts = artifacts; - } - - public Map<String, ArtifactDataDefinition> getDeploymentArtifacts() { - return deploymentArtifacts; - } - - public void setDeploymentArtifacts(Map<String, ArtifactDataDefinition> deploymentArtifacts) { - this.deploymentArtifacts = deploymentArtifacts; - } - public Map<String, AdditionalInfoParameterDataDefinition> getAdditionalInformation() { - return additionalInformation; - } - public void setAdditionalInformation(Map<String, AdditionalInfoParameterDataDefinition> additionalInformation) { - this.additionalInformation = additionalInformation; - } - public Map<String, PropertyDataDefinition> getProperties() { - return properties; - } - public void setProperties(Map<String, PropertyDataDefinition> properties) { - this.properties = properties; - } - - public Map<String, String> getAllVersions() { - return allVersions; - } - - public void setAllVersions(Map<String, String> allVersions) { - this.allVersions = allVersions; - } - - // metadata properties - // ---------------------------- - public Object getMetadataValue(JsonPresentationFields name) { - return getMetadataValueOrDefault(name, null); - } - - public Object getMetadataValueOrDefault(JsonPresentationFields name, Object defaultVal) { - if (metadata != null) { - return metadata.getOrDefault(name.getPresentation(), defaultVal); - } - return null; - } - - public void setMetadataValue(JsonPresentationFields name, Object value) { - if (metadata == null) { - metadata = new HashMap<String, Object>(); - } - metadata.put(name.getPresentation(), value); - - } - // -------------------- - public String getUUID() { - return (String) getMetadataValue(JsonPresentationFields.UUID); - } - - public void setUUID(String uuid) { - setMetadataValue(JsonPresentationFields.UUID, uuid); - } - - public String getVersion() { - return (String) getMetadataValue(JsonPresentationFields.VERSION); - } - - public String getNormalizedName() { - return (String) getMetadataValue(JsonPresentationFields.NORMALIZED_NAME); - } - - public void setNormalizedName(String normaliseComponentName) { - setMetadataValue(JsonPresentationFields.NORMALIZED_NAME, normaliseComponentName); - } - - public String getName() { - return (String) getMetadataValue(JsonPresentationFields.NAME); - } - - public String getSystemName() { - return (String) getMetadataValue(JsonPresentationFields.SYSTEM_NAME); - } - public void setSystemName(String systemName) { - setMetadataValue(JsonPresentationFields.SYSTEM_NAME, systemName); - } - - public void setLifecycleState(LifecycleStateEnum state) { - if(state != null) - setMetadataValue(JsonPresentationFields.LIFECYCLE_STATE, state.name()); - } - - public LifecycleStateEnum getLifecycleState() { - return LifecycleStateEnum.findState( (String) getMetadataValue(JsonPresentationFields.LIFECYCLE_STATE)); - } - - public Long getCreationDate() { - return (Long) getMetadataValue(JsonPresentationFields.CREATION_DATE); - } - - public void setCreationDate(Long currentDate) { - setMetadataValue(JsonPresentationFields.CREATION_DATE, currentDate); - } - - public void setLastUpdateDate(Long currentDate) { - setMetadataValue(JsonPresentationFields.LAST_UPDATE_DATE, currentDate); - } - public Long getLastUpdateDate() { - return (Long) getMetadataValue(JsonPresentationFields.LAST_UPDATE_DATE); - } - - public String getUniqueId() { - return (String) getMetadataValue(JsonPresentationFields.UNIQUE_ID); - } - public void setUniqueId(String uniqueId) { - setMetadataValue(JsonPresentationFields.UNIQUE_ID, uniqueId); - } - - public void setHighestVersion(Boolean isHighest) { - setMetadataValue(JsonPresentationFields.HIGHEST_VERSION, isHighest); - - } - public Boolean isHighestVersion() { - return (Boolean) getMetadataValue(JsonPresentationFields.HIGHEST_VERSION); - - } - public ResourceTypeEnum getResourceType() { - String resourceType = (String) getMetadataValue(JsonPresentationFields.RESOURCE_TYPE); - return resourceType != null ? ResourceTypeEnum.valueOf(resourceType) : null; - } - - public void setResourceType(ResourceTypeEnum resourceType) { - if(resourceType != null) - setMetadataValue(JsonPresentationFields.RESOURCE_TYPE, resourceType.name()); - } - - public ComponentTypeEnum getComponentType() { - return ComponentTypeEnum.valueOf((String) getMetadataValue(JsonPresentationFields.COMPONENT_TYPE)); - } - - public void setComponentType(ComponentTypeEnum componentType) { - if(componentType != null) - setMetadataValue(JsonPresentationFields.COMPONENT_TYPE, componentType.name()); - } - - public String getDerivedFromGenericType(){ - return (String) getMetadataValue(JsonPresentationFields.DERIVED_FROM_GENERIC_TYPE); - } - - public void setDerivedFromGenericType(String derivedFromGenericType){ - setMetadataValue(JsonPresentationFields.DERIVED_FROM_GENERIC_TYPE, derivedFromGenericType); - } - - public String getDerivedFromGenericVersion(){ - return (String) getMetadataValue(JsonPresentationFields.DERIVED_FROM_GENERIC_VERSION); - } - - public void setDerivedFromGenericVersion(String derivedFromGenericVersion){ - setMetadataValue(JsonPresentationFields.DERIVED_FROM_GENERIC_VERSION, derivedFromGenericVersion); - } - - - public String getCreatorUserId() { - return creatorUserId; - } - - public void setCreatorUserId(String creatorUserId) { - this.creatorUserId = creatorUserId; - } - - public String getCreatorFullName() { - return creatorFullName; - } - - public void setCreatorFullName(String creatorFullName) { - this.creatorFullName = creatorFullName; - } - - public String getLastUpdaterUserId() { - return lastUpdaterUserId; - } - - public void setLastUpdaterUserId(String lastUpdaterUserId) { - this.lastUpdaterUserId = lastUpdaterUserId; - } - - public String getLastUpdaterFullName() { - return lastUpdaterFullName; - } - - public void setLastUpdaterFullName(String lastUpdaterFullName) { - this.lastUpdaterFullName = lastUpdaterFullName; - } - - public void generateUUID() { - String prevUUID = getUUID(); - String version = getVersion(); - if ((prevUUID == null && NodeTypeOperation.uuidNormativeNewVersion.matcher(version).matches()) || NodeTypeOperation.uuidNewVersion.matcher(version).matches()) { - UUID uuid = UUID.randomUUID(); - setUUID(uuid.toString()); - MDC.put("serviceInstanceID", uuid.toString()); - } - } + + protected Map<String, Object> metadata; + protected List<CategoryDefinition> categories; + protected Map<String, ArtifactDataDefinition> toscaArtifacts; + private Map<String, ArtifactDataDefinition> artifacts; + private Map<String, ArtifactDataDefinition> deploymentArtifacts; + private Map<String, AdditionalInfoParameterDataDefinition> additionalInformation; + private Map<String, PropertyDataDefinition> properties; + + protected ToscaElementTypeEnum toscaType; + // User + private String creatorUserId; + private String creatorFullName; + private String lastUpdaterUserId; + private String lastUpdaterFullName; + + private Map<String, String> allVersions; + + public ToscaElement(ToscaElementTypeEnum toscaType){ + this.toscaType = toscaType; + } + + public Map<String, Object> getMetadata() { + return metadata; + } + + public void setMetadata(Map<String, Object> metadata) { + this.metadata = metadata; + } + + public List<CategoryDefinition> getCategories() { + return categories; + } + + public void setCategories(List<CategoryDefinition> categories) { + this.categories = categories; + } + public Map<String, ArtifactDataDefinition> getToscaArtifacts() { + return toscaArtifacts; + } + + public void setToscaArtifacts(Map<String, ArtifactDataDefinition> toscaArtifacts) { + this.toscaArtifacts = toscaArtifacts; + } + + public ToscaElementTypeEnum getToscaType() { + return toscaType; + } + + public void setToscaType(ToscaElementTypeEnum toscaType) { + this.toscaType = toscaType; + } + public Map<String, ArtifactDataDefinition> getArtifacts() { + return artifacts; + } + + public void setArtifacts(Map<String, ArtifactDataDefinition> artifacts) { + this.artifacts = artifacts; + } + + public Map<String, ArtifactDataDefinition> getDeploymentArtifacts() { + return deploymentArtifacts; + } + + public void setDeploymentArtifacts(Map<String, ArtifactDataDefinition> deploymentArtifacts) { + this.deploymentArtifacts = deploymentArtifacts; + } + public Map<String, AdditionalInfoParameterDataDefinition> getAdditionalInformation() { + return additionalInformation; + } + public void setAdditionalInformation(Map<String, AdditionalInfoParameterDataDefinition> additionalInformation) { + this.additionalInformation = additionalInformation; + } + public Map<String, PropertyDataDefinition> getProperties() { + return properties; + } + public void setProperties(Map<String, PropertyDataDefinition> properties) { + this.properties = properties; + } + + public Map<String, String> getAllVersions() { + return allVersions; + } + + public void setAllVersions(Map<String, String> allVersions) { + this.allVersions = allVersions; + } + + // metadata properties + // ---------------------------- + public Object getMetadataValue(JsonPresentationFields name) { + return getMetadataValueOrDefault(name, null); + } + + public Object getMetadataValueOrDefault(JsonPresentationFields name, Object defaultVal) { + if (metadata != null) { + return metadata.getOrDefault(name.getPresentation(), defaultVal); + } + return null; + } + + public void setMetadataValue(JsonPresentationFields name, Object value) { + if (metadata == null) { + metadata = new HashMap<>(); + } + metadata.put(name.getPresentation(), value); + + } + // -------------------- + public String getUUID() { + return (String) getMetadataValue(JsonPresentationFields.UUID); + } + + public void setUUID(String uuid) { + setMetadataValue(JsonPresentationFields.UUID, uuid); + } + + public String getVersion() { + return (String) getMetadataValue(JsonPresentationFields.VERSION); + } + + public String getNormalizedName() { + return (String) getMetadataValue(JsonPresentationFields.NORMALIZED_NAME); + } + + public void setNormalizedName(String normaliseComponentName) { + setMetadataValue(JsonPresentationFields.NORMALIZED_NAME, normaliseComponentName); + } + + public String getName() { + return (String) getMetadataValue(JsonPresentationFields.NAME); + } + + public String getSystemName() { + return (String) getMetadataValue(JsonPresentationFields.SYSTEM_NAME); + } + public void setSystemName(String systemName) { + setMetadataValue(JsonPresentationFields.SYSTEM_NAME, systemName); + } + + public void setLifecycleState(LifecycleStateEnum state) { + if(state != null) + setMetadataValue(JsonPresentationFields.LIFECYCLE_STATE, state.name()); + } + + public LifecycleStateEnum getLifecycleState() { + return LifecycleStateEnum.findState( (String) getMetadataValue(JsonPresentationFields.LIFECYCLE_STATE)); + } + + public Long getCreationDate() { + return (Long) getMetadataValue(JsonPresentationFields.CREATION_DATE); + } + + public void setCreationDate(Long currentDate) { + setMetadataValue(JsonPresentationFields.CREATION_DATE, currentDate); + } + + public void setLastUpdateDate(Long currentDate) { + setMetadataValue(JsonPresentationFields.LAST_UPDATE_DATE, currentDate); + } + public Long getLastUpdateDate() { + return (Long) getMetadataValue(JsonPresentationFields.LAST_UPDATE_DATE); + } + + public String getUniqueId() { + return (String) getMetadataValue(JsonPresentationFields.UNIQUE_ID); + } + public void setUniqueId(String uniqueId) { + setMetadataValue(JsonPresentationFields.UNIQUE_ID, uniqueId); + } + + public void setHighestVersion(Boolean isHighest) { + setMetadataValue(JsonPresentationFields.HIGHEST_VERSION, isHighest); + + } + public Boolean isHighestVersion() { + return (Boolean) getMetadataValue(JsonPresentationFields.HIGHEST_VERSION); + + } + public ResourceTypeEnum getResourceType() { + String resourceType = (String) getMetadataValue(JsonPresentationFields.RESOURCE_TYPE); + return resourceType != null ? ResourceTypeEnum.valueOf(resourceType) : null; + } + + public void setResourceType(ResourceTypeEnum resourceType) { + if(resourceType != null) + setMetadataValue(JsonPresentationFields.RESOURCE_TYPE, resourceType.name()); + } + + public ComponentTypeEnum getComponentType() { + return ComponentTypeEnum.valueOf((String) getMetadataValue(JsonPresentationFields.COMPONENT_TYPE)); + } + + public void setComponentType(ComponentTypeEnum componentType) { + if(componentType != null) + setMetadataValue(JsonPresentationFields.COMPONENT_TYPE, componentType.name()); + } + + public String getDerivedFromGenericType(){ + return (String) getMetadataValue(JsonPresentationFields.DERIVED_FROM_GENERIC_TYPE); + } + + public void setDerivedFromGenericType(String derivedFromGenericType){ + setMetadataValue(JsonPresentationFields.DERIVED_FROM_GENERIC_TYPE, derivedFromGenericType); + } + + public String getDerivedFromGenericVersion(){ + return (String) getMetadataValue(JsonPresentationFields.DERIVED_FROM_GENERIC_VERSION); + } + + public void setDerivedFromGenericVersion(String derivedFromGenericVersion){ + setMetadataValue(JsonPresentationFields.DERIVED_FROM_GENERIC_VERSION, derivedFromGenericVersion); + } + + public Boolean isArchived() { return (Boolean) getMetadataValue(JsonPresentationFields.IS_ARCHIVED); } + + public void setArchived(Boolean archived) { setMetadataValue(JsonPresentationFields.IS_ARCHIVED, archived); } + + public Long getArchiveTime() { + Object archiveTime = getMetadataValue(JsonPresentationFields.ARCHIVE_TIME); + if (archiveTime instanceof Integer){ + return new Long((Integer)getMetadataValue(JsonPresentationFields.ARCHIVE_TIME)); + } + return (Long)archiveTime; + } + + public void setArchiveTime(Long archiveTime) { setMetadataValue(JsonPresentationFields.ARCHIVE_TIME, archiveTime); } + + public Boolean isVspArchived() { return (Boolean) getMetadataValue(JsonPresentationFields.IS_VSP_ARCHIVED); } + + public void setVspArchived(Boolean vspArchived) { setMetadataValue(JsonPresentationFields.IS_VSP_ARCHIVED, vspArchived); } + + public String getCreatorUserId() { + return creatorUserId; + } + + public void setCreatorUserId(String creatorUserId) { + this.creatorUserId = creatorUserId; + } + + public String getCreatorFullName() { + return creatorFullName; + } + + public void setCreatorFullName(String creatorFullName) { + this.creatorFullName = creatorFullName; + } + + public String getLastUpdaterUserId() { + return lastUpdaterUserId; + } + + public void setLastUpdaterUserId(String lastUpdaterUserId) { + this.lastUpdaterUserId = lastUpdaterUserId; + } + + public String getLastUpdaterFullName() { + return lastUpdaterFullName; + } + + public void setLastUpdaterFullName(String lastUpdaterFullName) { + this.lastUpdaterFullName = lastUpdaterFullName; + } + + public void generateUUID() { + String prevUUID = getUUID(); + String version = getVersion(); + if ((prevUUID == null && NodeTypeOperation.uuidNormativeNewVersion.matcher(version).matches()) || NodeTypeOperation.uuidNewVersion.matcher(version).matches()) { + UUID uuid = UUID.randomUUID(); + setUUID(uuid.toString()); + MDC.put("serviceInstanceID", uuid.toString()); + } + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/ToscaElementTypeEnum.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/ToscaElementTypeEnum.java index 1dc7532c1c..3ee492b9bb 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/ToscaElementTypeEnum.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/ToscaElementTypeEnum.java @@ -23,27 +23,27 @@ package org.openecomp.sdc.be.model.jsontitan.datamodel; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; public enum ToscaElementTypeEnum { - NodeType("node_type"), - TopologyTemplate("topology_template"); - - String value; - private ToscaElementTypeEnum(String value){ - this.value = value; - } - - public static VertexTypeEnum getVertexTypeByToscaType(ToscaElementTypeEnum toscaType ){ - switch ( toscaType ){ - case NodeType : - return VertexTypeEnum.NODE_TYPE; - case TopologyTemplate : - return VertexTypeEnum.TOPOLOGY_TEMPLATE; - default : - return null; - } - } + NODE_TYPE("node_type"), + TOPOLOGY_TEMPLATE("topology_template"); + + String value; + private ToscaElementTypeEnum(String value){ + this.value = value; + } + + public static VertexTypeEnum getVertexTypeByToscaType(ToscaElementTypeEnum toscaType ){ + switch ( toscaType ){ + case NODE_TYPE : + return VertexTypeEnum.NODE_TYPE; + case TOPOLOGY_TEMPLATE : + return VertexTypeEnum.TOPOLOGY_TEMPLATE; + default : + return null; + } + } + + public String getValue() { + return value; + } - public String getValue() { - return value; - } - } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/enums/JsonConstantKeysEnum.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/enums/JsonConstantKeysEnum.java index 0a10a3a4e3..2a4496e793 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/enums/JsonConstantKeysEnum.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/enums/JsonConstantKeysEnum.java @@ -21,22 +21,22 @@ package org.openecomp.sdc.be.model.jsontitan.enums; public enum JsonConstantKeysEnum { - - COMPOSITION("composition"), - CAPABILITIES("capabilities"), - REQUIREMENTS("requirements"), - PROPERTIES("properties"), - INPUTS("inputs"), - GROUPS("groups"), - INSTANCE_PROPERIES("instanceProperties"); - - private String value; - - private JsonConstantKeysEnum(String value) { - this.value = value; - } - - public String getValue() { - return value; - } + + COMPOSITION("composition"), + CAPABILITIES("capabilities"), + REQUIREMENTS("requirements"), + PROPERTIES("properties"), + INPUTS("inputs"), + GROUPS("groups"), + INSTANCE_PROPERIES("instanceProperties"); + + private String value; + + private JsonConstantKeysEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ArchiveOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ArchiveOperation.java new file mode 100644 index 0000000000..f4033a2ffb --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ArchiveOperation.java @@ -0,0 +1,284 @@ +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.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.ComponentInstanceDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.jsontitan.enums.JsonConstantKeysEnum; +import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.stream.Collectors; + +import static org.openecomp.sdc.be.model.jsontitan.operations.ArchiveOperation.Action.ARCHIVE; +import static org.openecomp.sdc.be.model.jsontitan.operations.ArchiveOperation.Action.RESTORE; + +/** + * Created by yavivi on 25/03/2018. + */ +@Component +public class ArchiveOperation extends BaseOperation { + + private static final Logger log = Logger.getLogger(ArchiveOperation.class.getName()); + + @Autowired + private IGraphLockOperation graphLockOperation; + + public enum Action { + ARCHIVE, RESTORE; + } + + public ArchiveOperation(TitanDao titanDao, IGraphLockOperation graphLockOperation){ + this.titanDao = titanDao; + this.graphLockOperation = graphLockOperation; + } + + public Either<List<String>, ActionStatus> archiveComponent(String componentId) { + final Either<GraphVertex, TitanOperationStatus> vertexResult = this.titanDao.getVertexById(componentId); + if (vertexResult.isLeft()){ + return doAction(ARCHIVE, vertexResult.left().value()); + } else { + return Either.right(onError(ARCHIVE.name(), componentId, vertexResult.right().value())); + } + } + + public Either<List<String>, ActionStatus> restoreComponent(String componentId) { + final Either<GraphVertex, TitanOperationStatus> vertexResult = this.titanDao.getVertexById(componentId); + if (vertexResult.isLeft()){ + return doAction(RESTORE, vertexResult.left().value()); + } else { + return Either.right(onError(RESTORE.name(), componentId, vertexResult.right().value())); + } + } + + public ActionStatus onVspRestored(String csarId){ + return onVspStateChanged(RESTORE, csarId); + } + + public ActionStatus onVspArchived(String csarId){ + return onVspStateChanged(ARCHIVE, csarId); + } + + private ActionStatus onVspStateChanged(Action action, String csarId) { + Map<GraphPropertyEnum, Object> props = new HashMap<>(); + props.put(GraphPropertyEnum.CSAR_UUID, csarId); + Either<List<GraphVertex>, TitanOperationStatus> vfsE = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, props); + return vfsE.either(vList -> setVspArchived(action, vList), s -> onError("VSP_"+action.name(), csarId, s)); + } + + private ActionStatus setVspArchived(Action action, List<GraphVertex> vList) { + if (!vList.isEmpty()) { + //Find & Lock the highest version component + GraphVertex highestVersion = this.getHighestVersionFrom(vList.get(0)); + StorageOperationStatus lockStatus = this.graphLockOperation.lockComponent(highestVersion.getUniqueId(), highestVersion.getType().getNodeType()); + if (lockStatus != StorageOperationStatus.OK){ + return onError(action.name(), highestVersion.getUniqueId(), TitanOperationStatus.ALREADY_LOCKED); + } + + try { + //Set isVspArchived flag + for (GraphVertex v : vList) { + boolean val = action == ARCHIVE ? true : false; + v.setJsonMetadataField(JsonPresentationFields.IS_VSP_ARCHIVED, val); + v.addMetadataProperty(GraphPropertyEnum.IS_VSP_ARCHIVED, val); + titanDao.updateVertex(v); + } + return commitAndCheck("VSP_"+action.name(), vList.toString()); + } finally { + this.graphLockOperation.unlockComponent(highestVersion.getUniqueId(), highestVersion.getType().getNodeType()); + } + + } + return ActionStatus.OK; + } + + public List<String> setArchivedOriginsFlagInComponentInstances(GraphVertex compositionService) { + List<String> ciUidsWithArchivedOrigins = new LinkedList(); + Either<List<GraphVertex>, TitanOperationStatus> instanceOfVerticesE = titanDao.getChildrenVertecies(compositionService, EdgeLabelEnum.INSTANCE_OF, JsonParseFlagEnum.NoParse); + Either<List<GraphVertex>, TitanOperationStatus> proxyOfVerticesE = titanDao.getChildrenVertecies(compositionService, EdgeLabelEnum.PROXY_OF, JsonParseFlagEnum.NoParse); + + List<GraphVertex> all = new LinkedList<>(); + if (instanceOfVerticesE.isLeft()){ + all.addAll(instanceOfVerticesE.left().value()); + } + if (proxyOfVerticesE.isLeft()){ + all.addAll(proxyOfVerticesE.left().value()); + } + + List<GraphVertex> archivedOrigins = all.stream().filter(v -> Boolean.TRUE.equals(v.getMetadataProperty(GraphPropertyEnum.IS_ARCHIVED))).collect(Collectors.toList()); + List<String> archivedOriginsUids = archivedOrigins.stream().map(GraphVertex::getUniqueId).collect(Collectors.toList()); + + Map<String, CompositionDataDefinition> compositionsJson = (Map<String, CompositionDataDefinition>) compositionService.getJson(); + + if (compositionsJson != null) { + CompositionDataDefinition composition = compositionsJson.get(JsonConstantKeysEnum.COMPOSITION.getValue()); + if (composition != null) { + + //Get all component instances from composition + Map<String, ComponentInstanceDataDefinition> componentInstances = composition.getComponentInstances(); + + //Extract component instances uids that has archived origins + ciUidsWithArchivedOrigins = componentInstances. + values(). + stream(). + //filter CIs whose origins are marked as archived (componentUid is in archivedOriginsUids) the second condition handles the PROXY_OF case) + filter(ci -> archivedOriginsUids.contains(ci.getComponentUid()) || archivedOriginsUids.contains(ci.getToscaPresentationValue(JsonPresentationFields.CI_SOURCE_MODEL_UID))). + map(ComponentInstanceDataDefinition::getUniqueId).collect(Collectors.toList()); + + //set archived origins flag + componentInstances. + values(). + stream(). + filter(ci -> archivedOriginsUids.contains(ci.getComponentUid()) || archivedOriginsUids.contains(ci.getToscaPresentationValue(JsonPresentationFields.CI_SOURCE_MODEL_UID))). + forEach( ci -> ci.setOriginArchived(true)); + + } + } + + return ciUidsWithArchivedOrigins; + } + + private Either<List<String>, ActionStatus> doAction(Action action, GraphVertex componentVertex){ + + GraphVertex highestVersion = this.getHighestVersionFrom(componentVertex); + + if (action.equals(ARCHIVE) && isInCheckoutState(highestVersion)) { + return Either.right(ActionStatus.INVALID_SERVICE_STATE); + } + + //Lock the Highest Version + StorageOperationStatus lockStatus = this.graphLockOperation.lockComponent(highestVersion.getUniqueId(), highestVersion.getType().getNodeType()); + if (lockStatus != StorageOperationStatus.OK){ + return Either.right(onError(action.name(), componentVertex.getUniqueId(), TitanOperationStatus.ALREADY_LOCKED)); + } + + //Refetch latest version with full parsing + highestVersion = this.titanDao.getVertexById(highestVersion.getUniqueId(), JsonParseFlagEnum.ParseAll).left().value(); + + try { + //Get Catalog and Archive Roots + GraphVertex catalogRoot = titanDao.getVertexByLabel(VertexTypeEnum.CATALOG_ROOT).left().value(); + GraphVertex archiveRoot = titanDao.getVertexByLabel(VertexTypeEnum.ARCHIVE_ROOT).left().value(); + + if (action == ARCHIVE) { + archiveEdges(catalogRoot, archiveRoot, highestVersion); + } else if (action == RESTORE) { + restoreEdges(catalogRoot, archiveRoot, highestVersion); + } + setPropertiesByAction(highestVersion, action); + titanDao.updateVertex(highestVersion); + + List<String> affectedComponentIds = handleParents(highestVersion, catalogRoot, archiveRoot, action); + ActionStatus sc = commitAndCheck(action.name(), highestVersion.getUniqueId()); + return sc == ActionStatus.OK ? Either.left(affectedComponentIds) : Either.right(sc); + } finally { + this.graphLockOperation.unlockComponent(highestVersion.getUniqueId(), highestVersion.getType().getNodeType()); + } + } + + private ActionStatus commitAndCheck(String action, String componentId) { + TitanOperationStatus status = titanDao.commit(); + if (!status.equals(TitanOperationStatus.OK)){ + return onError(action, componentId, status); + } + return ActionStatus.OK; + } + + private boolean isInCheckoutState(GraphVertex v) { + if (LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name().equals(v.getMetadataProperty(GraphPropertyEnum.STATE))){ + return true; + } + return false; + } + + /** + * Walks on children until highest version is reached + * @param v + * @return + */ + private GraphVertex getHighestVersionFrom(GraphVertex v) { + Either<GraphVertex, TitanOperationStatus> childVertexE = titanDao.getChildVertex(v, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); + GraphVertex highestVersionVertex = v; + + while (childVertexE.isLeft()) { + highestVersionVertex = childVertexE.left().value(); + childVertexE = titanDao.getChildVertex(highestVersionVertex, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); + } + return highestVersionVertex; + } + + private boolean isHighestVersion(GraphVertex v){ + Boolean highest = (Boolean) v.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION); + return highest != null && highest; + } + + private List<String> handleParents(GraphVertex v, GraphVertex catalogRoot, GraphVertex archiveRoot, Action action) { + Either<GraphVertex, TitanOperationStatus> parentVertexE = titanDao.getParentVertex(v, EdgeLabelEnum.VERSION, JsonParseFlagEnum.ParseAll); + List<String> affectedCompIds = new ArrayList(); + affectedCompIds.add(v.getUniqueId()); + + while (parentVertexE.isLeft()){ + GraphVertex cv = parentVertexE.left().value(); + affectedCompIds.add(cv.getUniqueId()); + boolean isHighestVersion = isHighestVersion(cv); + if (isHighestVersion){ + if (action == ARCHIVE) { + archiveEdges(catalogRoot, archiveRoot, cv); + } else { + restoreEdges(catalogRoot, archiveRoot, cv); + } + } + setPropertiesByAction(cv, action); + titanDao.updateVertex(cv); + parentVertexE = titanDao.getParentVertex(cv, EdgeLabelEnum.VERSION, JsonParseFlagEnum.ParseAll); + } + return affectedCompIds; + } + + private void archiveEdges(GraphVertex catalogRoot, GraphVertex archiveRoot, GraphVertex v) { + titanDao.deleteAllEdges(catalogRoot, v, EdgeLabelEnum.CATALOG_ELEMENT); + titanDao.createEdge(archiveRoot, v, EdgeLabelEnum.ARCHIVE_ELEMENT, null); + setPropertiesByAction(v, ARCHIVE); + } + + private void restoreEdges(GraphVertex catalogRoot, GraphVertex archiveRoot, GraphVertex v) { + titanDao.deleteAllEdges(archiveRoot, v, EdgeLabelEnum.ARCHIVE_ELEMENT); + titanDao.createEdge(catalogRoot, v, EdgeLabelEnum.CATALOG_ELEMENT, null); + setPropertiesByAction(v, RESTORE); + } + + private void setPropertiesByAction(GraphVertex v, Action action) { + long now = System.currentTimeMillis(); + + boolean isArchived = action == ARCHIVE ? true : false; + v.addMetadataProperty(GraphPropertyEnum.IS_ARCHIVED, isArchived); + v.addMetadataProperty(GraphPropertyEnum.ARCHIVE_TIME, now); + v.setJsonMetadataField(JsonPresentationFields.IS_ARCHIVED, isArchived); + v.setJsonMetadataField(JsonPresentationFields.ARCHIVE_TIME, now); + } + + private ActionStatus onError(String action, String componentId, TitanOperationStatus s) { + ActionStatus ret = ActionStatus.GENERAL_ERROR; + if (s == TitanOperationStatus.NOT_FOUND){ + ret = ActionStatus.RESOURCE_NOT_FOUND; + } else if (s == TitanOperationStatus.ALREADY_LOCKED) { + ret = ActionStatus.COMPONENT_IN_USE; + } + String retCodeVal = ret.name(); + log.error("error occurred when trying to {} {}. Return code is: {}", action, componentId, retCodeVal); + return ret; + } +} 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 872a16041c..009d4cac3b 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 @@ -20,16 +20,7 @@ package org.openecomp.sdc.be.model.jsontitan.operations; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.UUID; -import java.util.stream.Collectors; - +import fj.data.Either; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.tuple.ImmutableTriple; import org.apache.commons.lang3.tuple.Triple; @@ -58,107 +49,109 @@ import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.openecomp.sdc.common.jsongraph.util.CommonUtility; import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.slf4j.MDC; -import fj.data.Either; +import java.util.*; +import java.util.Map.Entry; +import java.util.stream.Collectors; @org.springframework.stereotype.Component("artifacts-operations") public class ArtifactsOperations extends BaseOperation { - private static Logger log = LoggerFactory.getLogger(ArtifactsOperations.class.getName()); - - 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) { - artifactId = artifactInfo.getEsId(); - } - Either<ArtifactDataDefinition, StorageOperationStatus> status = updateArtifactOnGraph(parentId, artifactInfo, type, artifactId, instanceId, false, false); - if (status.isRight()) { - - log.debug("Failed to update artifact {} of {} {}. status is {}", artifactInfo.getArtifactName(), type.getName(), parentId, status.right().value()); - BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("Update Artifact", artifactInfo.getArtifactName(), String.valueOf(status.right().value())); - return Either.right(status.right().value()); - } else { - - ArtifactDataDefinition artifactData = status.left().value(); - - ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(artifactInfo, artifactData); - log.debug("The returned ArtifactDefintion is {}", artifactDefResult); - return Either.left(artifactDefResult); - } - - } - - public Either<ArtifactDefinition, StorageOperationStatus> updateArtifactOnResource(ArtifactDefinition artifactInfo, String id, String artifactId, NodeTypeEnum type, String instanceId) { - - Either<ArtifactDataDefinition, StorageOperationStatus> status = updateArtifactOnGraph(id, artifactInfo, type, artifactId, instanceId, true, false); - if (status.isRight()) { - - log.debug("Failed to update artifact {} of {} {}. status is {}", artifactInfo.getArtifactName(), type.getName(), id, status.right().value()); - BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("Update Artifact", artifactInfo.getArtifactName(), String.valueOf(status.right().value())); - return Either.right(status.right().value()); - } else { - - ArtifactDataDefinition artifactData = status.left().value(); - - ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(artifactInfo, artifactData); - log.debug("The returned ArtifactDefintion is {}", artifactDefResult); - return Either.left(artifactDefResult); - } - } - - public Either<Boolean, StorageOperationStatus> isCloneNeeded(String parentId, ArtifactDefinition artifactInfo, NodeTypeEnum type) { - ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType(); - - Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> triple = getEdgeLabelEnumFromArtifactGroupType(groupType, type); - EdgeLabelEnum edgeLabelEnum = triple.getLeft(); - return super.isCloneNeeded(parentId, edgeLabelEnum); - } - - public Either<ArtifactDefinition, StorageOperationStatus> getArtifactById(String parentId, String id) { - return getArtifactById(parentId, id, null, null); - } - - public Either<ArtifactDefinition, StorageOperationStatus> getArtifactById(String parentId, String id, ComponentTypeEnum componentType, String containerId) { - Either<ArtifactDefinition, StorageOperationStatus> result = null; - ArtifactDataDefinition foundArtifact = null; - if (componentType != null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) { - foundArtifact = getInstanceArtifactByLabelAndId(parentId, id, containerId, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS); - if (foundArtifact == null) { - foundArtifact = getInstanceArtifactByLabelAndId(parentId, id, containerId, EdgeLabelEnum.INSTANCE_ARTIFACTS); - } - } - if (foundArtifact == null) { - foundArtifact = getArtifactByLabelAndId(parentId, id, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS); - } - if (foundArtifact == null) { - foundArtifact = getArtifactByLabelAndId(parentId, id, EdgeLabelEnum.TOSCA_ARTIFACTS); - } - - if (foundArtifact == null) { - foundArtifact = getArtifactByLabelAndId(parentId, id, EdgeLabelEnum.ARTIFACTS); - } - - if (foundArtifact == null) { - foundArtifact = getArtifactByLabelAndId(parentId, id, EdgeLabelEnum.SERVICE_API_ARTIFACTS); - } + private static final String FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR = "failed to fetch {} for tosca element with id {}, error {}"; + private static final Logger log = Logger.getLogger(ArtifactsOperations.class.getName()); + + 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) { + artifactId = artifactInfo.getEsId(); + } + Either<ArtifactDataDefinition, StorageOperationStatus> status = updateArtifactOnGraph(parentId, artifactInfo, type, artifactId, instanceId, false, false); + if (status.isRight()) { + + log.debug("Failed to update artifact {} of {} {}. status is {}", artifactInfo.getArtifactName(), type.getName(), parentId, status.right().value()); + BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("Update Artifact", artifactInfo.getArtifactName(), String.valueOf(status.right().value())); + return Either.right(status.right().value()); + } else { + + ArtifactDataDefinition artifactData = status.left().value(); + + ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(artifactInfo, artifactData); + log.debug("The returned ArtifactDefintion is {}", artifactDefResult); + return Either.left(artifactDefResult); + } + + } + + public Either<ArtifactDefinition, StorageOperationStatus> updateArtifactOnResource(ArtifactDefinition artifactInfo, String id, String artifactId, NodeTypeEnum type, String instanceId) { + + Either<ArtifactDataDefinition, StorageOperationStatus> status = updateArtifactOnGraph(id, artifactInfo, type, artifactId, instanceId, true, false); + if (status.isRight()) { + + log.debug("Failed to update artifact {} of {} {}. status is {}", artifactInfo.getArtifactName(), type.getName(), id, status.right().value()); + BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("Update Artifact", artifactInfo.getArtifactName(), String.valueOf(status.right().value())); + return Either.right(status.right().value()); + } else { + + ArtifactDataDefinition artifactData = status.left().value(); + + ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(artifactInfo, artifactData); + log.debug("The returned ArtifactDefintion is {}", artifactDefResult); + return Either.left(artifactDefResult); + } + } + + public Either<Boolean, StorageOperationStatus> isCloneNeeded(String parentId, ArtifactDefinition artifactInfo, NodeTypeEnum type) { + ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType(); + + Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> triple = getEdgeLabelEnumFromArtifactGroupType(groupType, type); + EdgeLabelEnum edgeLabelEnum = triple.getLeft(); + return super.isCloneNeeded(parentId, edgeLabelEnum); + } + + public Either<ArtifactDefinition, StorageOperationStatus> getArtifactById(String parentId, String id) { + return getArtifactById(parentId, id, null, null); + } + + public Either<ArtifactDefinition, StorageOperationStatus> getArtifactById(String parentId, String id, ComponentTypeEnum componentType, String containerId) { + Either<ArtifactDefinition, StorageOperationStatus> result = null; + ArtifactDataDefinition foundArtifact = null; + if (componentType != null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) { + foundArtifact = getInstanceArtifactByLabelAndId(parentId, id, containerId, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS); + if (foundArtifact == null) { + foundArtifact = getInstanceArtifactByLabelAndId(parentId, id, containerId, EdgeLabelEnum.INSTANCE_ARTIFACTS); + } + } + if (foundArtifact == null) { + foundArtifact = getArtifactByLabelAndId(parentId, id, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS); + } + if (foundArtifact == null) { + foundArtifact = getArtifactByLabelAndId(parentId, id, EdgeLabelEnum.TOSCA_ARTIFACTS); + } + + if (foundArtifact == null) { + foundArtifact = getArtifactByLabelAndId(parentId, id, EdgeLabelEnum.ARTIFACTS); + } + + if (foundArtifact == null) { + foundArtifact = getArtifactByLabelAndId(parentId, id, EdgeLabelEnum.SERVICE_API_ARTIFACTS); + } if (foundArtifact == null) { foundArtifact = findInterfaceArtifact(parentId, id); } - if (foundArtifact == null) { - result = Either.right(StorageOperationStatus.NOT_FOUND); - return result; - } + if (foundArtifact == null) { + result = Either.right(StorageOperationStatus.NOT_FOUND); + return result; + } - ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(null, foundArtifact); - return Either.left(artifactDefResult); + ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(null, foundArtifact); + return Either.left(artifactDefResult); - } + } private ArtifactDataDefinition findInterfaceArtifact(String parentId, String id) { Either<Map<String, InterfaceDefinition>, TitanOperationStatus> dataFromGraph = getDataFromGraph(parentId, EdgeLabelEnum.INTERFACE_ARTIFACTS); if (dataFromGraph.isRight()){ @@ -201,568 +194,565 @@ public class ArtifactsOperations extends BaseOperation { } - public Either<ArtifactDefinition, StorageOperationStatus> removeArifactFromResource(String id, String artifactId, NodeTypeEnum type, boolean deleteMandatoryArtifact) { - Either<ArtifactDefinition, StorageOperationStatus> status = removeArtifactOnGraph(id, artifactId, type, deleteMandatoryArtifact); - - if (status.isRight()) { - - log.debug("Failed to delete artifact {} of resource {}", artifactId, id); - - BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError("Delete Artifact", artifactId, String.valueOf(status.right().value())); - return Either.right(status.right().value()); - } else { - - return Either.left(status.left().value()); - } - } - - public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, ArtifactGroupTypeEnum groupType, String instanceId) { - - Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> triple = getEdgeLabelEnumFromArtifactGroupType(groupType, parentType); - EdgeLabelEnum edgeLabelEnum = triple.getLeft(); - - Either<Map<String, ArtifactDefinition>, TitanOperationStatus> foundArtifact = null; - Map<String, ArtifactDefinition> resMap = new HashMap<>(); - foundArtifact = getArtifactByLabel(parentId, instanceId, edgeLabelEnum); - if (foundArtifact.isRight()) { - log.debug("Failed to find artifact in component {} with label {} ", parentId, edgeLabelEnum); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(foundArtifact.right().value())); - } - - resMap.putAll(foundArtifact.left().value()); - - return Either.left(resMap); - } - - /** - * @param parentId the id of the instance container - * @param instanceId the id of the instance of which to return its artifacts - * @return instance and instance deployment artifacts mapped by artifact label name - */ - public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getAllInstanceArtifacts(String parentId, String instanceId) { - Map<String, ArtifactDataDefinition> resMap = new HashMap<>(); - Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> instArtifacts = getInstanceArtifactsByLabel(parentId, instanceId, EdgeLabelEnum.INSTANCE_ARTIFACTS); - if (instArtifacts.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(instArtifacts.right().value())); - } - Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> deployInstArtifacts = getInstanceArtifactsByLabel(parentId, instanceId, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS); - if (deployInstArtifacts.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(deployInstArtifacts.right().value())); - } - resMap.putAll(instArtifacts.left().value()); - resMap.putAll(deployInstArtifacts.left().value()); - return Either.left(convertArtifactMapToArtifactDefinitionMap(resMap)); - } - - public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId) { - - Either<Map<String, ArtifactDefinition>, TitanOperationStatus> foundArtifact = null; - Map<String, ArtifactDefinition> resMap = new HashMap<>(); - foundArtifact = getArtifactByLabel(parentId, null, EdgeLabelEnum.ARTIFACTS); - if (foundArtifact.isLeft()) { - resMap.putAll(foundArtifact.left().value()); - - } - foundArtifact = getArtifactByLabel(parentId, null, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS); - if (foundArtifact.isLeft()) { - resMap.putAll(foundArtifact.left().value()); - - } - foundArtifact = getArtifactByLabel(parentId, null, EdgeLabelEnum.TOSCA_ARTIFACTS); - if (foundArtifact.isLeft()) { - resMap.putAll(foundArtifact.left().value()); - - } - - return Either.left(resMap); - - } - - public Either<ArtifactDefinition, StorageOperationStatus> removeArtifactOnGraph(String id, String artifactId, NodeTypeEnum type, boolean deleteMandatoryArtifact) { - - Either<ArtifactDefinition, StorageOperationStatus> artifactData = this.getArtifactById(id, artifactId); - if (artifactData.isRight()) { - log.debug("Failed to find artifact in component {} with id {} ", id, artifactId); - return Either.right(artifactData.right().value()); - } - ArtifactDataDefinition artifactDefinition = artifactData.left().value(); - boolean isMandatory = false; - if ((artifactDefinition.getMandatory() || artifactDefinition.getServiceApi()) && !deleteMandatoryArtifact) { - // return Either.left(artifactData.left().value()); - isMandatory = true; - } - - Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> triple = getEdgeLabelEnumFromArtifactGroupType(artifactDefinition.getArtifactGroupType(), type); - EdgeLabelEnum edgeLabelEnum = triple.getLeft(); - VertexTypeEnum vertexTypeEnum = triple.getRight(); - - if (!isMandatory) { - StorageOperationStatus status = deleteToscaDataElement(id, edgeLabelEnum, vertexTypeEnum, artifactDefinition.getArtifactLabel(), JsonPresentationFields.ARTIFACT_LABEL); - if (status != StorageOperationStatus.OK) - return Either.right(status); - } - - return Either.left(artifactData.left().value()); - - } - - public void updateUUID(ArtifactDataDefinition artifactData, String oldChecksum, String oldVesrion, boolean isUpdate, EdgeLabelEnum edgeLabel) { - if (oldVesrion == null || oldVesrion.isEmpty()) - oldVesrion = "0"; - - String currentChecksum = artifactData.getArtifactChecksum(); - - 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) { - generateUUID(artifactData, oldVesrion); - } - } else if ((currentChecksum != null && !currentChecksum.isEmpty()) && !oldChecksum.equals(currentChecksum)) { - generateUUID(artifactData, oldVesrion); - } - break; - } - } else { - if (oldChecksum == null || oldChecksum.isEmpty()) { - if (currentChecksum != null) { - generateUUID(artifactData, oldVesrion); - } - } else if ((currentChecksum != null && !currentChecksum.isEmpty()) && !oldChecksum.equals(currentChecksum)) { - generateUUID(artifactData, oldVesrion); - } - } - } - - // @TODO add implementation - - public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType) { - return null; - } - - public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifactHeat, String componentId, NodeTypeEnum parentType, boolean failIfExist, String instanceId) { - artifactHeatEnv.setGeneratedFromId(artifactHeat.getUniqueId()); - return addArifactToComponent(artifactHeatEnv, componentId, parentType, failIfExist, instanceId); - } - - public Either<ArtifactDefinition, StorageOperationStatus> getHeatArtifactByHeatEnvId(String parentId, ArtifactDefinition heatEnv, NodeTypeEnum parentType, String containerId, ComponentTypeEnum componentType) { - String id = heatEnv.getGeneratedFromId(); - ComponentTypeEnum compType; - switch (parentType) { - case ResourceInstance: - compType = ComponentTypeEnum.RESOURCE_INSTANCE; - break; - default: - compType = componentType; - } - return getArtifactById(parentId, id, compType, containerId); - } - - public Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact(String id, ArtifactDefinition artifactEnvInfo, String artifactId, String newArtifactId, NodeTypeEnum type, String instanceId) { - - Either<Map<String, ArtifactDefinition>, TitanOperationStatus> artifactsEither = getArtifactByLabel(id, instanceId, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS); - if (artifactsEither.isRight()) { - log.debug("Failed to find artifacts in component {} with id {} ", id, artifactsEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(artifactsEither.right().value())); - } - - Map<String, ArtifactDefinition> artifacts = artifactsEither.left().value(); - List<ArtifactDefinition> envList = artifacts.values().stream().filter(a -> a.getGeneratedFromId() != null && a.getGeneratedFromId().equals(artifactId)).collect(Collectors.toList()); - if (envList != null && !envList.isEmpty()) { - envList.forEach(a -> { - a.setGeneratedFromId(newArtifactId); - updateArtifactOnResource(a, id, a.getUniqueId(), type, instanceId); + public Either<ArtifactDefinition, StorageOperationStatus> removeArifactFromResource(String id, String artifactId, NodeTypeEnum type, boolean deleteMandatoryArtifact) { + Either<ArtifactDefinition, StorageOperationStatus> status = removeArtifactOnGraph(id, artifactId, type, deleteMandatoryArtifact); + + if (status.isRight()) { - }); + log.debug("Failed to delete artifact {} of resource {}", artifactId, id); + + BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError("Delete Artifact", artifactId, String.valueOf(status.right().value())); + return Either.right(status.right().value()); + } else { - } - return Either.left(artifactEnvInfo); - } - - public Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvPlaceholder(ArtifactDefinition artifactInfo, String parentId, NodeTypeEnum type) { + return Either.left(status.left().value()); + } + } + + public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, ArtifactGroupTypeEnum groupType, String instanceId) { + + Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> triple = getEdgeLabelEnumFromArtifactGroupType(groupType, parentType); + EdgeLabelEnum edgeLabelEnum = triple.getLeft(); + + Either<Map<String, ArtifactDefinition>, TitanOperationStatus> foundArtifact = null; + Map<String, ArtifactDefinition> resMap = new HashMap<>(); + foundArtifact = getArtifactByLabel(parentId, instanceId, edgeLabelEnum); + if (foundArtifact.isRight()) { + log.debug("Failed to find artifact in component {} with label {} ", parentId, edgeLabelEnum); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(foundArtifact.right().value())); + } + + resMap.putAll(foundArtifact.left().value()); + + return Either.left(resMap); + } + + /** + * @param parentId the id of the instance container + * @param instanceId the id of the instance of which to return its artifacts + * @return instance and instance deployment artifacts mapped by artifact label name + */ + public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getAllInstanceArtifacts(String parentId, String instanceId) { + Map<String, ArtifactDataDefinition> resMap = new HashMap<>(); + Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> instArtifacts = getInstanceArtifactsByLabel(parentId, instanceId, EdgeLabelEnum.INSTANCE_ARTIFACTS); + if (instArtifacts.isRight()) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(instArtifacts.right().value())); + } + Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> deployInstArtifacts = getInstanceArtifactsByLabel(parentId, instanceId, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS); + if (deployInstArtifacts.isRight()) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(deployInstArtifacts.right().value())); + } + resMap.putAll(instArtifacts.left().value()); + resMap.putAll(deployInstArtifacts.left().value()); + return Either.left(convertArtifactMapToArtifactDefinitionMap(resMap)); + } + + public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId) { + + Either<Map<String, ArtifactDefinition>, TitanOperationStatus> foundArtifact = null; + Map<String, ArtifactDefinition> resMap = new HashMap<>(); + foundArtifact = getArtifactByLabel(parentId, null, EdgeLabelEnum.ARTIFACTS); + if (foundArtifact.isLeft()) { + resMap.putAll(foundArtifact.left().value()); + + } + foundArtifact = getArtifactByLabel(parentId, null, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS); + if (foundArtifact.isLeft()) { + resMap.putAll(foundArtifact.left().value()); + + } + foundArtifact = getArtifactByLabel(parentId, null, EdgeLabelEnum.TOSCA_ARTIFACTS); + if (foundArtifact.isLeft()) { + resMap.putAll(foundArtifact.left().value()); + + } + + return Either.left(resMap); + + } + + public Either<ArtifactDefinition, StorageOperationStatus> removeArtifactOnGraph(String id, String artifactId, NodeTypeEnum type, boolean deleteMandatoryArtifact) { + + Either<ArtifactDefinition, StorageOperationStatus> artifactData = this.getArtifactById(id, artifactId); + if (artifactData.isRight()) { + log.debug("Failed to find artifact in component {} with id {} ", id, artifactId); + return Either.right(artifactData.right().value()); + } + ArtifactDataDefinition artifactDefinition = artifactData.left().value(); + boolean isMandatory = false; + if ((artifactDefinition.getMandatory() || artifactDefinition.getServiceApi()) && !deleteMandatoryArtifact) { + // return Either.left(artifactData.left().value()); + isMandatory = true; + } + + Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> triple = getEdgeLabelEnumFromArtifactGroupType(artifactDefinition.getArtifactGroupType(), type); + EdgeLabelEnum edgeLabelEnum = triple.getLeft(); + VertexTypeEnum vertexTypeEnum = triple.getRight(); + + if (!isMandatory) { + StorageOperationStatus status = deleteToscaDataElement(id, edgeLabelEnum, vertexTypeEnum, artifactDefinition.getArtifactLabel(), JsonPresentationFields.ARTIFACT_LABEL); + if (status != StorageOperationStatus.OK) + return Either.right(status); + } + + return Either.left(artifactData.left().value()); + + } + + public void updateUUID(ArtifactDataDefinition artifactData, String oldChecksum, String oldVesrion, boolean isUpdate, EdgeLabelEnum edgeLabel) { + if (oldVesrion == null || oldVesrion.isEmpty()) + oldVesrion = "0"; + + String currentChecksum = artifactData.getArtifactChecksum(); + + 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) { + generateUUID(artifactData, oldVesrion); + } + } else if ((currentChecksum != null && !currentChecksum.isEmpty()) && !oldChecksum.equals(currentChecksum)) { + generateUUID(artifactData, oldVesrion); + } + break; + } + } else { + if (oldChecksum == null || oldChecksum.isEmpty()) { + if (currentChecksum != null) { + generateUUID(artifactData, oldVesrion); + } + } else if ((currentChecksum != null && !currentChecksum.isEmpty()) && !oldChecksum.equals(currentChecksum)) { + generateUUID(artifactData, oldVesrion); + } + } + } + + // @TODO add implementation + + public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType) { + return null; + } + + public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifactHeat, String componentId, NodeTypeEnum parentType, boolean failIfExist, String instanceId) { + artifactHeatEnv.setGeneratedFromId(artifactHeat.getUniqueId()); + return addArifactToComponent(artifactHeatEnv, componentId, parentType, failIfExist, instanceId); + } + + public Either<ArtifactDefinition, StorageOperationStatus> getHeatArtifactByHeatEnvId(String parentId, ArtifactDefinition heatEnv, NodeTypeEnum parentType, String containerId, ComponentTypeEnum componentType) { + String id = heatEnv.getGeneratedFromId(); + ComponentTypeEnum compType; + switch (parentType) { + case ResourceInstance: + compType = ComponentTypeEnum.RESOURCE_INSTANCE; + break; + default: + compType = componentType; + } + return getArtifactById(parentId, id, compType, containerId); + } + + public Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact(String id, ArtifactDefinition artifactEnvInfo, String artifactId, String newArtifactId, NodeTypeEnum type, String instanceId) { + + Either<Map<String, ArtifactDefinition>, TitanOperationStatus> artifactsEither = getArtifactByLabel(id, instanceId, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS); + if (artifactsEither.isRight()) { + log.debug("Failed to find artifacts in component {} with id {} ", id, artifactsEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(artifactsEither.right().value())); + } + + Map<String, ArtifactDefinition> artifacts = artifactsEither.left().value(); + List<ArtifactDefinition> envList = artifacts.values().stream().filter(a -> a.getGeneratedFromId() != null && a.getGeneratedFromId().equals(artifactId)).collect(Collectors.toList()); + if (envList != null && !envList.isEmpty()) { + envList.forEach(a -> { + a.setGeneratedFromId(newArtifactId); + updateArtifactOnResource(a, id, a.getUniqueId(), type, instanceId); + + }); + + } + return Either.left(artifactEnvInfo); + } + + public Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvPlaceholder(ArtifactDefinition artifactInfo, String parentId, NodeTypeEnum type) { return updateArtifactOnResource(artifactInfo, parentId, artifactInfo.getUniqueId(), type, null); - } - - // public Either<List<HeatParameterDefinition>, StorageOperationStatus> getHeatParamsForEnv(ArtifactDefinition heatEnvArtifact, String parentId) { - // return null; - // } - - ///////////////////////////////////////////// private methods //////////////////////////////////////////////////// - - protected ArtifactDefinition convertArtifactDataToArtifactDefinition(ArtifactDefinition artifactInfo, ArtifactDataDefinition artifactDefResult) { - log.debug("The object returned after create property is {}", artifactDefResult); - - ArtifactDefinition propertyDefResult = new ArtifactDefinition(artifactDefResult); - if (artifactInfo != null) - propertyDefResult.setPayload(artifactInfo.getPayloadData()); - - List<HeatParameterDefinition> parameters = new ArrayList<HeatParameterDefinition>(); - /* - * StorageOperationStatus heatParametersOfNode = heatParametersOperation.getHeatParametersOfNode(NodeTypeEnum.ArtifactRef, artifactDefResult.getUniqueId().toString(), parameters); if ((heatParametersOfNode.equals(StorageOperationStatus.OK)) - * && !parameters.isEmpty()) { propertyDefResult.setHeatParameters(parameters); } - */ - return propertyDefResult; - } - - private ArtifactDataDefinition getInstanceArtifactByLabelAndId(String parentId, String id, String containerId, EdgeLabelEnum edgeLabelEnum) { - ArtifactDataDefinition foundArtifact = null; - Either<Map<String, MapArtifactDataDefinition>, TitanOperationStatus> artifactsEither = getDataFromGraph(containerId, edgeLabelEnum); - if (artifactsEither.isRight()) { - log.debug("failed to fetch {} for tosca element with id {}, error {}", edgeLabelEnum, containerId, artifactsEither.right().value()); - return null; - } - - Map<String, MapArtifactDataDefinition> artifacts = artifactsEither.left().value(); - - MapArtifactDataDefinition artifactsPerInstance = artifacts.get(parentId); - if (artifactsPerInstance == null) { - log.debug("failed to fetch artifacts for instance {} in tosca element with id {}, error {}", parentId, containerId, artifactsEither.right().value()); - return null; - } - Optional<ArtifactDataDefinition> op = artifactsPerInstance.getMapToscaDataDefinition().values().stream().filter(p -> p.getUniqueId().equals(id)).findAny(); - if (op.isPresent()) { - foundArtifact = op.get(); - } - return foundArtifact; - } - - private ArtifactDataDefinition getArtifactByLabelAndId(String parentId, String id, EdgeLabelEnum edgeLabelEnum) { - ArtifactDataDefinition foundArtifact = null; - Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> artifactsEither = getDataFromGraph(parentId, edgeLabelEnum); - if (artifactsEither.isRight()) { - log.debug("failed to fetch {} for tosca element with id {}, error {}", edgeLabelEnum, parentId, artifactsEither.right().value()); - return null; - } - - Map<String, ArtifactDataDefinition> artifacts = artifactsEither.left().value(); - Optional<ArtifactDataDefinition> op = artifacts.values().stream().filter(p -> p.getUniqueId().equals(id)).findAny(); - if (op.isPresent()) { - foundArtifact = op.get(); - } - return foundArtifact; - } - - private Either<Map<String, ArtifactDefinition>, TitanOperationStatus> getArtifactByLabel(String parentId, String instanceId, EdgeLabelEnum edgeLabelEnum) { - Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> artifactsEither = getArtifactsDataByLabel(parentId, instanceId, edgeLabelEnum); - if (artifactsEither.isRight()) { - log.debug("failed to fetch {} for tosca element with id {}, error {}", edgeLabelEnum, parentId, artifactsEither.right().value()); - return Either.right(artifactsEither.right().value()); - } - Map<String, ArtifactDataDefinition> artifactDataMap = artifactsEither.left().value(); - return Either.left(convertArtifactMapToArtifactDefinitionMap(artifactDataMap)); - } - - private Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> getArtifactsDataByLabel(String parentId, String instanceId, EdgeLabelEnum edgeLabelEnum) { - return edgeLabelEnum.isInstanceArtifactsLabel() ? getInstanceArtifactsByLabel(parentId, instanceId, edgeLabelEnum) : getDataFromGraph(parentId, edgeLabelEnum); - } - - private Map<String, ArtifactDefinition> convertArtifactMapToArtifactDefinitionMap(Map<String, ArtifactDataDefinition> artifactDataMap) { - Map<String, ArtifactDefinition> artMap = new HashMap<>(); - if (artifactDataMap != null && !artifactDataMap.isEmpty()) { - artMap = artifactDataMap.entrySet().stream().collect(Collectors.toMap(Entry::getKey, e -> convertArtifactDataToArtifactDefinition(null, e.getValue()))); - } - return artMap; - } - - private Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> getInstanceArtifactsByLabel(String parentId, String instanceId, EdgeLabelEnum edgeLabelEnum) { - Either<Map<String, MapArtifactDataDefinition>, TitanOperationStatus> resultEither = getDataFromGraph(parentId, edgeLabelEnum); - if (resultEither.isRight()) { - log.debug("failed to fetch {} for tosca element with id {}, error {}", edgeLabelEnum, parentId, resultEither.right().value()); - return Either.right(resultEither.right().value()); - } - Map<String, MapArtifactDataDefinition> mapArtifacts = resultEither.left().value(); - MapArtifactDataDefinition artifactPerInstance = mapArtifacts.get(instanceId); - return artifactPerInstance != null ? Either.left(artifactPerInstance.getMapToscaDataDefinition()) : Either.left(new HashMap<>()); - } - - private Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> getEdgeLabelEnumFromArtifactGroupType(ArtifactGroupTypeEnum groupType, NodeTypeEnum nodeType) { - EdgeLabelEnum edgeLabelEnum; - VertexTypeEnum vertexTypeEnum; - Boolean isDeepElement = false; - /* - * 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; - } - // } - return new ImmutableTriple<EdgeLabelEnum, Boolean, VertexTypeEnum>(edgeLabelEnum, isDeepElement, vertexTypeEnum); - - } - - public Either<ArtifactDataDefinition, StorageOperationStatus> updateArtifactOnGraph(String componentId, ArtifactDefinition artifactInfo, NodeTypeEnum type, String artifactId, String instanceId, boolean isUpdate, boolean isDeletePlaceholder) { - Either<ArtifactDataDefinition, StorageOperationStatus> res = null; - ArtifactDataDefinition artifactToUpdate = new ArtifactDataDefinition(artifactInfo); - ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType(); - - Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> triple = getEdgeLabelEnumFromArtifactGroupType(groupType, type); - EdgeLabelEnum edgeLabelEnum = triple.getLeft(); - VertexTypeEnum vertexTypeEnum = triple.getRight(); - - Either<Boolean, StorageOperationStatus> isNeedToCloneEither = isCloneNeeded(componentId, edgeLabelEnum); - if (isNeedToCloneEither.isRight()) { - log.debug("Failed check is clone needed {}", componentId); - return Either.right(isNeedToCloneEither.right().value()); - - } - boolean isNeedToClone = isNeedToCloneEither.left().value(); - - if (artifactId == null || isNeedToClone) { - String uniqueId; - if (edgeLabelEnum != EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS && edgeLabelEnum != EdgeLabelEnum.INSTANCE_ARTIFACTS) { - uniqueId = UniqueIdBuilder.buildPropertyUniqueId(componentId, artifactToUpdate.getArtifactLabel()); - } else { - uniqueId = UniqueIdBuilder.buildInstanceArtifactUniqueId(componentId, instanceId, artifactToUpdate.getArtifactLabel()); - } - artifactToUpdate.setUniqueId(uniqueId); - if (!isDeletePlaceholder) - artifactToUpdate.setEsId(uniqueId); - } else - artifactToUpdate.setUniqueId(artifactId); - - Map<String, ArtifactDataDefinition> artifacts = new HashMap<>(); - Map<String, MapArtifactDataDefinition> artifactInst = null; - if (edgeLabelEnum != EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS && edgeLabelEnum != EdgeLabelEnum.INSTANCE_ARTIFACTS) { - - Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> artifactsEither = this.getDataFromGraph(componentId, edgeLabelEnum); - - if (artifactsEither.isLeft() && artifactsEither.left().value() != null && !artifactsEither.left().value().isEmpty()) { - artifacts = artifactsEither.left().value(); - if (isNeedToClone && artifacts != null) { - artifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE)); - } - } - } else { - - Either<Map<String, MapArtifactDataDefinition>, TitanOperationStatus> artifactsEither = this.getDataFromGraph(componentId, edgeLabelEnum); - if (artifactsEither.isLeft()) { - artifactInst = artifactsEither.left().value(); - if (isNeedToClone && artifactInst != null) { - artifactInst.values().forEach(ma -> ma.getMapToscaDataDefinition().values().forEach(a -> a.setDuplicated(Boolean.TRUE))); - } - MapArtifactDataDefinition artifatcsOnInstance = artifactInst.get(instanceId); - if (artifatcsOnInstance != null) { - artifacts = artifatcsOnInstance.getMapToscaDataDefinition(); - } - } - } - String oldChecksum = null; - String oldVersion = null; - if (artifacts != null && artifacts.containsKey(artifactInfo.getArtifactLabel())) { - ArtifactDataDefinition oldArtifactData = artifacts.get(artifactInfo.getArtifactLabel()); - oldChecksum = oldArtifactData.getArtifactChecksum(); - 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 uniqueId = ""; - if(type != NodeTypeEnum.ResourceInstance) - uniqueId = UniqueIdBuilder.buildPropertyUniqueId(componentId, artifactToUpdate.getArtifactLabel()); - else - uniqueId = UniqueIdBuilder.buildInstanceArtifactUniqueId(componentId, instanceId, artifactToUpdate.getArtifactLabel()); - - artifactToUpdate.setUniqueId(uniqueId); - if (!isDeletePlaceholder) - artifactToUpdate.setEsId(uniqueId); - artifactToUpdate.setDuplicated(Boolean.FALSE); - } - } - } - updateUUID(artifactToUpdate, oldChecksum, oldVersion, isUpdate, edgeLabelEnum); - - if (artifactInfo.getPayloadData() == null) { - if (!artifactToUpdate.getMandatory() || artifactToUpdate.getEsId() != null) { - artifactToUpdate.setEsId(artifactToUpdate.getUniqueId()); - } - } else { - if (artifactToUpdate.getEsId() == null) { - artifactToUpdate.setEsId(artifactToUpdate.getUniqueId()); - } - } - - StorageOperationStatus status = StorageOperationStatus.OK; - if (edgeLabelEnum != EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS && edgeLabelEnum != EdgeLabelEnum.INSTANCE_ARTIFACTS) { - List<ArtifactDataDefinition> toscaDataList = new ArrayList<>(); - toscaDataList.add(artifactToUpdate); - - if (isNeedToClone && artifacts != null) { - artifacts.values().stream().filter(a -> !a.getArtifactLabel().equals(artifactToUpdate.getArtifactLabel())).forEach(a -> toscaDataList.add(a)); - } - status = updateToscaDataOfToscaElement(componentId, edgeLabelEnum, vertexTypeEnum, toscaDataList, JsonPresentationFields.ARTIFACT_LABEL); - } else { - List<ArtifactDataDefinition> toscaDataList = new ArrayList<>(); - toscaDataList.add(artifactToUpdate); - List<String> pathKeys = new ArrayList<>(); - pathKeys.add(instanceId); - if (isNeedToClone) { - MapArtifactDataDefinition artifatcsOnInstance = artifactInst.get(instanceId); - if (artifatcsOnInstance != null) { - artifacts = artifatcsOnInstance.getMapToscaDataDefinition(); - artifacts.put(artifactToUpdate.getArtifactLabel(), artifactToUpdate); - } - - 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) { - log.debug("Failed to update atifacts group for instance {} in component {} edge type {} error {}", instanceId, componentId, edgeLabelEnum, status); - res = Either.right(status); - break; - } - } - } else { - status = updateToscaDataDeepElementsOfToscaElement(componentId, edgeLabelEnum, vertexTypeEnum, toscaDataList, pathKeys, JsonPresentationFields.ARTIFACT_LABEL); - } - } - if (status == StorageOperationStatus.OK) - res = Either.left(artifactToUpdate); - else - res = Either.right(status); - return res; - } - - public void generateUUID(ArtifactDataDefinition artifactData, String oldVesrion) { - - UUID uuid = UUID.randomUUID(); - artifactData.setArtifactUUID(uuid.toString()); - MDC.put("serviceInstanceID", uuid.toString()); - updateVersionAndDate(artifactData, oldVesrion); - } - - private void updateVersionAndDate(ArtifactDataDefinition artifactData, String oldVesrion) { - if (artifactData.getArtifactChecksum() != null) { - long time = System.currentTimeMillis(); - artifactData.setPayloadUpdateDate(time); - } - int newVersion = new Integer(oldVesrion).intValue(); - newVersion++; - artifactData.setArtifactVersion(String.valueOf(newVersion)); - } - - public Either<ArtifactDataDefinition, StorageOperationStatus> removeArtifactOnGraph(ArtifactDefinition artifactFromGraph, String componentId, String instanceId, NodeTypeEnum type, boolean deleteMandatoryArtifact) { - - Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> triple = getEdgeLabelEnumFromArtifactGroupType(artifactFromGraph.getArtifactGroupType(), type); - EdgeLabelEnum edgeLabelEnum = triple.getLeft(); - VertexTypeEnum vertexTypeEnum = triple.getRight(); - - if (deleteMandatoryArtifact || !(artifactFromGraph.getMandatory() || artifactFromGraph.getServiceApi())) { - StorageOperationStatus status; - if (triple.getMiddle()) { - List<String> pathKeys = new ArrayList<>(); - pathKeys.add(instanceId); - status = deleteToscaDataDeepElement(componentId, edgeLabelEnum, vertexTypeEnum, artifactFromGraph.getArtifactLabel(), pathKeys, JsonPresentationFields.ARTIFACT_LABEL); - } else { - status = deleteToscaDataElement(componentId, edgeLabelEnum, vertexTypeEnum, artifactFromGraph.getArtifactLabel(), JsonPresentationFields.ARTIFACT_LABEL); - } - if (status != StorageOperationStatus.OK) - return Either.right(status); - } - return Either.left(artifactFromGraph); - - } - - public Either<ArtifactDataDefinition, StorageOperationStatus> deleteArtifactWithClonnigOnGraph(String componentId, ArtifactDefinition artifactToDelete, NodeTypeEnum type, String instanceId, boolean deleteMandatoryArtifact) { - - Either<ArtifactDataDefinition, StorageOperationStatus> result = null; - Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> triple = getEdgeLabelEnumFromArtifactGroupType(artifactToDelete.getArtifactGroupType(), type); - EdgeLabelEnum edgeLabel = triple.getLeft(); - VertexTypeEnum vertexLabel = triple.getRight(); - - Boolean deleteElement = deleteMandatoryArtifact || !(artifactToDelete.getMandatory() || artifactToDelete.getServiceApi()); - Map<String, ToscaDataDefinition> artifacts = null; - GraphVertex parentVertex = null; - Either<Map<String, ToscaDataDefinition>, TitanOperationStatus> getArtifactsRes = null; - - Either<GraphVertex, TitanOperationStatus> getToscaElementRes = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getToscaElementRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get tosca element {} upon getting tosca data from graph. Status is {}. ", componentId, getToscaElementRes.right().value()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getToscaElementRes.right().value())); - } - if (result == null) { - parentVertex = getToscaElementRes.left().value(); - getArtifactsRes = this.getDataFromGraph(parentVertex, edgeLabel); - if (getArtifactsRes.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getArtifactsRes.right().value())); - } - } - if (result == null) { - artifacts = getArtifactsRes.left().value(); - if (triple.getMiddle()) { - artifacts.values().forEach(ma -> ((MapArtifactDataDefinition) ma).getMapToscaDataDefinition().values().forEach(a -> a.setDuplicated(Boolean.TRUE))); - MapArtifactDataDefinition artifatcsOnInstance = (MapArtifactDataDefinition) artifacts.get(instanceId); - if (artifatcsOnInstance != null && deleteElement) { - artifatcsOnInstance.getMapToscaDataDefinition().remove(artifactToDelete.getArtifactLabel()); - } - } else { - if (deleteElement) { - artifacts.remove(artifactToDelete.getArtifactLabel()); - } - artifacts.values().stream().forEach(a -> ((ArtifactDataDefinition) a).setDuplicated(Boolean.TRUE)); - } - artifactToDelete.setDuplicated(Boolean.TRUE); - } - if (artifacts != null) { - TitanOperationStatus status = titanDao.deleteEdgeByDirection(parentVertex, Direction.OUT, edgeLabel); - if (status != TitanOperationStatus.OK) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } else if (MapUtils.isNotEmpty(artifacts)) { - Either<GraphVertex, StorageOperationStatus> assosiateRes = assosiateElementToData(parentVertex, vertexLabel, edgeLabel, artifacts); - if (assosiateRes.isRight()) { - result = Either.right(result.right().value()); - } - } - } - if (result == null) { - result = Either.left(artifactToDelete); - } - return result; - } + } + + + ///////////////////////////////////////////// private methods //////////////////////////////////////////////////// + + protected ArtifactDefinition convertArtifactDataToArtifactDefinition(ArtifactDefinition artifactInfo, ArtifactDataDefinition artifactDefResult) { + log.debug("The object returned after create property is {}", artifactDefResult); + + ArtifactDefinition propertyDefResult = new ArtifactDefinition(artifactDefResult); + if (artifactInfo != null) + propertyDefResult.setPayload(artifactInfo.getPayloadData()); + + List<HeatParameterDefinition> parameters = new ArrayList<>(); + /* + * StorageOperationStatus heatParametersOfNode = heatParametersOperation.getHeatParametersOfNode(NodeTypeEnum.ArtifactRef, artifactDefResult.getUniqueId().toString(), parameters); if ((heatParametersOfNode.equals(StorageOperationStatus.OK)) + * && !parameters.isEmpty()) { propertyDefResult.setHeatParameters(parameters); } + */ + return propertyDefResult; + } + + private ArtifactDataDefinition getInstanceArtifactByLabelAndId(String parentId, String id, String containerId, EdgeLabelEnum edgeLabelEnum) { + ArtifactDataDefinition foundArtifact = null; + Either<Map<String, MapArtifactDataDefinition>, TitanOperationStatus> artifactsEither = getDataFromGraph(containerId, edgeLabelEnum); + if (artifactsEither.isRight()) { + log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, edgeLabelEnum, containerId, artifactsEither.right().value()); + return null; + } + + Map<String, MapArtifactDataDefinition> artifacts = artifactsEither.left().value(); + + MapArtifactDataDefinition artifactsPerInstance = artifacts.get(parentId); + if (artifactsPerInstance == null) { + log.debug("failed to fetch artifacts for instance {} in tosca element with id {}, error {}", parentId, containerId, artifactsEither.right().value()); + return null; + } + Optional<ArtifactDataDefinition> op = artifactsPerInstance.getMapToscaDataDefinition().values().stream().filter(p -> p.getUniqueId().equals(id)).findAny(); + if (op.isPresent()) { + foundArtifact = op.get(); + } + return foundArtifact; + } + + private ArtifactDataDefinition getArtifactByLabelAndId(String parentId, String id, EdgeLabelEnum edgeLabelEnum) { + ArtifactDataDefinition foundArtifact = null; + Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> artifactsEither = getDataFromGraph(parentId, edgeLabelEnum); + if (artifactsEither.isRight()) { + log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, edgeLabelEnum, parentId, artifactsEither.right().value()); + return null; + } + + Map<String, ArtifactDataDefinition> artifacts = artifactsEither.left().value(); + Optional<ArtifactDataDefinition> op = artifacts.values().stream().filter(p -> p.getUniqueId().equals(id)).findAny(); + if (op.isPresent()) { + foundArtifact = op.get(); + } + return foundArtifact; + } + + private Either<Map<String, ArtifactDefinition>, TitanOperationStatus> getArtifactByLabel(String parentId, String instanceId, EdgeLabelEnum edgeLabelEnum) { + Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> artifactsEither = getArtifactsDataByLabel(parentId, instanceId, edgeLabelEnum); + if (artifactsEither.isRight()) { + log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, edgeLabelEnum, parentId, artifactsEither.right().value()); + return Either.right(artifactsEither.right().value()); + } + Map<String, ArtifactDataDefinition> artifactDataMap = artifactsEither.left().value(); + return Either.left(convertArtifactMapToArtifactDefinitionMap(artifactDataMap)); + } + + private Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> getArtifactsDataByLabel(String parentId, String instanceId, EdgeLabelEnum edgeLabelEnum) { + return edgeLabelEnum.isInstanceArtifactsLabel() ? getInstanceArtifactsByLabel(parentId, instanceId, edgeLabelEnum) : getDataFromGraph(parentId, edgeLabelEnum); + } + + private Map<String, ArtifactDefinition> convertArtifactMapToArtifactDefinitionMap(Map<String, ArtifactDataDefinition> artifactDataMap) { + Map<String, ArtifactDefinition> artMap = new HashMap<>(); + if (artifactDataMap != null && !artifactDataMap.isEmpty()) { + artMap = artifactDataMap.entrySet().stream().collect(Collectors.toMap(Entry::getKey, e -> convertArtifactDataToArtifactDefinition(null, e.getValue()))); + } + return artMap; + } + + private Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> getInstanceArtifactsByLabel(String parentId, String instanceId, EdgeLabelEnum edgeLabelEnum) { + Either<Map<String, MapArtifactDataDefinition>, TitanOperationStatus> resultEither = getDataFromGraph(parentId, edgeLabelEnum); + if (resultEither.isRight()) { + log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, edgeLabelEnum, parentId, resultEither.right().value()); + return Either.right(resultEither.right().value()); + } + Map<String, MapArtifactDataDefinition> mapArtifacts = resultEither.left().value(); + MapArtifactDataDefinition artifactPerInstance = mapArtifacts.get(instanceId); + return artifactPerInstance != null ? Either.left(artifactPerInstance.getMapToscaDataDefinition()) : Either.left(new HashMap<>()); + } + + private Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> getEdgeLabelEnumFromArtifactGroupType(ArtifactGroupTypeEnum groupType, NodeTypeEnum nodeType) { + EdgeLabelEnum edgeLabelEnum; + VertexTypeEnum vertexTypeEnum; + Boolean isDeepElement = false; + /* + * 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; + } + // } + return new ImmutableTriple<>(edgeLabelEnum, isDeepElement, vertexTypeEnum); + + } + + public Either<ArtifactDataDefinition, StorageOperationStatus> updateArtifactOnGraph(String componentId, ArtifactDefinition artifactInfo, NodeTypeEnum type, String artifactId, String instanceId, boolean isUpdate, boolean isDeletePlaceholder) { + Either<ArtifactDataDefinition, StorageOperationStatus> res = null; + ArtifactDataDefinition artifactToUpdate = new ArtifactDataDefinition(artifactInfo); + ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType(); + + Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> triple = getEdgeLabelEnumFromArtifactGroupType(groupType, type); + EdgeLabelEnum edgeLabelEnum = triple.getLeft(); + VertexTypeEnum vertexTypeEnum = triple.getRight(); + + Either<Boolean, StorageOperationStatus> isNeedToCloneEither = isCloneNeeded(componentId, edgeLabelEnum); + if (isNeedToCloneEither.isRight()) { + log.debug("Failed check is clone needed {}", componentId); + return Either.right(isNeedToCloneEither.right().value()); + + } + boolean isNeedToClone = isNeedToCloneEither.left().value(); + + if (artifactId == null || isNeedToClone) { + String uniqueId; + if (edgeLabelEnum != EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS && edgeLabelEnum != EdgeLabelEnum.INSTANCE_ARTIFACTS) { + uniqueId = UniqueIdBuilder.buildPropertyUniqueId(componentId, artifactToUpdate.getArtifactLabel()); + } else { + uniqueId = UniqueIdBuilder.buildInstanceArtifactUniqueId(componentId, instanceId, artifactToUpdate.getArtifactLabel()); + } + artifactToUpdate.setUniqueId(uniqueId); + if (!isDeletePlaceholder) + artifactToUpdate.setEsId(uniqueId); + } else + artifactToUpdate.setUniqueId(artifactId); + + Map<String, ArtifactDataDefinition> artifacts = new HashMap<>(); + Map<String, MapArtifactDataDefinition> artifactInst = null; + if (edgeLabelEnum != EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS && edgeLabelEnum != EdgeLabelEnum.INSTANCE_ARTIFACTS) { + + Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> artifactsEither = this.getDataFromGraph(componentId, edgeLabelEnum); + + if (artifactsEither.isLeft() && artifactsEither.left().value() != null && !artifactsEither.left().value().isEmpty()) { + artifacts = artifactsEither.left().value(); + if (isNeedToClone && artifacts != null) { + artifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE)); + } + } + } else { + + Either<Map<String, MapArtifactDataDefinition>, TitanOperationStatus> artifactsEither = this.getDataFromGraph(componentId, edgeLabelEnum); + if (artifactsEither.isLeft()) { + artifactInst = artifactsEither.left().value(); + if (isNeedToClone && artifactInst != null) { + artifactInst.values().forEach(ma -> ma.getMapToscaDataDefinition().values().forEach(a -> a.setDuplicated(Boolean.TRUE))); + } + MapArtifactDataDefinition artifatcsOnInstance = artifactInst.get(instanceId); + if (artifatcsOnInstance != null) { + artifacts = artifatcsOnInstance.getMapToscaDataDefinition(); + } + } + } + String oldChecksum = null; + String oldVersion = null; + if (artifacts != null && artifacts.containsKey(artifactInfo.getArtifactLabel())) { + ArtifactDataDefinition oldArtifactData = artifacts.get(artifactInfo.getArtifactLabel()); + oldChecksum = oldArtifactData.getArtifactChecksum(); + 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 uniqueId = ""; + if(type != NodeTypeEnum.ResourceInstance) + uniqueId = UniqueIdBuilder.buildPropertyUniqueId(componentId, artifactToUpdate.getArtifactLabel()); + else + uniqueId = UniqueIdBuilder.buildInstanceArtifactUniqueId(componentId, instanceId, artifactToUpdate.getArtifactLabel()); + + artifactToUpdate.setUniqueId(uniqueId); + if (!isDeletePlaceholder) + artifactToUpdate.setEsId(uniqueId); + artifactToUpdate.setDuplicated(Boolean.FALSE); + } + } + } + updateUUID(artifactToUpdate, oldChecksum, oldVersion, isUpdate, edgeLabelEnum); + + if (artifactInfo.getPayloadData() == null) { + if (!artifactToUpdate.getMandatory() || artifactToUpdate.getEsId() != null) { + artifactToUpdate.setEsId(artifactToUpdate.getUniqueId()); + } + } else { + if (artifactToUpdate.getEsId() == null) { + artifactToUpdate.setEsId(artifactToUpdate.getUniqueId()); + } + } + + StorageOperationStatus status = StorageOperationStatus.OK; + if (edgeLabelEnum != EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS && edgeLabelEnum != EdgeLabelEnum.INSTANCE_ARTIFACTS) { + List<ArtifactDataDefinition> toscaDataList = new ArrayList<>(); + toscaDataList.add(artifactToUpdate); + + if (isNeedToClone && artifacts != null) { + artifacts.values().stream().filter(a -> !a.getArtifactLabel().equals(artifactToUpdate.getArtifactLabel())).forEach(toscaDataList::add); + } + status = updateToscaDataOfToscaElement(componentId, edgeLabelEnum, vertexTypeEnum, toscaDataList, JsonPresentationFields.ARTIFACT_LABEL); + } else { + List<ArtifactDataDefinition> toscaDataList = new ArrayList<>(); + toscaDataList.add(artifactToUpdate); + List<String> pathKeys = new ArrayList<>(); + pathKeys.add(instanceId); + if (isNeedToClone) { + MapArtifactDataDefinition artifatcsOnInstance = artifactInst.get(instanceId); + if (artifatcsOnInstance != null) { + artifacts = artifatcsOnInstance.getMapToscaDataDefinition(); + artifacts.put(artifactToUpdate.getArtifactLabel(), artifactToUpdate); + } + + 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) { + log.debug("Failed to update atifacts group for instance {} in component {} edge type {} error {}", instanceId, componentId, edgeLabelEnum, status); + res = Either.right(status); + break; + } + } + } else { + status = updateToscaDataDeepElementsOfToscaElement(componentId, edgeLabelEnum, vertexTypeEnum, toscaDataList, pathKeys, JsonPresentationFields.ARTIFACT_LABEL); + } + } + if (status == StorageOperationStatus.OK) + res = Either.left(artifactToUpdate); + else + res = Either.right(status); + return res; + } + + public void generateUUID(ArtifactDataDefinition artifactData, String oldVesrion) { + + UUID uuid = UUID.randomUUID(); + artifactData.setArtifactUUID(uuid.toString()); + MDC.put("serviceInstanceID", uuid.toString()); + updateVersionAndDate(artifactData, oldVesrion); + } + + private void updateVersionAndDate(ArtifactDataDefinition artifactData, String oldVesrion) { + if (artifactData.getArtifactChecksum() != null) { + long time = System.currentTimeMillis(); + artifactData.setPayloadUpdateDate(time); + } + int newVersion = new Integer(oldVesrion).intValue(); + newVersion++; + artifactData.setArtifactVersion(String.valueOf(newVersion)); + } + + public Either<ArtifactDataDefinition, StorageOperationStatus> removeArtifactOnGraph(ArtifactDefinition artifactFromGraph, String componentId, String instanceId, NodeTypeEnum type, boolean deleteMandatoryArtifact) { + + Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> triple = getEdgeLabelEnumFromArtifactGroupType(artifactFromGraph.getArtifactGroupType(), type); + EdgeLabelEnum edgeLabelEnum = triple.getLeft(); + VertexTypeEnum vertexTypeEnum = triple.getRight(); + + if (deleteMandatoryArtifact || !(artifactFromGraph.getMandatory() || artifactFromGraph.getServiceApi())) { + StorageOperationStatus status; + if (triple.getMiddle()) { + List<String> pathKeys = new ArrayList<>(); + pathKeys.add(instanceId); + status = deleteToscaDataDeepElement(componentId, edgeLabelEnum, vertexTypeEnum, artifactFromGraph.getArtifactLabel(), pathKeys, JsonPresentationFields.ARTIFACT_LABEL); + } else { + status = deleteToscaDataElement(componentId, edgeLabelEnum, vertexTypeEnum, artifactFromGraph.getArtifactLabel(), JsonPresentationFields.ARTIFACT_LABEL); + } + if (status != StorageOperationStatus.OK) + return Either.right(status); + } + return Either.left(artifactFromGraph); + + } + + public Either<ArtifactDataDefinition, StorageOperationStatus> deleteArtifactWithCloningOnGraph(String componentId, ArtifactDefinition artifactToDelete, NodeTypeEnum type, String instanceId, boolean deleteMandatoryArtifact) { + + Either<ArtifactDataDefinition, StorageOperationStatus> result = null; + Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> triple = getEdgeLabelEnumFromArtifactGroupType(artifactToDelete.getArtifactGroupType(), type); + EdgeLabelEnum edgeLabel = triple.getLeft(); + VertexTypeEnum vertexLabel = triple.getRight(); + + Boolean deleteElement = deleteMandatoryArtifact || !(artifactToDelete.getMandatory() || artifactToDelete.getServiceApi()); + Map<String, ToscaDataDefinition> artifacts = null; + GraphVertex parentVertex = null; + Either<Map<String, ToscaDataDefinition>, TitanOperationStatus> getArtifactsRes = null; + + Either<GraphVertex, TitanOperationStatus> getToscaElementRes = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getToscaElementRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get tosca element {} upon getting tosca data from graph. Status is {}. ", componentId, getToscaElementRes.right().value()); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getToscaElementRes.right().value())); + } + if (result == null) { + parentVertex = getToscaElementRes.left().value(); + getArtifactsRes = this.getDataFromGraph(parentVertex, edgeLabel); + if (getArtifactsRes.isRight()) { + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getArtifactsRes.right().value())); + } + } + if (result == null) { + artifacts = getArtifactsRes.left().value(); + if (triple.getMiddle()) { + artifacts.values().forEach(ma -> ((MapArtifactDataDefinition) ma).getMapToscaDataDefinition().values().forEach(a -> a.setDuplicated(Boolean.TRUE))); + MapArtifactDataDefinition artifatcsOnInstance = (MapArtifactDataDefinition) artifacts.get(instanceId); + if (artifatcsOnInstance != null && deleteElement) { + artifatcsOnInstance.getMapToscaDataDefinition().remove(artifactToDelete.getArtifactLabel()); + } + } else { + if (deleteElement) { + artifacts.remove(artifactToDelete.getArtifactLabel()); + } + artifacts.values().stream().forEach(a -> ((ArtifactDataDefinition) a).setDuplicated(Boolean.TRUE)); + } + artifactToDelete.setDuplicated(Boolean.TRUE); + } + if (artifacts != null) { + TitanOperationStatus status = titanDao.deleteEdgeByDirection(parentVertex, Direction.OUT, edgeLabel); + if (status != TitanOperationStatus.OK) { + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } else if (MapUtils.isNotEmpty(artifacts)) { + Either<GraphVertex, StorageOperationStatus> associateResult = associateElementToData(parentVertex, vertexLabel, edgeLabel, artifacts); + if (associateResult.isRight()) { + result = Either.right(associateResult.right().value()); + } + } + } + if (result == null) { + result = Either.left(artifactToDelete); + } + 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 ee1a8a0339..52801751cc 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 @@ -20,15 +20,8 @@ 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; -import java.util.Map; -import java.util.UUID; -import java.util.stream.Collectors; - +import com.thinkaurelius.titan.core.TitanVertex; +import fj.data.Either; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; @@ -36,40 +29,39 @@ import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.apache.tinkerpop.gremlin.structure.Direction; import org.apache.tinkerpop.gremlin.structure.Edge; +import org.apache.tinkerpop.gremlin.structure.Property; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.apache.tinkerpop.gremlin.structure.VertexProperty; 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.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.IdBuilderUtils; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapDataDefinition; -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.datatypes.tosca.ToscaDataDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; +import org.openecomp.sdc.be.model.operations.StorageException; 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.jsongraph.util.CommonUtility; import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.util.ValidationUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import com.thinkaurelius.titan.core.TitanVertex; - -import fj.data.Either; +import java.util.*; +import java.util.EnumMap; +import java.util.stream.Collectors; /** * public abstract class BaseOperation provides base operation functionality and common fields @@ -77,1212 +69,1220 @@ import fj.data.Either; */ public abstract class BaseOperation { - private static Logger logger = LoggerFactory.getLogger(BaseOperation.class.getName()); - - public static final String VF_MODULE = "org.openecomp.groups.VfModule"; - - @Autowired - protected TitanDao titanDao; - - @Autowired - protected NodeTypeOperation nodeTypeOperation; - - @Autowired - protected TopologyTemplateOperation topologyTemplateOperation; - - public void setTitanDao(TitanDao titanDao) { - this.titanDao = titanDao; - } - /** - * Returns reference to appropriate toscaTemplateOperation - * - * @param componentType - * @return - */ - public ToscaElementOperation getToscaElementOperation(ComponentTypeEnum componentType) { - ToscaElementOperation operation; - switch (componentType) { - case SERVICE: - case RESOURCE: - operation = topologyTemplateOperation; - break; - default: - operation = nodeTypeOperation; - break; - } - return operation; - } - - /** - * Returns reference to appropriate toscaTemplateOperation - * - * @param toscaElementType - * @return - */ - public ToscaElementOperation getToscaElementOperation(ToscaElementTypeEnum toscaElementType) { - ToscaElementOperation operation; - switch (toscaElementType) { - case TopologyTemplate: - operation = topologyTemplateOperation; - break; - case NodeType: - operation = nodeTypeOperation; - break; - default: - operation = null; - break; - } - return operation; - } - - /** - * Returns reference to appropriate toscaTemplateOperation - * - * @param toscaElementType - * @return - */ - public ToscaElementOperation getToscaElementOperation(VertexTypeEnum toscaElementType) { - ToscaElementOperation operation; - switch (toscaElementType) { - case TOPOLOGY_TEMPLATE: - operation = topologyTemplateOperation; - break; - case NODE_TYPE: - operation = nodeTypeOperation; - break; - default: - operation = null; - break; - } - return operation; - } - /** - * Converts received vertex to User object - * - * @param ownerV - * @return - */ - public User convertToUser(Vertex ownerV) { - User owner = new User(); - owner.setUserId((String) ownerV.property(GraphPropertyEnum.USERID.getProperty()).value()); - VertexProperty<Object> property = ownerV.property(GraphPropertyEnum.ROLE.getProperty()); - if(property != null && property.isPresent() ){ - owner.setRole((String) property.value()); - } - - property = ownerV.property(GraphPropertyEnum.FIRST_NAME.getProperty()); - if(property != null && property.isPresent() ){ - owner.setFirstName((String) ownerV.property(GraphPropertyEnum.FIRST_NAME.getProperty()).value()); - } - - property = ownerV.property(GraphPropertyEnum.LAST_NAME.getProperty()); - if( property != null && property.isPresent() ){ - owner.setLastName((String) ownerV.property(GraphPropertyEnum.LAST_NAME.getProperty()).value()); - } - - property = ownerV.property(GraphPropertyEnum.EMAIL.getProperty()); - if( property != null && property.isPresent() ){ - owner.setEmail((String) ownerV.property(GraphPropertyEnum.EMAIL.getProperty()).value()); - } - - property = ownerV.property(GraphPropertyEnum.LAST_LOGIN_TIME.getProperty()); - if( property != null && property.isPresent() ){ - owner.setLastLoginTime((Long) ownerV.property(GraphPropertyEnum.LAST_LOGIN_TIME.getProperty()).value()); - } - return owner; - } - - protected <T extends ToscaDataDefinition> Either<Map<String, T>, TitanOperationStatus> getDataFromGraph(GraphVertex componentV, EdgeLabelEnum edgelabel) { - Either<Pair<GraphVertex, Map<String, T>>, TitanOperationStatus> dataVertex = getDataAndVertexFromGraph(componentV, edgelabel); - if (dataVertex.isRight()) { - return Either.right(dataVertex.right().value()); - } - Map<String, T> properties = dataVertex.left().value().getRight(); - return Either.left(properties); - } - - @SuppressWarnings("unchecked") - protected <T extends ToscaDataDefinition> Either<Pair<GraphVertex, Map<String, T>>, TitanOperationStatus> getDataAndVertexFromGraph(GraphVertex componentV, EdgeLabelEnum edgelabel) { - Either<GraphVertex, TitanOperationStatus> dataVertex = getDataVertex(componentV, edgelabel); - if (dataVertex.isRight()) { - return Either.right(dataVertex.right().value()); - } - GraphVertex propV = dataVertex.left().value(); - Map<String, T> properties = (Map<String, T>) propV.getJson(); - Pair<GraphVertex, Map<String, T>> pair = new ImmutablePair<GraphVertex, Map<String, T>>(propV, properties); - return Either.left(pair); - } - - protected <T extends ToscaDataDefinition> Either<GraphVertex, TitanOperationStatus> getDataVertex(GraphVertex componentV, EdgeLabelEnum edgelabel) { - Either<GraphVertex, TitanOperationStatus> childVertex = titanDao.getChildVertex(componentV, edgelabel, JsonParseFlagEnum.ParseJson); - if (childVertex.isRight()) { - if (childVertex.right().value() != TitanOperationStatus.NOT_FOUND) { - logger.debug("failed to fetch {} for tosca element with id {}, error {}", edgelabel, componentV.getUniqueId(), childVertex.right().value()); - } - return Either.right(childVertex.right().value()); - } - GraphVertex propV = childVertex.left().value(); - return Either.left(propV); - } - - /** - * Returns tosca data belonging to tosca element specified by uid according received label - * - * @param toscaElementUid - * @param edgelabel - * @return - */ - public <T extends ToscaDataDefinition> Either<Map<String, T>, TitanOperationStatus> getDataFromGraph(String toscaElementUid, EdgeLabelEnum edgelabel) { - - Either<Map<String, T>, TitanOperationStatus> result = null; - Either<GraphVertex, TitanOperationStatus> getToscaElementRes; - - getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); - if (getToscaElementRes.isRight()) { - TitanOperationStatus status = getToscaElementRes.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get tosca element {} upon getting tosca data from graph. Status is {}. ", toscaElementUid, status); - result = Either.right(status); - } - if (result == null) { - result = getDataFromGraph(getToscaElementRes.left().value(), edgelabel); - } - return result; - } - - public Either<GraphVertex, TitanOperationStatus> findUserVertex(String userId) { - return titanDao.getVertexByPropertyAndLabel(GraphPropertyEnum.USERID, userId, VertexTypeEnum.USER, JsonParseFlagEnum.NoParse); - } - - /** - * - * @param elemementId - * @param label - * @return - */ - public Either<Boolean, StorageOperationStatus> isCloneNeeded(String elemementId, EdgeLabelEnum label) { - Either<GraphVertex, TitanOperationStatus> vertexById = titanDao.getVertexById(elemementId); - if (vertexById.isRight()) { - logger.debug("Failed to fetch element by id {} error {}", elemementId, vertexById.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexById.right().value())); - } - GraphVertex toscaElementVertex = vertexById.left().value(); - Either<GraphVertex, TitanOperationStatus> childVertex = titanDao.getChildVertex(toscaElementVertex, label, JsonParseFlagEnum.NoParse); - if (childVertex.isRight()) { - if (childVertex.right().value() != TitanOperationStatus.NOT_FOUND) { - logger.debug("failed to fetch {} for tosca element with id {}, error {}", label, toscaElementVertex.getUniqueId(), childVertex.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(childVertex.right().value())); - } - return Either.left(Boolean.FALSE); - } - GraphVertex dataVertex = childVertex.left().value(); - Iterator<Edge> edges = dataVertex.getVertex().edges(Direction.IN, label.name()); - int edgeCount = 0; - while (edges.hasNext()) { - edges.next(); - ++edgeCount; - } - if (edgeCount > 1) { - return Either.left(Boolean.TRUE); - } else { - return Either.left(Boolean.FALSE); - } - } - - protected Either<GraphVertex, TitanOperationStatus> updateOrCopyOnUpdate(GraphVertex dataVertex, GraphVertex toscaElementVertex, EdgeLabelEnum label) { - Iterator<Edge> edges = dataVertex.getVertex().edges(Direction.IN, label.name()); - int edgeCount = 0; - Edge edgeToRemove = null; - while (edges.hasNext()) { - Edge edge = edges.next(); - ++edgeCount; - Vertex outVertex = edge.outVertex(); - String outId = (String) titanDao.getProperty((TitanVertex) outVertex, GraphPropertyEnum.UNIQUE_ID.getProperty()); - if (toscaElementVertex.getUniqueId().equals(outId)) { - edgeToRemove = edge; - } - } - if (edgeToRemove == null) { - logger.debug("No edges {} from vertex {} to vertex {}", label, toscaElementVertex.getUniqueId(), dataVertex.getUniqueId()); - return Either.right(TitanOperationStatus.GENERAL_ERROR); - } - switch (edgeCount) { - case 0: - // error - logger.debug("No edges {} to vertex {}", label, dataVertex.getUniqueId()); - return Either.right(TitanOperationStatus.GENERAL_ERROR); - case 1: - // update - logger.trace("Only one edge {} to vertex {}. Update vertex", label, dataVertex.getUniqueId()); - return titanDao.updateVertex(dataVertex); - default: - // copy on update - logger.trace("More than one edge {} to vertex {}. Need to clone vertex", label, dataVertex.getUniqueId()); - return cloneDataVertex(dataVertex, toscaElementVertex, label, edgeToRemove); - } - } - - private Either<GraphVertex, TitanOperationStatus> cloneDataVertex(GraphVertex dataVertex, GraphVertex toscaElementVertex, EdgeLabelEnum label, Edge edgeToRemove) { - GraphVertex newDataVertex = new GraphVertex(dataVertex.getLabel()); - String id = IdBuilderUtils.generateChildId(toscaElementVertex.getUniqueId(), dataVertex.getLabel()); - newDataVertex.setUniqueId(id); - newDataVertex.cloneData(dataVertex); - - Either<GraphVertex, TitanOperationStatus> createVertex = titanDao.createVertex(newDataVertex); - if (createVertex.isRight()) { - logger.debug("Failed to clone data vertex for {} error {}", dataVertex.getUniqueId(), createVertex.right().value()); - return createVertex; - } - newDataVertex = createVertex.left().value(); - TitanOperationStatus createEdge = titanDao.createEdge(toscaElementVertex, newDataVertex, label, titanDao.getEdgeProperties(edgeToRemove)); - if (createEdge != TitanOperationStatus.OK) { - logger.debug("Failed to associate vertex {} to vertex {}, error {}", toscaElementVertex.getUniqueId(), newDataVertex.getUniqueId(), createEdge); - return Either.right(createEdge); - } - edgeToRemove.remove(); - return Either.left(newDataVertex); - } - - public Either<GraphVertex, StorageOperationStatus> assosiateElementToData(GraphVertex element, VertexTypeEnum vertexLabel, EdgeLabelEnum edgeLabel, Map<String, ? extends ToscaDataDefinition> data) { - GraphVertex dataV = new GraphVertex(vertexLabel); - String id = IdBuilderUtils.generateChildId(element.getUniqueId(), vertexLabel); - dataV.setUniqueId(id); - dataV.setJson(data); - Either<GraphVertex, TitanOperationStatus> createVertex = titanDao.createVertex(dataV); - if (createVertex.isRight()) { - logger.trace("Failed to create {} vertex for type node {}", vertexLabel, element.getUniqueId()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createVertex.right().value())); - } - dataV = createVertex.left().value(); - TitanOperationStatus createEdgeStatus = titanDao.createEdge(element.getVertex(), dataV.getVertex(), edgeLabel, new HashMap<>()); - if (createEdgeStatus != TitanOperationStatus.OK) { - logger.trace("Failed to create {} vertex for type node {}", vertexLabel, element.getUniqueId()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createEdgeStatus)); - } - return Either.left(dataV); - } - - /** - * Adds tosca data element to tosca element according received labels - * - * @param toscaElement - * @param edgeLabel - * @param vertexLabel - * @param toscaData - * @param mapKeyField - * @return - */ - public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, JsonPresentationFields mapKeyField) { - - List<T> toscaDataList = new ArrayList<>(); - toscaDataList.add(toscaData); - return addToscaDataToToscaElement(toscaElement, edgeLabel, vertexLabel, toscaDataList, mapKeyField); - } - - /** - * Adds tosca data deep element to tosca element according received labels - * - * @param toscaElement - * @param edgeLabel - * @param vertexLabel - * @param toscaData - * @param pathKeys - * @param mapKeyField - * @return - */ - public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataDeepElementToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, List<String> pathKeys, - JsonPresentationFields mapKeyField) { - - List<T> toscaDataList = new ArrayList<>(); - toscaDataList.add(toscaData); - return addToscaDataDeepElementsToToscaElement(toscaElement, edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField); - } - - /** - * Converts recieved map of tosca data deep elements to list and adds it to tosca element according received labels - * - * @param toscaElement - * @param edgeLabel - * @param vertexLabel - * @param toscaDataMap - * @param pathKeys - * @param mapKeyField - * @return - */ - public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataDeepElementsToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, Map<String, T> toscaDataMap, List<String> pathKeys, - JsonPresentationFields mapKeyField) { - - if (toscaDataMap != null) { - return addToscaDataDeepElementsToToscaElement(toscaElement, edgeLabel, vertexLabel, toscaDataMap.values().stream().collect(Collectors.toList()), pathKeys, mapKeyField); - } - return StorageOperationStatus.OK; - } - - /** - * Adds list of tosca data deep elements to tosca element according received labels - * - * @param toscaElement - * @param edgeLabel - * @param vertexLabel - * @param toscaDataList - * @param pathKeys - * @param mapKeyField - * @return - */ - public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataDeepElementsToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<T> toscaDataList, List<String> pathKeys, - JsonPresentationFields mapKeyField) { - - return updateOrAddToscaDataDeepElement(toscaElement, edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField, false); - } - - /** - * Updates list of tosca data elements of tosca element according received labels - * - * @param toscaElement - * @param edgeLabel - * @param vertexLabel - * @param toscaData - * @param mapKeyField - * @return - */ - public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataOfToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, JsonPresentationFields mapKeyField) { - List<T> toscaDataList = new ArrayList<>(); - toscaDataList.add(toscaData); - return updateToscaDataOfToscaElement(toscaElement, edgeLabel, vertexLabel, toscaDataList, mapKeyField); - } - - /** - * Updates tosca data deep element of tosca element according received labels - * - * @param toscaElement - * @param edgeLabel - * @param vertexLabel - * @param toscaData - * @param pathKeys - * @param mapKeyField - * @return - */ - public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataDeepElementOfToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, List<String> pathKeys, - JsonPresentationFields mapKeyField) { - List<T> toscaDataList = new ArrayList<>(); - toscaDataList.add(toscaData); - return updateToscaDataDeepElementsOfToscaElement(toscaElement, edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField); - } - - /** - * Updates tosca data deep elements of tosca element according received labels - * - * @param toscaElement - * @param edgeLabel - * @param vertexLabel - * @param toscaDataList - * @param pathKeys - * @param mapKeyField - * @return - */ - public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataDeepElementsOfToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<T> toscaDataList, List<String> pathKeys, - JsonPresentationFields mapKeyField) { - - return updateOrAddToscaDataDeepElement(toscaElement, edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField, true); - } - - /** - * Adds tosca data element to tosca element with specified uid according received labels - * - * @param toscaElementUid - * @param toscaData - * @param edgeLabel - * @param vertexLabel - * @param mapKeyField - * @return - */ - public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataToToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, JsonPresentationFields mapKeyField) { - - List<T> toscaDataList = new ArrayList<>(); - toscaDataList.add(toscaData); - return addToscaDataToToscaElement(toscaElementUid, edgeLabel, vertexLabel, toscaDataList, mapKeyField); - } - - /** - * Adds tosca data deep element to tosca element with specified uid according received labels - * - * @param toscaElementUid - * @param edgeLabel - * @param vertexLabel - * @param toscaData - * @param pathKeys - * @param mapKeyField - * @return - */ - public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataDeepElementToToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, List<String> pathKeys, - JsonPresentationFields mapKeyField) { - - List<T> toscaDataList = new ArrayList<>(); - toscaDataList.add(toscaData); - return addToscaDataDeepElementsToToscaElement(toscaElementUid, edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField); - } - - public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataDeepElementOfToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, List<String> pathKeys, - JsonPresentationFields mapKeyField) { - - List<T> toscaDataList = new ArrayList<>(); - toscaDataList.add(toscaData); - return updateToscaDataDeepElementsOfToscaElement(toscaElementUid, edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField); - } - - public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataDeepElementsOfToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<T> toscaDataList, List<String> pathKeys, - JsonPresentationFields mapKeyField) { - - StorageOperationStatus statusRes = null; - Either<GraphVertex, TitanOperationStatus> getToscaElementRes; - - getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); - if (getToscaElementRes.isRight()) { - TitanOperationStatus status = getToscaElementRes.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get tosca element {} upon adding the properties. Status is {}. ", toscaElementUid, status); - statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - if (statusRes == null && CollectionUtils.isNotEmpty(toscaDataList)) { - statusRes = updateToscaDataDeepElementsOfToscaElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField); - } - if (statusRes == null) { - statusRes = StorageOperationStatus.OK; - } - 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 - * - * @param toscaElementUid - * @param edgeLabel - * @param vertexLabel - * @param toscaDataList - * @param pathKeys - * @param mapKeyField - * @return - */ - public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataDeepElementsToToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<T> toscaDataList, List<String> pathKeys, - JsonPresentationFields mapKeyField) { - - StorageOperationStatus statusRes = null; - Either<GraphVertex, TitanOperationStatus> getToscaElementRes; - - getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); - if (getToscaElementRes.isRight()) { - TitanOperationStatus status = getToscaElementRes.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get tosca element {} upon adding the properties. Status is {}. ", toscaElementUid, status); - statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - if (statusRes == null && CollectionUtils.isNotEmpty(toscaDataList)) { - statusRes = addToscaDataDeepElementsToToscaElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField); - } - if (statusRes == null) { - statusRes = StorageOperationStatus.OK; - } - return statusRes; - } - - public <T extends ToscaDataDefinition> StorageOperationStatus deleteToscaDataDeepElementsBlockToToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, String key) { - - StorageOperationStatus statusRes = null; - Either<GraphVertex, TitanOperationStatus> getToscaElementRes; - - getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); - if (getToscaElementRes.isRight()) { - TitanOperationStatus status = getToscaElementRes.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get tosca element {} upon adding the properties. Status is {}. ", toscaElementUid, status); - statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - if (statusRes == null) { - statusRes = deleteToscaDataDeepElementsBlockToToscaElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, key); - } - if (statusRes == null) { - statusRes = StorageOperationStatus.OK; - } - return statusRes; - } - - public <T extends ToscaDataDefinition> StorageOperationStatus deleteToscaDataDeepElementsBlockToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, String key) { - - StorageOperationStatus result = null; - GraphVertex toscaDataVertex = null; - Either<GraphVertex, TitanOperationStatus> toscaDataVertexRes = titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson); - if (toscaDataVertexRes.isRight()) { - TitanOperationStatus status = toscaDataVertexRes.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get child vertex of the tosca element {} by label {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel, status); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(toscaDataVertexRes.right().value()); - } - if (result == null) { - toscaDataVertex = toscaDataVertexRes.left().value(); - result = deleteDeepElementsBlock(toscaDataVertex, key); - } - if (result == null) { - Either<GraphVertex, TitanOperationStatus> updateOrCopyRes = updateOrCopyOnUpdate(toscaDataVertex, toscaElement, edgeLabel); - if (updateOrCopyRes.isRight()) { - TitanOperationStatus status = updateOrCopyRes.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete tosca data block {} from the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), status); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - } - if (result == null) { - result = StorageOperationStatus.OK; - } - return result; - } - - @SuppressWarnings("rawtypes") - public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataDeepElementsBlockToToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, MapDataDefinition toscaDataMap, String key) { - - StorageOperationStatus statusRes = null; - Either<GraphVertex, TitanOperationStatus> getToscaElementRes; - - getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); - if (getToscaElementRes.isRight()) { - TitanOperationStatus status = getToscaElementRes.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get tosca element {} upon adding the properties. Status is {}. ", toscaElementUid, status); - statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - if (statusRes == null && toscaDataMap != null) { - statusRes = addToscaDataDeepElementsBlockToToscaElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, toscaDataMap, key); - } - if (statusRes == null) { - statusRes = StorageOperationStatus.OK; - } - return statusRes; - } - - @SuppressWarnings("rawtypes") - public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataDeepElementsBlockToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, MapDataDefinition toscaDataMap, String key) { - - StorageOperationStatus result = null; - GraphVertex toscaDataVertex = null; - Either<GraphVertex, TitanOperationStatus> toscaDataVertexRes = titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson); - if (toscaDataVertexRes.isRight() && toscaDataVertexRes.right().value() != TitanOperationStatus.NOT_FOUND) { - TitanOperationStatus status = toscaDataVertexRes.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get child vertex of the tosca element {} by label {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel, status); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(toscaDataVertexRes.right().value()); - } - if (result == null) { - if (toscaDataVertexRes.isLeft()) { - toscaDataVertex = toscaDataVertexRes.left().value(); - result = addDeepElementsBlock(toscaDataVertex, toscaDataMap, key); - } - } - if (result == null) { - if (toscaDataVertex != null) { - Either<GraphVertex, TitanOperationStatus> updateOrCopyRes = updateOrCopyOnUpdate(toscaDataVertex, toscaElement, edgeLabel); - if (updateOrCopyRes.isRight()) { - TitanOperationStatus status = updateOrCopyRes.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to add tosca data {} to the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), status); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - } else { - Map<String, MapDataDefinition> data = new HashMap<>(); - data.put(key, toscaDataMap); - Either<GraphVertex, StorageOperationStatus> createRes = assosiateElementToData(toscaElement, vertexLabel, edgeLabel, data); - if (createRes.isRight()) { - StorageOperationStatus status = createRes.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to assosiate tosca data {} of the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), status); - result = status; - } - } - } - if (result == null) { - result = StorageOperationStatus.OK; - } - return result; - } - - /** - * - * @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 - * @param edgeLabel - * @param vertexLabel - * @param toscaData - * @param mapKeyField - * @return - */ - public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataOfToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, JsonPresentationFields mapKeyField) { - - List<T> toscaDataList = new ArrayList<>(); - toscaDataList.add(toscaData); - return updateToscaDataOfToscaElement(toscaElementUid, edgeLabel, vertexLabel, toscaDataList, mapKeyField); - } - - /** - * Updates list of tosca data elements belonging to tosca element with specified uid according received labels - * - * @param toscaElementUid - * @param edgeLabel - * @param vertexLabel - * @param toscaDataList - * @param mapKeyField - * @return - */ - public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataOfToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<T> toscaDataList, JsonPresentationFields mapKeyField) { - - StorageOperationStatus statusRes = null; - Either<GraphVertex, TitanOperationStatus> getToscaElementRes; - - getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); - if (getToscaElementRes.isRight()) { - TitanOperationStatus status = getToscaElementRes.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get tosca element {} upon adding the properties. Status is {}. ", toscaElementUid, status); - statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - if (statusRes == null && CollectionUtils.isNotEmpty(toscaDataList)) { - statusRes = updateToscaDataOfToscaElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, toscaDataList, mapKeyField); - } - if (statusRes == null) { - statusRes = StorageOperationStatus.OK; - } - return statusRes; - } - - /** - * Adds list of tosca data elements to tosca element with specified uid according received labels - * - * @param toscaElementUid - * @param edgeLabel - * @param vertexLabel - * @param toscaDataList - * @param mapKeyField - * @return - */ - public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataToToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<T> toscaDataList, JsonPresentationFields mapKeyField) { - - StorageOperationStatus statusRes = null; - Either<GraphVertex, TitanOperationStatus> getToscaElementRes; - - getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); - if (getToscaElementRes.isRight()) { - TitanOperationStatus status = getToscaElementRes.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get tosca element {} upon adding the properties. Status is {}. ", toscaElementUid, status); - statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - if (statusRes == null && CollectionUtils.isNotEmpty(toscaDataList)) { - statusRes = addToscaDataToToscaElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, toscaDataList, mapKeyField); - } - if (statusRes == null) { - statusRes = StorageOperationStatus.OK; - } - return statusRes; - } - - /** - * Converts recieved map of tosca data elements to list and adds it to tosca element according received labels - * - * @param toscaElement - * @param edgeLabel - * @param vertexLabel - * @param toscaDataMap - * @param mapKeyField - * @return - */ - public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, Map<String, T> toscaDataMap, JsonPresentationFields mapKeyField) { - - return addToscaDataToToscaElement(toscaElement, edgeLabel, vertexLabel, toscaDataMap.values().stream().collect(Collectors.toList()), mapKeyField); - } - - /** - * Adds list of tosca data elements to tosca element according received labels - * - * @param toscaElement - * @param edgeLabel - * @param vertexLabel - * @param toscaDataList - * @param mapKeyField - * @return - */ - public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<T> toscaDataList, JsonPresentationFields mapKeyField) { - - return updateOrAddToscaData(toscaElement, edgeLabel, vertexLabel, toscaDataList, mapKeyField, false); - } - - /** - * Updates list of tosca data elements belonging to tosca element according received labels - * - * @param toscaElement - * @param edgeLabel - * @param vertexLabel - * @param toscaDataList - * @param mapKeyField - * @return - */ - public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataOfToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<T> toscaDataList, JsonPresentationFields mapKeyField) { - - return updateOrAddToscaData(toscaElement, edgeLabel, vertexLabel, toscaDataList, mapKeyField, true); - } - - @SuppressWarnings("unchecked") - private <T extends ToscaDataDefinition> StorageOperationStatus updateOrAddToscaData(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<T> toscaDataList, JsonPresentationFields mapKeyField, boolean isUpdate) { - StorageOperationStatus result = null; - GraphVertex toscaDataVertex = null; - Map<String, T> existingToscaDataMap = null; - Either<Map<String, T>, StorageOperationStatus> validateRes = null; - Map<String, T> mergedToscaDataMap; - Either<GraphVertex, TitanOperationStatus> toscaDataVertexRes = titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson); - if (toscaDataVertexRes.isRight() && toscaDataVertexRes.right().value() != TitanOperationStatus.NOT_FOUND) { - TitanOperationStatus status = toscaDataVertexRes.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get child vertex of the tosca element {} by label {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel, status); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(toscaDataVertexRes.right().value()); - } - if (result == null) { - if (toscaDataVertexRes.isLeft()) { - toscaDataVertex = toscaDataVertexRes.left().value(); - existingToscaDataMap = (Map<String, T>) toscaDataVertex.getJson(); - } - - 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); - } - } - if (result == null) { - mergedToscaDataMap = validateRes.left().value(); - result = handleToscaData(toscaElement, vertexLabel, edgeLabel, toscaDataVertex, mergedToscaDataMap); - } - if (result == null) { - result = StorageOperationStatus.OK; - } - return result; - - } - - @SuppressWarnings("unchecked") - public <T extends ToscaDataDefinition> StorageOperationStatus updateFullToscaData(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, Map<String, T> toscaData) { - StorageOperationStatus result = null; - GraphVertex toscaDataVertex = null; - Map<String, T> existingToscaDataMap = null; - - Either<GraphVertex, TitanOperationStatus> toscaDataVertexRes = titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson); - if (toscaDataVertexRes.isRight() && toscaDataVertexRes.right().value() != TitanOperationStatus.NOT_FOUND) { - TitanOperationStatus status = toscaDataVertexRes.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get child vertex of the tosca element {} by label {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel, status); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(toscaDataVertexRes.right().value()); - } - if (result == null) { - if (toscaDataVertexRes.isLeft()) { - toscaDataVertex = toscaDataVertexRes.left().value(); - existingToscaDataMap = (Map<String, T>) toscaDataVertex.getJson(); - } - - - } - if (result == null) { - - result = handleToscaData(toscaElement, vertexLabel, edgeLabel, toscaDataVertex, toscaData); - } - if (result == null) { - result = StorageOperationStatus.OK; - } - return result; - - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - private <T, K extends ToscaDataDefinition> StorageOperationStatus updateOrAddToscaDataDeepElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<K> toscaDataList, List<String> pathKeys, - JsonPresentationFields mapKeyField, boolean isUpdate) { - - StorageOperationStatus result = null; - GraphVertex toscaDataVertex = null; - Map<String, K> existingDeepElementsMap = null; - Either<Map<String, K>, StorageOperationStatus> validateRes = null; - Either<GraphVertex, TitanOperationStatus> toscaDataVertexRes = titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson); - if (toscaDataVertexRes.isRight() && toscaDataVertexRes.right().value() != TitanOperationStatus.NOT_FOUND) { - TitanOperationStatus status = toscaDataVertexRes.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get child vertex of the tosca element {} by label {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel, status); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(toscaDataVertexRes.right().value()); - } - if (result == null) { - if (toscaDataVertexRes.isLeft()) { - toscaDataVertex = toscaDataVertexRes.left().value(); - existingDeepElementsMap = getDeepElements(toscaDataVertex, pathKeys); - } - validateRes = validateMergeToscaData(toscaElement, toscaDataList, mapKeyField, existingDeepElementsMap, 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); - } - } - if (result == null) { - updateDeepElements(toscaDataVertex, validateRes.left().value(), pathKeys); - Map<String, K> toscaDataToHandle; - if(toscaDataVertex == null){ - toscaDataToHandle = new HashMap<>(); - Map<String, K> currMap = toscaDataToHandle; - for (int i = 1; i < pathKeys.size()-1; ++i) { - currMap.put(pathKeys.get(i), (K) new MapDataDefinition()); - currMap = (Map<String, K>) ((MapDataDefinition) currMap).getMapToscaDataDefinition().get(pathKeys.get(i)); - } - toscaDataToHandle.put(pathKeys.get(pathKeys.size()-1), (K) new MapDataDefinition(validateRes.left().value())); - - } else { - toscaDataToHandle = (Map<String, K>) toscaDataVertex.getJson(); - } - result = handleToscaData(toscaElement, vertexLabel, edgeLabel, toscaDataVertex, toscaDataToHandle); - } - if (result == null) { - result = StorageOperationStatus.OK; - } - return result; - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - private <T, K extends ToscaDataDefinition> void updateDeepElements(GraphVertex toscaDataVertex, Map<String, K> mergedDeepElementMap, List<String> pathKeys) { - - if (toscaDataVertex != null && MapUtils.isNotEmpty(mergedDeepElementMap)) { - Map<String, MapDataDefinition> currMap = (Map<String, MapDataDefinition>) toscaDataVertex.getJson(); - if(!currMap.containsKey(pathKeys.get(0))){ - currMap.put(pathKeys.get(0), new MapDataDefinition<>()); - } - MapDataDefinition currDeepElement = currMap.get(pathKeys.get(0)); - - for (int i = 1; i < pathKeys.size(); ++i) { - if(currDeepElement.findByKey(pathKeys.get(i)) == null){ - currDeepElement.put(pathKeys.get(i), new MapDataDefinition<>()); - } - currDeepElement = (MapDataDefinition) currDeepElement.findByKey(pathKeys.get(i)); - } - if(currDeepElement != null){ - for (Map.Entry<String, K> elementEntry : mergedDeepElementMap.entrySet()) { - currDeepElement.put(elementEntry.getKey(), elementEntry.getValue()); - } - } - } - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - private <T, K extends ToscaDataDefinition> Map<String, K> getDeepElements(GraphVertex toscaDataVertex, List<String> pathKeys) { - Map<String, K> result = null; - Map<String, T> currMap = (Map<String, T>) toscaDataVertex.getJson(); - MapDataDefinition currDeepElement = (MapDataDefinition) currMap.get(pathKeys.get(0)); - for (int i = 1; i < pathKeys.size(); ++i) { - currDeepElement = (MapDataDefinition) currDeepElement.findByKey(pathKeys.get(i)); - } - if(currDeepElement != null){ - result = (Map<String, K>) currDeepElement.getMapToscaDataDefinition(); - } - return result; - } - - @SuppressWarnings("unchecked") - private <T extends ToscaDataDefinition> StorageOperationStatus addDeepElementsBlock(GraphVertex toscaDataVertex, T toscaDataBlock, String key) { - - StorageOperationStatus result = null; - Map<String, T> currMap = (Map<String, T>) toscaDataVertex.getJson(); - if (currMap.containsKey(key)) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to add block of deep tosca data elements by label {}." + " The block element with the same key {} already exists. ", toscaDataVertex.getLabel(), key); - result = StorageOperationStatus.ENTITY_ALREADY_EXISTS; - } - if (result == null) { - currMap.put(key, toscaDataBlock); - } - return result; - } - - @SuppressWarnings("unchecked") - private <T extends ToscaDataDefinition> StorageOperationStatus deleteDeepElementsBlock(GraphVertex toscaDataVertex, String key) { - - StorageOperationStatus result = null; - Map<String, T> currMap = (Map<String, T>) toscaDataVertex.getJson(); - if (!currMap.containsKey(key)) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete block of deep tosca data elements by label {}." + " The block element with the same key {} doesn't exist. ", toscaDataVertex.getLabel(), key); - result = StorageOperationStatus.NOT_FOUND; - } - if (result == null) { - currMap.remove(key); - } - return null; - } - - /** - * Removes tosca data vertex belonging to tosca element specified by uid according label - * - * @param toscaElementUid - * @param edgeLabel - * @param vertexLabel - * @return - */ - public StorageOperationStatus removeToscaData(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel) { - - StorageOperationStatus statusRes = StorageOperationStatus.OK; - Either<GraphVertex, TitanOperationStatus> getToscaElementRes; - - getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); - if (getToscaElementRes.isRight()) { - TitanOperationStatus status = getToscaElementRes.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get tosca element {} upon adding the properties. Status is {}. ", toscaElementUid, status); - statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - if (statusRes == StorageOperationStatus.OK) { - statusRes = removeToscaDataVertex(getToscaElementRes.left().value(), edgeLabel, vertexLabel); - } - return statusRes; - } - - /** - * Removes tosca data vertex belonging to tosca element according label - * - * @param toscaElement - * @param edgeLabel - * @param vertexLabel - * @return - */ - public StorageOperationStatus removeToscaDataVertex(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel) { - StorageOperationStatus result = null; - GraphVertex toscaDataVertex = null; - Iterator<Edge> edges = null; - int edgeCounter = 0; - Edge edge = null; - Edge edgeToDelete = null; - Either<GraphVertex, TitanOperationStatus> toscaDataVertexRes = titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson); - if (toscaDataVertexRes.isRight()) { - TitanOperationStatus status = toscaDataVertexRes.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed remove tosca data vertex of the tosca element {} by label {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel, status); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(toscaDataVertexRes.right().value()); - } - if (result == null) { - toscaDataVertex = toscaDataVertexRes.left().value(); - edges = toscaDataVertex.getVertex().edges(Direction.IN); - if (edges == null || !edges.hasNext()) { - result = StorageOperationStatus.NOT_FOUND; - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed remove tosca data vertex of the tosca element {} by label {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel, result); - } - } - if (result == null) { - while (edges.hasNext()) { - ++edgeCounter; - edge = edges.next(); - if (edge.outVertex().id().equals(toscaElement.getVertex().id())) { - edgeToDelete = edge; - break; - } - } - if (edgeToDelete == null) { - result = StorageOperationStatus.NOT_FOUND; - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed remove tosca data vertex of the tosca element {} by label {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel, result); - } - } - if (result == null) { - if (edgeCounter > 1) { - edgeToDelete.remove(); - } else { - toscaDataVertex.getVertex().remove(); - } - } - if (result == null) { - result = StorageOperationStatus.OK; - } - return result; - } - - /** - * Deletes tosca data elements belonging to tosca element specified by uid according label - * - * @param toscaElementUid - * @param edgeLabel - * @param uniqueKeys - * @return - */ - public StorageOperationStatus deleteToscaDataElements(String toscaElementUid, EdgeLabelEnum edgeLabel, List<String> uniqueKeys) { - - StorageOperationStatus statusRes = StorageOperationStatus.OK; - Either<GraphVertex, TitanOperationStatus> getToscaElementRes; - - getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); - if (getToscaElementRes.isRight()) { - TitanOperationStatus status = getToscaElementRes.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get tosca element {} upon adding the properties. Status is {}. ", toscaElementUid, status); - statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - if (statusRes == StorageOperationStatus.OK) { - statusRes = deleteToscaDataElements(getToscaElementRes.left().value(), edgeLabel, uniqueKeys); - } - return statusRes; - } - - /** - * Deletes tosca data element belonging to tosca element specified by uid according label - * - * @param toscaElementUid - * @param edgeLabel - * @param vertexLabel - * @param uniqueKey - * @param mapKeyField - * @return - */ - public StorageOperationStatus deleteToscaDataElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, String uniqueKey, JsonPresentationFields mapKeyField) { - - StorageOperationStatus statusRes = StorageOperationStatus.OK; - Either<GraphVertex, TitanOperationStatus> getToscaElementRes; - - getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); - if (getToscaElementRes.isRight()) { - TitanOperationStatus status = getToscaElementRes.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get tosca element {} upon adding the properties. Status is {}. ", toscaElementUid, status); - statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - if (statusRes == StorageOperationStatus.OK) { - statusRes = deleteToscaDataElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, uniqueKey, mapKeyField); - } - return statusRes; - - } - - /** - * Deletes tosca data deep element belonging to tosca element specified by uid according label - * - * @param toscaElementUid - * @param edgeLabel - * @param vertexLabel - * @param uniqueKey - * @param pathKeys - * @param mapKeyField - * @return - */ - public StorageOperationStatus deleteToscaDataDeepElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, String uniqueKey, List<String> pathKeys, JsonPresentationFields mapKeyField) { - - StorageOperationStatus statusRes = StorageOperationStatus.OK; - Either<GraphVertex, TitanOperationStatus> getToscaElementRes; - - getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); - if (getToscaElementRes.isRight()) { - TitanOperationStatus status = getToscaElementRes.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get tosca element {} upon adding the properties. Status is {}. ", toscaElementUid, status); - statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - if (statusRes == StorageOperationStatus.OK) { - statusRes = deleteToscaDataDeepElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, uniqueKey, pathKeys, mapKeyField); - } - return statusRes; - - } - - /** - * Deletes tosca data deep element belonging to tosca element according label - * - * @param toscaElement - * @param edgeLabel - * @param vertexLabel - * @param uniqueKey - * @param pathKeys - * @param mapKeyField - * @return - */ - public StorageOperationStatus deleteToscaDataDeepElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, String uniqueKey, List<String> pathKeys, JsonPresentationFields mapKeyField) { - - List<String> uniqueKeys = new ArrayList<>(); - uniqueKeys.add(uniqueKey); - return deleteToscaDataDeepElements(toscaElement, edgeLabel, vertexLabel, uniqueKeys, pathKeys, mapKeyField); - } - - public StorageOperationStatus deleteToscaDataDeepElements(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<String> uniqueKeys, List<String> pathKeys, JsonPresentationFields mapKeyField) { - - StorageOperationStatus result = null; - GraphVertex toscaDataVertex; - Map<String, ToscaDataDefinition> existingToscaDataMap = null; - Either<GraphVertex, TitanOperationStatus> toscaDataVertexRes = titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson); - if (toscaDataVertexRes.isRight()) { - TitanOperationStatus status = toscaDataVertexRes.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get child vertex of the tosca element {} by label {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel, status); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(toscaDataVertexRes.right().value()); - } - if (result == null) { - toscaDataVertex = toscaDataVertexRes.left().value(); - existingToscaDataMap = getDeepElements(toscaDataVertexRes.left().value(), pathKeys); - result = deleteElementsFromDataVertex(toscaElement, edgeLabel, uniqueKeys, toscaDataVertex, existingToscaDataMap); - } - if (result == null) { - result = StorageOperationStatus.OK; - } - return result; - } - - private StorageOperationStatus deleteElementsFromDataVertex(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, List<String> uniqueKeys, GraphVertex toscaDataVertex, Map<String, ToscaDataDefinition> existingToscaDataMap) { - StorageOperationStatus result; - for (String uniqueKey : uniqueKeys) { - result = removeKeyFromDataVertex(uniqueKey, existingToscaDataMap); - if (result != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete tosca data element of the tosca element {} by label {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel, result); - break; - } - } - result = updateToscaDataElement(toscaElement, edgeLabel, toscaDataVertex); - return result; - } - - /** - * Deletes tosca data element belonging to tosca element according label - * - * @param toscaElement - * @param edgeLabel - * @param vertexLabel - * @param uniqueKey - * @param mapKeyField - * @return - */ - public StorageOperationStatus deleteToscaDataElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, String uniqueKey, JsonPresentationFields mapKeyField) { - - List<String> uniqueKeys = new ArrayList<>(); - uniqueKeys.add(uniqueKey); - return deleteToscaDataElements(toscaElement, edgeLabel, uniqueKeys); - } - - @SuppressWarnings("unchecked") + private static final String FAILED_REMOVE_TOSCA_DATA_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS = "Failed remove tosca data vertex of the tosca element {} by label {}. Status is {}. "; + private static final String FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS = "Failed to get child vertex of the tosca element {} by label {}. Status is {}. "; + private static final String FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS = "Failed to get tosca element {} upon adding the properties. Status is {}. "; + private static final Logger log = Logger.getLogger(BaseOperation.class.getName()); + public static final String VF_MODULE = "org.openecomp.groups.VfModule"; + + @Autowired + protected TitanDao titanDao; + + @Autowired + protected NodeTypeOperation nodeTypeOperation; + + @Autowired + protected TopologyTemplateOperation topologyTemplateOperation; + + public void setTitanDao(TitanDao titanDao) { + this.titanDao = titanDao; + } + /** + * Returns reference to appropriate toscaTemplateOperation + * + * @param componentType + * @return + */ + public ToscaElementOperation getToscaElementOperation(ComponentTypeEnum componentType) { + ToscaElementOperation operation; + switch (componentType) { + case SERVICE: + case RESOURCE: + operation = topologyTemplateOperation; + break; + default: + operation = nodeTypeOperation; + break; + } + return operation; + } + + /** + * Returns reference to appropriate toscaTemplateOperation + * + * @param toscaElementType + * @return + */ + public ToscaElementOperation getToscaElementOperation(ToscaElementTypeEnum toscaElementType) { + ToscaElementOperation operation; + switch (toscaElementType) { + case TOPOLOGY_TEMPLATE: + operation = topologyTemplateOperation; + break; + case NODE_TYPE: + operation = nodeTypeOperation; + break; + default: + operation = null; + break; + } + return operation; + } + + /** + * Returns reference to appropriate toscaTemplateOperation + * + * @param toscaElementType + * @return + */ + public ToscaElementOperation getToscaElementOperation(VertexTypeEnum toscaElementType) { + ToscaElementOperation operation; + switch (toscaElementType) { + case TOPOLOGY_TEMPLATE: + operation = topologyTemplateOperation; + break; + case NODE_TYPE: + operation = nodeTypeOperation; + break; + default: + operation = null; + break; + } + return operation; + } + /** + * Converts received vertex to User object + * + * @param ownerV + * @return + */ + public User convertToUser(Vertex ownerV) { + User owner = new User(); + owner.setUserId((String) ownerV.property(GraphPropertyEnum.USERID.getProperty()).value()); + VertexProperty<Object> property = ownerV.property(GraphPropertyEnum.ROLE.getProperty()); + if(property != null && property.isPresent() ){ + owner.setRole((String) property.value()); + } + + property = ownerV.property(GraphPropertyEnum.FIRST_NAME.getProperty()); + if(property != null && property.isPresent() ){ + owner.setFirstName((String) ownerV.property(GraphPropertyEnum.FIRST_NAME.getProperty()).value()); + } + + property = ownerV.property(GraphPropertyEnum.LAST_NAME.getProperty()); + if( property != null && property.isPresent() ){ + owner.setLastName((String) ownerV.property(GraphPropertyEnum.LAST_NAME.getProperty()).value()); + } + + property = ownerV.property(GraphPropertyEnum.EMAIL.getProperty()); + if( property != null && property.isPresent() ){ + owner.setEmail((String) ownerV.property(GraphPropertyEnum.EMAIL.getProperty()).value()); + } + + property = ownerV.property(GraphPropertyEnum.LAST_LOGIN_TIME.getProperty()); + if( property != null && property.isPresent() ){ + owner.setLastLoginTime((Long) ownerV.property(GraphPropertyEnum.LAST_LOGIN_TIME.getProperty()).value()); + } + return owner; + } + + protected <T extends ToscaDataDefinition> Either<Map<String, T>, TitanOperationStatus> getDataFromGraph(GraphVertex componentV, EdgeLabelEnum edgelabel) { + Either<Pair<GraphVertex, Map<String, T>>, TitanOperationStatus> dataVertex = getDataAndVertexFromGraph(componentV, edgelabel); + if (dataVertex.isRight()) { + return Either.right(dataVertex.right().value()); + } + Map<String, T> properties = dataVertex.left().value().getRight(); + return Either.left(properties); + } + + @SuppressWarnings("unchecked") + protected <T extends ToscaDataDefinition> Either<Pair<GraphVertex, Map<String, T>>, TitanOperationStatus> getDataAndVertexFromGraph(GraphVertex componentV, EdgeLabelEnum edgelabel) { + Either<GraphVertex, TitanOperationStatus> dataVertex = getDataVertex(componentV, edgelabel); + if (dataVertex.isRight()) { + return Either.right(dataVertex.right().value()); + } + GraphVertex propV = dataVertex.left().value(); + Map<String, T> properties = (Map<String, T>) propV.getJson(); + Pair<GraphVertex, Map<String, T>> pair = new ImmutablePair<>(propV, properties); + return Either.left(pair); + } + + protected <T extends ToscaDataDefinition> Either<GraphVertex, TitanOperationStatus> getDataVertex(GraphVertex componentV, EdgeLabelEnum edgelabel) { + Either<GraphVertex, TitanOperationStatus> childVertex = titanDao.getChildVertex(componentV, edgelabel, JsonParseFlagEnum.ParseJson); + if (childVertex.isRight()) { + if (childVertex.right().value() != TitanOperationStatus.NOT_FOUND) { + log.debug("failed to fetch {} for tosca element with id {}, error {}", edgelabel, componentV.getUniqueId(), childVertex.right().value()); + } + return Either.right(childVertex.right().value()); + } + GraphVertex propV = childVertex.left().value(); + return Either.left(propV); + } + + /** + * Returns tosca data belonging to tosca element specified by uid according received label + * + * @param toscaElementUid + * @param edgelabel + * @return + */ + public <T extends ToscaDataDefinition> Either<Map<String, T>, TitanOperationStatus> getDataFromGraph(String toscaElementUid, EdgeLabelEnum edgelabel) { + + Either<Map<String, T>, TitanOperationStatus> result = null; + Either<GraphVertex, TitanOperationStatus> getToscaElementRes; + + getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); + if (getToscaElementRes.isRight()) { + TitanOperationStatus status = getToscaElementRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get tosca element {} upon getting tosca data from graph. Status is {}. ", toscaElementUid, status); + result = Either.right(status); + } + if (result == null) { + result = getDataFromGraph(getToscaElementRes.left().value(), edgelabel); + } + return result; + } + + public Either<GraphVertex, TitanOperationStatus> findUserVertex(String userId) { + return titanDao.getVertexByPropertyAndLabel(GraphPropertyEnum.USERID, userId, VertexTypeEnum.USER, JsonParseFlagEnum.NoParse); + } + + /** + * + * @param elemementId + * @param label + * @return + */ + public Either<Boolean, StorageOperationStatus> isCloneNeeded(String elemementId, EdgeLabelEnum label) { + Either<GraphVertex, TitanOperationStatus> vertexById = titanDao.getVertexById(elemementId); + if (vertexById.isRight()) { + log.debug("Failed to fetch element by id {} error {}", elemementId, vertexById.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexById.right().value())); + } + GraphVertex toscaElementVertex = vertexById.left().value(); + Either<GraphVertex, TitanOperationStatus> childVertex = titanDao.getChildVertex(toscaElementVertex, label, JsonParseFlagEnum.NoParse); + if (childVertex.isRight()) { + if (childVertex.right().value() != TitanOperationStatus.NOT_FOUND) { + log.debug("failed to fetch {} for tosca element with id {}, error {}", label, toscaElementVertex.getUniqueId(), childVertex.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(childVertex.right().value())); + } + return Either.left(Boolean.FALSE); + } + GraphVertex dataVertex = childVertex.left().value(); + Iterator<Edge> edges = dataVertex.getVertex().edges(Direction.IN, label.name()); + int edgeCount = 0; + while (edges.hasNext()) { + edges.next(); + ++edgeCount; + } + if (edgeCount > 1) { + return Either.left(Boolean.TRUE); + } else { + return Either.left(Boolean.FALSE); + } + } + + protected Either<GraphVertex, TitanOperationStatus> updateOrCopyOnUpdate(GraphVertex dataVertex, GraphVertex toscaElementVertex, EdgeLabelEnum label) { + Iterator<Edge> edges = dataVertex.getVertex().edges(Direction.IN, label.name()); + int edgeCount = 0; + Edge edgeToRemove = null; + while (edges.hasNext()) { + Edge edge = edges.next(); + ++edgeCount; + Vertex outVertex = edge.outVertex(); + String outId = (String) titanDao.getProperty((TitanVertex) outVertex, GraphPropertyEnum.UNIQUE_ID.getProperty()); + if (toscaElementVertex.getUniqueId().equals(outId)) { + edgeToRemove = edge; + } + } + if (edgeToRemove == null) { + log.debug("No edges {} from vertex {} to vertex {}", label, toscaElementVertex.getUniqueId(), dataVertex.getUniqueId()); + return Either.right(TitanOperationStatus.GENERAL_ERROR); + } + switch (edgeCount) { + case 0: + // error + log.debug("No edges {} to vertex {}", label, dataVertex.getUniqueId()); + return Either.right(TitanOperationStatus.GENERAL_ERROR); + case 1: + // update + log.trace("Only one edge {} to vertex {}. Update vertex", label, dataVertex.getUniqueId()); + return titanDao.updateVertex(dataVertex); + default: + // copy on update + log.trace("More than one edge {} to vertex {}. Need to clone vertex", label, dataVertex.getUniqueId()); + return cloneDataVertex(dataVertex, toscaElementVertex, label, edgeToRemove); + } + } + + private Either<GraphVertex, TitanOperationStatus> cloneDataVertex(GraphVertex dataVertex, GraphVertex toscaElementVertex, EdgeLabelEnum label, Edge edgeToRemove) { + GraphVertex newDataVertex = new GraphVertex(dataVertex.getLabel()); + String id = IdBuilderUtils.generateChildId(toscaElementVertex.getUniqueId(), dataVertex.getLabel()); + newDataVertex.cloneData(dataVertex); + newDataVertex.setUniqueId(id); + + Either<GraphVertex, TitanOperationStatus> createVertex = titanDao.createVertex(newDataVertex); + if (createVertex.isRight()) { + log.debug("Failed to clone data vertex for {} error {}", dataVertex.getUniqueId(), createVertex.right().value()); + return createVertex; + } + newDataVertex = createVertex.left().value(); + TitanOperationStatus createEdge = titanDao.createEdge(toscaElementVertex, newDataVertex, label, titanDao.getEdgeProperties(edgeToRemove)); + if (createEdge != TitanOperationStatus.OK) { + log.debug("Failed to associate vertex {} to vertex {}, error {}", toscaElementVertex.getUniqueId(), newDataVertex.getUniqueId(), createEdge); + return Either.right(createEdge); + } + edgeToRemove.remove(); + return Either.left(newDataVertex); + } + + public Either<GraphVertex, StorageOperationStatus> associateElementToData(GraphVertex element, VertexTypeEnum vertexLabel, EdgeLabelEnum edgeLabel, Map<String, ? extends ToscaDataDefinition> data) { + GraphVertex dataV = new GraphVertex(vertexLabel); + String id = IdBuilderUtils.generateChildId(element.getUniqueId(), vertexLabel); + dataV.setUniqueId(id); + dataV.setJson(data); + Either<GraphVertex, TitanOperationStatus> createVertex = titanDao.createVertex(dataV); + if (createVertex.isRight()) { + log.trace("Failed to create {} vertex for type node {}", vertexLabel, element.getUniqueId()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createVertex.right().value())); + } + dataV = createVertex.left().value(); + TitanOperationStatus createEdgeStatus = titanDao.createEdge(element.getVertex(), dataV.getVertex(), edgeLabel, new HashMap<>()); + if (createEdgeStatus != TitanOperationStatus.OK) { + log.trace("Failed to create {} vertex for type node {}", vertexLabel, element.getUniqueId()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createEdgeStatus)); + } + return Either.left(dataV); + } + + /** + * Adds tosca data element to tosca element according received labels + * + * @param toscaElement + * @param edgeLabel + * @param vertexLabel + * @param toscaData + * @param mapKeyField + * @return + */ + public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, JsonPresentationFields mapKeyField) { + + List<T> toscaDataList = new ArrayList<>(); + toscaDataList.add(toscaData); + return addToscaDataToToscaElement(toscaElement, edgeLabel, vertexLabel, toscaDataList, mapKeyField); + } + + /** + * Adds tosca data deep element to tosca element according received labels + * + * @param toscaElement + * @param edgeLabel + * @param vertexLabel + * @param toscaData + * @param pathKeys + * @param mapKeyField + * @return + */ + public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataDeepElementToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, List<String> pathKeys, + JsonPresentationFields mapKeyField) { + + List<T> toscaDataList = new ArrayList<>(); + toscaDataList.add(toscaData); + return addToscaDataDeepElementsToToscaElement(toscaElement, edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField); + } + + /** + * Converts recieved map of tosca data deep elements to list and adds it to tosca element according received labels + * + * @param toscaElement + * @param edgeLabel + * @param vertexLabel + * @param toscaDataMap + * @param pathKeys + * @param mapKeyField + * @return + */ + public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataDeepElementsToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, Map<String, T> toscaDataMap, List<String> pathKeys, + JsonPresentationFields mapKeyField) { + + if (toscaDataMap != null) { + return addToscaDataDeepElementsToToscaElement(toscaElement, edgeLabel, vertexLabel, toscaDataMap.values().stream().collect(Collectors.toList()), pathKeys, mapKeyField); + } + return StorageOperationStatus.OK; + } + + /** + * Adds list of tosca data deep elements to tosca element according received labels + * + * @param toscaElement + * @param edgeLabel + * @param vertexLabel + * @param toscaDataList + * @param pathKeys + * @param mapKeyField + * @return + */ + public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataDeepElementsToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<T> toscaDataList, List<String> pathKeys, + JsonPresentationFields mapKeyField) { + + return updateOrAddToscaDataDeepElement(toscaElement, edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField, false); + } + + /** + * Updates list of tosca data elements of tosca element according received labels + * + * @param toscaElement + * @param edgeLabel + * @param vertexLabel + * @param toscaData + * @param mapKeyField + * @return + */ + public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataOfToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, JsonPresentationFields mapKeyField) { + List<T> toscaDataList = new ArrayList<>(); + toscaDataList.add(toscaData); + return updateToscaDataOfToscaElement(toscaElement, edgeLabel, vertexLabel, toscaDataList, mapKeyField); + } + + /** + * Updates tosca data deep element of tosca element according received labels + * + * @param toscaElement + * @param edgeLabel + * @param vertexLabel + * @param toscaData + * @param pathKeys + * @param mapKeyField + * @return + */ + public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataDeepElementOfToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, List<String> pathKeys, + JsonPresentationFields mapKeyField) { + List<T> toscaDataList = new ArrayList<>(); + toscaDataList.add(toscaData); + return updateToscaDataDeepElementsOfToscaElement(toscaElement, edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField); + } + + /** + * Updates tosca data deep elements of tosca element according received labels + * + * @param toscaElement + * @param edgeLabel + * @param vertexLabel + * @param toscaDataList + * @param pathKeys + * @param mapKeyField + * @return + */ + public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataDeepElementsOfToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<T> toscaDataList, List<String> pathKeys, + JsonPresentationFields mapKeyField) { + + return updateOrAddToscaDataDeepElement(toscaElement, edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField, true); + } + + /** + * Adds tosca data element to tosca element with specified uid according received labels + * + * @param toscaElementUid + * @param toscaData + * @param edgeLabel + * @param vertexLabel + * @param mapKeyField + * @return + */ + public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataToToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, JsonPresentationFields mapKeyField) { + + List<T> toscaDataList = new ArrayList<>(); + toscaDataList.add(toscaData); + return addToscaDataToToscaElement(toscaElementUid, edgeLabel, vertexLabel, toscaDataList, mapKeyField); + } + + /** + * Adds tosca data deep element to tosca element with specified uid according received labels + * + * @param toscaElementUid + * @param edgeLabel + * @param vertexLabel + * @param toscaData + * @param pathKeys + * @param mapKeyField + * @return + */ + public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataDeepElementToToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, List<String> pathKeys, + JsonPresentationFields mapKeyField) { + + List<T> toscaDataList = new ArrayList<>(); + toscaDataList.add(toscaData); + return addToscaDataDeepElementsToToscaElement(toscaElementUid, edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField); + } + + public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataDeepElementOfToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, List<String> pathKeys, + JsonPresentationFields mapKeyField) { + + List<T> toscaDataList = new ArrayList<>(); + toscaDataList.add(toscaData); + return updateToscaDataDeepElementsOfToscaElement(toscaElementUid, edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField); + } + + public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataDeepElementsOfToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<T> toscaDataList, List<String> pathKeys, + JsonPresentationFields mapKeyField) { + + StorageOperationStatus statusRes = null; + Either<GraphVertex, TitanOperationStatus> getToscaElementRes; + + getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); + if (getToscaElementRes.isRight()) { + TitanOperationStatus status = getToscaElementRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status); + statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status); + } + if (statusRes == null && CollectionUtils.isNotEmpty(toscaDataList)) { + statusRes = updateToscaDataDeepElementsOfToscaElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField); + } + if (statusRes == null) { + statusRes = StorageOperationStatus.OK; + } + 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 + * + * @param toscaElementUid + * @param edgeLabel + * @param vertexLabel + * @param toscaDataList + * @param pathKeys + * @param mapKeyField + * @return + */ + public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataDeepElementsToToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<T> toscaDataList, List<String> pathKeys, + JsonPresentationFields mapKeyField) { + + StorageOperationStatus statusRes = null; + Either<GraphVertex, TitanOperationStatus> getToscaElementRes; + + getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); + if (getToscaElementRes.isRight()) { + TitanOperationStatus status = getToscaElementRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status); + statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status); + } + if (statusRes == null && CollectionUtils.isNotEmpty(toscaDataList)) { + statusRes = addToscaDataDeepElementsToToscaElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, toscaDataList, pathKeys, mapKeyField); + } + if (statusRes == null) { + statusRes = StorageOperationStatus.OK; + } + return statusRes; + } + + public <T extends ToscaDataDefinition> StorageOperationStatus deleteToscaDataDeepElementsBlockOfToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, String key) { + + StorageOperationStatus statusRes = null; + Either<GraphVertex, TitanOperationStatus> getToscaElementRes; + + getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); + if (getToscaElementRes.isRight()) { + TitanOperationStatus status = getToscaElementRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status); + statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status); + } + if (statusRes == null) { + statusRes = deleteToscaDataDeepElementsBlockToToscaElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, key); + } + if (statusRes == null) { + statusRes = StorageOperationStatus.OK; + } + return statusRes; + } + + public <T extends ToscaDataDefinition> StorageOperationStatus deleteToscaDataDeepElementsBlockToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, String key) { + + StorageOperationStatus result = null; + GraphVertex toscaDataVertex = null; + Either<GraphVertex, TitanOperationStatus> toscaDataVertexRes = titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson); + if (toscaDataVertexRes.isRight()) { + TitanOperationStatus status = toscaDataVertexRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, status); + result = DaoStatusConverter.convertTitanStatusToStorageStatus(toscaDataVertexRes.right().value()); + } + if (result == null) { + toscaDataVertex = toscaDataVertexRes.left().value(); + result = deleteDeepElementsBlock(toscaDataVertex, key); + } + if (result == null) { + Either<GraphVertex, TitanOperationStatus> updateOrCopyRes = updateOrCopyOnUpdate(toscaDataVertex, toscaElement, edgeLabel); + if (updateOrCopyRes.isRight()) { + TitanOperationStatus status = updateOrCopyRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete tosca data block {} from the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), status); + result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); + } + } + if (result == null) { + result = StorageOperationStatus.OK; + } + return result; + } + + @SuppressWarnings("rawtypes") + public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataDeepElementsBlockToToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, MapDataDefinition toscaDataMap, String key) { + + StorageOperationStatus statusRes = null; + Either<GraphVertex, TitanOperationStatus> getToscaElementRes; + + getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); + if (getToscaElementRes.isRight()) { + TitanOperationStatus status = getToscaElementRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status); + statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status); + } + if (statusRes == null && toscaDataMap != null) { + statusRes = addToscaDataDeepElementsBlockToToscaElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, toscaDataMap, key); + } + if (statusRes == null) { + statusRes = StorageOperationStatus.OK; + } + return statusRes; + } + + @SuppressWarnings("rawtypes") + public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataDeepElementsBlockToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, MapDataDefinition toscaDataMap, String key) { + + StorageOperationStatus result = null; + GraphVertex toscaDataVertex = null; + Either<GraphVertex, TitanOperationStatus> toscaDataVertexRes = titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson); + if (toscaDataVertexRes.isRight() && toscaDataVertexRes.right().value() != TitanOperationStatus.NOT_FOUND) { + TitanOperationStatus status = toscaDataVertexRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, status); + result = DaoStatusConverter.convertTitanStatusToStorageStatus(toscaDataVertexRes.right().value()); + } + if (result == null && toscaDataVertexRes.isLeft()) { + toscaDataVertex = toscaDataVertexRes.left().value(); + result = addDeepElementsBlock(toscaDataVertex, toscaDataMap, key); + + } + if (result == null) { + if (toscaDataVertex != null) { + Either<GraphVertex, TitanOperationStatus> updateOrCopyRes = updateOrCopyOnUpdate(toscaDataVertex, toscaElement, edgeLabel); + if (updateOrCopyRes.isRight()) { + TitanOperationStatus status = updateOrCopyRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add tosca data {} to the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), status); + result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); + } + } else { + Map<String, MapDataDefinition> data = new HashMap<>(); + data.put(key, toscaDataMap); + Either<GraphVertex, StorageOperationStatus> createRes = associateElementToData(toscaElement, vertexLabel, edgeLabel, data); + if (createRes.isRight()) { + StorageOperationStatus status = createRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to assosiate tosca data {} of the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), status); + result = status; + } + } + } + if (result == null) { + result = StorageOperationStatus.OK; + } + return result; + } + + /** + * + * @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 + * @param edgeLabel + * @param vertexLabel + * @param toscaData + * @param mapKeyField + * @return + */ + public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataOfToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, T toscaData, JsonPresentationFields mapKeyField) { + + List<T> toscaDataList = new ArrayList<>(); + toscaDataList.add(toscaData); + return updateToscaDataOfToscaElement(toscaElementUid, edgeLabel, vertexLabel, toscaDataList, mapKeyField); + } + + /** + * Updates list of tosca data elements belonging to tosca element with specified uid according received labels + * + * @param toscaElementUid + * @param edgeLabel + * @param vertexLabel + * @param toscaDataList + * @param mapKeyField + * @return + */ + public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataOfToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<T> toscaDataList, JsonPresentationFields mapKeyField) { + + StorageOperationStatus statusRes = null; + Either<GraphVertex, TitanOperationStatus> getToscaElementRes; + + getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); + if (getToscaElementRes.isRight()) { + TitanOperationStatus status = getToscaElementRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status); + statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status); + } + if (statusRes == null && CollectionUtils.isNotEmpty(toscaDataList)) { + statusRes = updateToscaDataOfToscaElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, toscaDataList, mapKeyField); + } + if (statusRes == null) { + statusRes = StorageOperationStatus.OK; + } + return statusRes; + } + + /** + * Adds list of tosca data elements to tosca element with specified uid according received labels + * + * @param toscaElementUid + * @param edgeLabel + * @param vertexLabel + * @param toscaDataList + * @param mapKeyField + * @return + */ + public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataToToscaElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<T> toscaDataList, JsonPresentationFields mapKeyField) { + + StorageOperationStatus statusRes = null; + Either<GraphVertex, TitanOperationStatus> getToscaElementRes; + + getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); + if (getToscaElementRes.isRight()) { + TitanOperationStatus status = getToscaElementRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status); + statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status); + } + if (statusRes == null && CollectionUtils.isNotEmpty(toscaDataList)) { + statusRes = addToscaDataToToscaElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, toscaDataList, mapKeyField); + } + if (statusRes == null) { + statusRes = StorageOperationStatus.OK; + } + return statusRes; + } + + /** + * Converts recieved map of tosca data elements to list and adds it to tosca element according received labels + * + * @param toscaElement + * @param edgeLabel + * @param vertexLabel + * @param toscaDataMap + * @param mapKeyField + * @return + */ + public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, Map<String, T> toscaDataMap, JsonPresentationFields mapKeyField) { + + return addToscaDataToToscaElement(toscaElement, edgeLabel, vertexLabel, toscaDataMap.values().stream().collect(Collectors.toList()), mapKeyField); + } + + /** + * Adds list of tosca data elements to tosca element according received labels + * + * @param toscaElement + * @param edgeLabel + * @param vertexLabel + * @param toscaDataList + * @param mapKeyField + * @return + */ + public <T extends ToscaDataDefinition> StorageOperationStatus addToscaDataToToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<T> toscaDataList, JsonPresentationFields mapKeyField) { + + return updateOrAddToscaData(toscaElement, edgeLabel, vertexLabel, toscaDataList, mapKeyField, false); + } + + /** + * Updates list of tosca data elements belonging to tosca element according received labels + * + * @param toscaElement + * @param edgeLabel + * @param vertexLabel + * @param toscaDataList + * @param mapKeyField + * @return + */ + public <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataOfToscaElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<T> toscaDataList, JsonPresentationFields mapKeyField) { + + return updateOrAddToscaData(toscaElement, edgeLabel, vertexLabel, toscaDataList, mapKeyField, true); + } + + public boolean hasEdgeOfType(GraphVertex toscaElement, EdgeLabelEnum edgeLabel) { + Either<GraphVertex, TitanOperationStatus> vertex = titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson); + return vertex.isLeft(); + } + + @SuppressWarnings("unchecked") + private <T extends ToscaDataDefinition> StorageOperationStatus updateOrAddToscaData(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<T> toscaDataList, JsonPresentationFields mapKeyField, boolean isUpdate) { + StorageOperationStatus result = null; + GraphVertex toscaDataVertex = null; + Map<String, T> existingToscaDataMap = null; + Either<Map<String, T>, StorageOperationStatus> validateRes = null; + Map<String, T> mergedToscaDataMap; + Either<GraphVertex, TitanOperationStatus> toscaDataVertexRes = titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson); + if (toscaDataVertexRes.isRight() && toscaDataVertexRes.right().value() != TitanOperationStatus.NOT_FOUND) { + TitanOperationStatus status = toscaDataVertexRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, status); + result = DaoStatusConverter.convertTitanStatusToStorageStatus(toscaDataVertexRes.right().value()); + } + if (result == null) { + if (toscaDataVertexRes.isLeft()) { + toscaDataVertex = toscaDataVertexRes.left().value(); + existingToscaDataMap = (Map<String, T>) toscaDataVertex.getJson(); + } + + validateRes = validateMergeToscaData(toscaElement, toscaDataList, mapKeyField, existingToscaDataMap, isUpdate); + if (validateRes.isRight()) { + result = validateRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed validate tosca data upon adding to tosca element {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel, result); + } + } + if (result == null) { + mergedToscaDataMap = validateRes.left().value(); + result = handleToscaData(toscaElement, vertexLabel, edgeLabel, toscaDataVertex, mergedToscaDataMap); + } + if (result == null) { + result = StorageOperationStatus.OK; + } + return result; + + } + + @SuppressWarnings("unchecked") + public <T extends ToscaDataDefinition> StorageOperationStatus updateFullToscaData(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, Map<String, T> toscaData) { + StorageOperationStatus result = null; + GraphVertex toscaDataVertex = null; + Map<String, T> existingToscaDataMap = null; + + Either<GraphVertex, TitanOperationStatus> toscaDataVertexRes = titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson); + if (toscaDataVertexRes.isRight() && toscaDataVertexRes.right().value() != TitanOperationStatus.NOT_FOUND) { + TitanOperationStatus status = toscaDataVertexRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, status); + result = DaoStatusConverter.convertTitanStatusToStorageStatus(toscaDataVertexRes.right().value()); + } + if (result == null) { + if (toscaDataVertexRes.isLeft()) { + toscaDataVertex = toscaDataVertexRes.left().value(); + existingToscaDataMap = (Map<String, T>) toscaDataVertex.getJson(); + } + + + } + if (result == null) { + + result = handleToscaData(toscaElement, vertexLabel, edgeLabel, toscaDataVertex, toscaData); + } + if (result == null) { + result = StorageOperationStatus.OK; + } + return result; + + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + private <T, K extends ToscaDataDefinition> StorageOperationStatus updateOrAddToscaDataDeepElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<K> toscaDataList, List<String> pathKeys, + JsonPresentationFields mapKeyField, boolean isUpdate) { + + StorageOperationStatus result = null; + GraphVertex toscaDataVertex = null; + Map<String, K> existingDeepElementsMap = null; + Either<Map<String, K>, StorageOperationStatus> validateRes = null; + Either<GraphVertex, TitanOperationStatus> toscaDataVertexRes = titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson); + if (toscaDataVertexRes.isRight() && toscaDataVertexRes.right().value() != TitanOperationStatus.NOT_FOUND) { + TitanOperationStatus status = toscaDataVertexRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, status); + result = DaoStatusConverter.convertTitanStatusToStorageStatus(toscaDataVertexRes.right().value()); + } + if (result == null) { + if (toscaDataVertexRes.isLeft()) { + toscaDataVertex = toscaDataVertexRes.left().value(); + existingDeepElementsMap = getDeepElements(toscaDataVertex, pathKeys); + } + validateRes = validateMergeToscaData(toscaElement, toscaDataList, mapKeyField, existingDeepElementsMap, isUpdate); + if (validateRes.isRight()) { + result = validateRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed validate tosca data upon adding to tosca element {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel, result); + } + } + if (result == null) { + updateDeepElements(toscaDataVertex, validateRes.left().value(), pathKeys); + Map<String, K> toscaDataToHandle; + if(toscaDataVertex == null){ + toscaDataToHandle = new HashMap<>(); + Map<String, K> currMap = toscaDataToHandle; + for (int i = 1; i < pathKeys.size()-1; ++i) { + currMap.put(pathKeys.get(i), (K) new MapDataDefinition()); + currMap = (Map<String, K>) ((MapDataDefinition) currMap).getMapToscaDataDefinition().get(pathKeys.get(i)); + } + toscaDataToHandle.put(pathKeys.get(pathKeys.size()-1), (K) new MapDataDefinition(validateRes.left().value())); + + } else { + toscaDataToHandle = (Map<String, K>) toscaDataVertex.getJson(); + } + result = handleToscaData(toscaElement, vertexLabel, edgeLabel, toscaDataVertex, toscaDataToHandle); + } + if (result == null) { + result = StorageOperationStatus.OK; + } + return result; + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + private <T, K extends ToscaDataDefinition> void updateDeepElements(GraphVertex toscaDataVertex, Map<String, K> mergedDeepElementMap, List<String> pathKeys) { + + if (toscaDataVertex != null && MapUtils.isNotEmpty(mergedDeepElementMap)) { + Map<String, MapDataDefinition> currMap = (Map<String, MapDataDefinition>) toscaDataVertex.getJson(); + if(!currMap.containsKey(pathKeys.get(0))){ + currMap.put(pathKeys.get(0), new MapDataDefinition<>()); + } + MapDataDefinition currDeepElement = currMap.get(pathKeys.get(0)); + + for (int i = 1; i < pathKeys.size(); ++i) { + if(currDeepElement.findByKey(pathKeys.get(i)) == null){ + currDeepElement.put(pathKeys.get(i), new MapDataDefinition<>()); + } + currDeepElement = (MapDataDefinition) currDeepElement.findByKey(pathKeys.get(i)); + } + if(currDeepElement != null){ + for (Map.Entry<String, K> elementEntry : mergedDeepElementMap.entrySet()) { + currDeepElement.put(elementEntry.getKey(), elementEntry.getValue()); + } + } + } + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private <T, K extends ToscaDataDefinition> Map<String, K> getDeepElements(GraphVertex toscaDataVertex, List<String> pathKeys) { + Map<String, K> result = null; + Map<String, T> currMap = (Map<String, T>) toscaDataVertex.getJson(); + MapDataDefinition currDeepElement = (MapDataDefinition) currMap.get(pathKeys.get(0)); + for (int i = 1; i < pathKeys.size(); ++i) { + currDeepElement = (MapDataDefinition) currDeepElement.findByKey(pathKeys.get(i)); + } + if(currDeepElement != null){ + result = (Map<String, K>) currDeepElement.getMapToscaDataDefinition(); + } + return result; + } + + @SuppressWarnings("unchecked") + private <T extends ToscaDataDefinition> StorageOperationStatus addDeepElementsBlock(GraphVertex toscaDataVertex, T toscaDataBlock, String key) { + + StorageOperationStatus result = null; + Map<String, T> currMap = (Map<String, T>) toscaDataVertex.getJson(); + if (currMap.containsKey(key)) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add block of deep tosca data elements by label {}." + " The block element with the same key {} already exists. ", toscaDataVertex.getLabel(), key); + result = StorageOperationStatus.ENTITY_ALREADY_EXISTS; + } + if (result == null) { + currMap.put(key, toscaDataBlock); + } + return result; + } + + @SuppressWarnings("unchecked") + private <T extends ToscaDataDefinition> StorageOperationStatus deleteDeepElementsBlock(GraphVertex toscaDataVertex, String key) { + + StorageOperationStatus result = null; + Map<String, T> currMap = (Map<String, T>) toscaDataVertex.getJson(); + if (!currMap.containsKey(key)) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete block of deep tosca data elements by label {}." + " The block element with the same key {} doesn't exist. ", toscaDataVertex.getLabel(), key); + result = StorageOperationStatus.NOT_FOUND; + } + if (result == null) { + currMap.remove(key); + } + return null; + } + + /** + * Removes tosca data vertex belonging to tosca element specified by uid according label + * + * @param toscaElementUid + * @param edgeLabel + * @param vertexLabel + * @return + */ + public StorageOperationStatus removeToscaData(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel) { + + StorageOperationStatus statusRes = StorageOperationStatus.OK; + Either<GraphVertex, TitanOperationStatus> getToscaElementRes; + + getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); + if (getToscaElementRes.isRight()) { + TitanOperationStatus status = getToscaElementRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status); + statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status); + } + if (statusRes == StorageOperationStatus.OK) { + statusRes = removeToscaDataVertex(getToscaElementRes.left().value(), edgeLabel, vertexLabel); + } + return statusRes; + } + + /** + * Removes tosca data vertex belonging to tosca element according label + * + * @param toscaElement + * @param edgeLabel + * @param vertexLabel + * @return + */ + public StorageOperationStatus removeToscaDataVertex(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel) { + StorageOperationStatus result = null; + GraphVertex toscaDataVertex = null; + Iterator<Edge> edges = null; + int edgeCounter = 0; + Edge edge = null; + Edge edgeToDelete = null; + Either<GraphVertex, TitanOperationStatus> toscaDataVertexRes = titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson); + if (toscaDataVertexRes.isRight()) { + TitanOperationStatus status = toscaDataVertexRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_REMOVE_TOSCA_DATA_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, status); + result = DaoStatusConverter.convertTitanStatusToStorageStatus(toscaDataVertexRes.right().value()); + } + if (result == null) { + toscaDataVertex = toscaDataVertexRes.left().value(); + edges = toscaDataVertex.getVertex().edges(Direction.IN); + if (edges == null || !edges.hasNext()) { + result = StorageOperationStatus.NOT_FOUND; + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_REMOVE_TOSCA_DATA_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, result); + } + } + if (result == null) { + if (edges!=null) { + while (edges.hasNext()) { + ++edgeCounter; + edge = edges.next(); + if (edge.outVertex().id().equals(toscaElement.getVertex().id())) { + edgeToDelete = edge; + break; + } + } + } + if (edgeToDelete == null) { + result = StorageOperationStatus.NOT_FOUND; + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_REMOVE_TOSCA_DATA_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, result); + } + } + if (result == null) { + if (edgeCounter > 1 && edgeToDelete!=null) { + edgeToDelete.remove(); + } else { + toscaDataVertex.getVertex().remove(); + } + } + if (result == null) { + result = StorageOperationStatus.OK; + } + return result; + } + + /** + * Deletes tosca data elements belonging to tosca element specified by uid according label + * + * @param toscaElementUid + * @param edgeLabel + * @param uniqueKeys + * @return + */ + public StorageOperationStatus deleteToscaDataElements(String toscaElementUid, EdgeLabelEnum edgeLabel, List<String> uniqueKeys) { + + StorageOperationStatus statusRes = StorageOperationStatus.OK; + Either<GraphVertex, TitanOperationStatus> getToscaElementRes; + + getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); + if (getToscaElementRes.isRight()) { + TitanOperationStatus status = getToscaElementRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status); + statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status); + } + if (statusRes == StorageOperationStatus.OK) { + statusRes = deleteToscaDataElements(getToscaElementRes.left().value(), edgeLabel, uniqueKeys); + } + return statusRes; + } + + /** + * Deletes tosca data element belonging to tosca element specified by uid according label + * + * @param toscaElementUid + * @param edgeLabel + * @param vertexLabel + * @param uniqueKey + * @param mapKeyField + * @return + */ + public StorageOperationStatus deleteToscaDataElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, String uniqueKey, JsonPresentationFields mapKeyField) { + + StorageOperationStatus statusRes = StorageOperationStatus.OK; + Either<GraphVertex, TitanOperationStatus> getToscaElementRes; + + getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); + if (getToscaElementRes.isRight()) { + TitanOperationStatus status = getToscaElementRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status); + statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status); + } + if (statusRes == StorageOperationStatus.OK) { + statusRes = deleteToscaDataElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, uniqueKey, mapKeyField); + } + return statusRes; + + } + + /** + * Deletes tosca data deep element belonging to tosca element specified by uid according label + * + * @param toscaElementUid + * @param edgeLabel + * @param vertexLabel + * @param uniqueKey + * @param pathKeys + * @param mapKeyField + * @return + */ + public StorageOperationStatus deleteToscaDataDeepElement(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, String uniqueKey, List<String> pathKeys, JsonPresentationFields mapKeyField) { + + StorageOperationStatus statusRes = StorageOperationStatus.OK; + Either<GraphVertex, TitanOperationStatus> getToscaElementRes; + + getToscaElementRes = titanDao.getVertexById(toscaElementUid, JsonParseFlagEnum.NoParse); + if (getToscaElementRes.isRight()) { + TitanOperationStatus status = getToscaElementRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_TOSCA_ELEMENT_UPON_ADDING_THE_PROPERTIES_STATUS_IS, toscaElementUid, status); + statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status); + } + if (statusRes == StorageOperationStatus.OK) { + statusRes = deleteToscaDataDeepElement(getToscaElementRes.left().value(), edgeLabel, vertexLabel, uniqueKey, pathKeys, mapKeyField); + } + return statusRes; + + } + + /** + * Deletes tosca data deep element belonging to tosca element according label + * + * @param toscaElement + * @param edgeLabel + * @param vertexLabel + * @param uniqueKey + * @param pathKeys + * @param mapKeyField + * @return + */ + public StorageOperationStatus deleteToscaDataDeepElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, String uniqueKey, List<String> pathKeys, JsonPresentationFields mapKeyField) { + + List<String> uniqueKeys = new ArrayList<>(); + uniqueKeys.add(uniqueKey); + return deleteToscaDataDeepElements(toscaElement, edgeLabel, vertexLabel, uniqueKeys, pathKeys, mapKeyField); + } + + public StorageOperationStatus deleteToscaDataDeepElements(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<String> uniqueKeys, List<String> pathKeys, JsonPresentationFields mapKeyField) { + + StorageOperationStatus result = null; + GraphVertex toscaDataVertex; + Map<String, ToscaDataDefinition> existingToscaDataMap = null; + Either<GraphVertex, TitanOperationStatus> toscaDataVertexRes = titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson); + if (toscaDataVertexRes.isRight()) { + TitanOperationStatus status = toscaDataVertexRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, status); + result = DaoStatusConverter.convertTitanStatusToStorageStatus(toscaDataVertexRes.right().value()); + } + if (result == null) { + toscaDataVertex = toscaDataVertexRes.left().value(); + existingToscaDataMap = getDeepElements(toscaDataVertexRes.left().value(), pathKeys); + result = deleteElementsFromDataVertex(toscaElement, edgeLabel, uniqueKeys, toscaDataVertex, existingToscaDataMap); + } + if (result == null) { + result = StorageOperationStatus.OK; + } + return result; + } + + private StorageOperationStatus deleteElementsFromDataVertex(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, List<String> uniqueKeys, GraphVertex toscaDataVertex, Map<String, ToscaDataDefinition> existingToscaDataMap) { + StorageOperationStatus result; + for (String uniqueKey : uniqueKeys) { + result = removeKeyFromDataVertex(uniqueKey, existingToscaDataMap); + if (result != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete tosca data element of the tosca element {} by label {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel, result); + break; + } + } + result = updateToscaDataElement(toscaElement, edgeLabel, toscaDataVertex); + return result; + } + + /** + * Deletes tosca data element belonging to tosca element according label + * + * @param toscaElement + * @param edgeLabel + * @param vertexLabel + * @param uniqueKey + * @param mapKeyField + * @return + */ + public StorageOperationStatus deleteToscaDataElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, String uniqueKey, JsonPresentationFields mapKeyField) { + + List<String> uniqueKeys = new ArrayList<>(); + uniqueKeys.add(uniqueKey); + return deleteToscaDataElements(toscaElement, edgeLabel, uniqueKeys); + } + + @SuppressWarnings("unchecked") /** * Deletes tosca data elements belonging to tosca element according label * @param toscaElement @@ -1290,110 +1290,125 @@ public abstract class BaseOperation { * @param uniqueKeys * @return */ - public StorageOperationStatus deleteToscaDataElements(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, List<String> uniqueKeys) { - StorageOperationStatus result = null; - GraphVertex toscaDataVertex; - Map<String, ToscaDataDefinition> existingToscaDataMap; - Either<GraphVertex, TitanOperationStatus> toscaDataVertexRes = titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson); - if (toscaDataVertexRes.isRight()) { - TitanOperationStatus status = toscaDataVertexRes.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get child vertex of the tosca element {} by label {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel, status); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(toscaDataVertexRes.right().value()); - } - if (result == null) { - toscaDataVertex = toscaDataVertexRes.left().value(); - existingToscaDataMap = (Map<String, ToscaDataDefinition>) toscaDataVertex.getJson(); - result = deleteElementsFromDataVertex(toscaElement, edgeLabel, uniqueKeys, toscaDataVertex, existingToscaDataMap); - } - if (result == null) { - result = StorageOperationStatus.OK; - } - return result; - } - - private <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, GraphVertex toscaDataVertex) { - StorageOperationStatus result = StorageOperationStatus.OK; - Either<GraphVertex, TitanOperationStatus> updateOrCopyRes = updateOrCopyOnUpdate(toscaDataVertex, toscaElement, edgeLabel); - if (updateOrCopyRes.isRight()) { - result = DaoStatusConverter.convertTitanStatusToStorageStatus(updateOrCopyRes.right().value()); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update tosca data {} of the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), result); - } - return result; - } - - private <T extends ToscaDataDefinition> StorageOperationStatus removeKeyFromDataVertex(String uniqueKey, Map<String, T> existingToscaDataMap) { - if (!existingToscaDataMap.containsKey(uniqueKey)) { - return StorageOperationStatus.NOT_FOUND; - } - existingToscaDataMap.remove(uniqueKey); - return StorageOperationStatus.OK; - } - - protected <K extends ToscaDataDefinition> StorageOperationStatus handleToscaData(GraphVertex toscaElement, VertexTypeEnum vertexLabel, EdgeLabelEnum edgeLabel, GraphVertex toscaDataVertex, Map<String, K> mergedToscaDataMap) { - - StorageOperationStatus result = StorageOperationStatus.OK; - if (toscaDataVertex == null) { - - Either<GraphVertex, StorageOperationStatus> createRes = assosiateElementToData(toscaElement, vertexLabel, edgeLabel, mergedToscaDataMap); - if (createRes.isRight()) { - StorageOperationStatus status = createRes.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to assosiate tosca data {} of the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), status); - result = status; - } - } else { - toscaDataVertex.setJson(mergedToscaDataMap); - Either<GraphVertex, TitanOperationStatus> updateOrCopyRes = updateOrCopyOnUpdate(toscaDataVertex, toscaElement, edgeLabel); - if (updateOrCopyRes.isRight()) { - TitanOperationStatus status = updateOrCopyRes.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to add tosca data {} to the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), status); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - } - return result; - } - - private <T extends ToscaDataDefinition> Either<Map<String, T>, StorageOperationStatus> validateMergeToscaData(GraphVertex toscaElement, List<T> toscaDataList, JsonPresentationFields mapKeyField, Map<String, T> existingToscaDataMap, - boolean isUpdate) { - - Map<String, T> mergedToscaDataMap = new HashMap<>(); - StorageOperationStatus status; - Either<Map<String, T>, StorageOperationStatus> result = Either.left(mergedToscaDataMap); - if (MapUtils.isNotEmpty(existingToscaDataMap)) { - mergedToscaDataMap.putAll(existingToscaDataMap); - } - for (T toscaDataElement : toscaDataList) { - status = handleToscaDataElement(toscaElement, mapKeyField, mergedToscaDataMap, toscaDataElement, isUpdate); - if (status != StorageOperationStatus.OK) { - result = Either.right(status); - break; - } - } - return result; - } - - private <T extends ToscaDataDefinition> StorageOperationStatus handleToscaDataElement(GraphVertex toscaElement, JsonPresentationFields mapKeyField, Map<String, T> mergedToscaDataMap, T toscaDataElement, boolean isUpdate) { - - StorageOperationStatus status = StorageOperationStatus.OK; - String currKey = (String) toscaDataElement.getToscaPresentationValue(mapKeyField); - if (StringUtils.isEmpty(currKey)) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to add tosca data to tosca element {}. The key is empty. "); - status = StorageOperationStatus.BAD_REQUEST; - } else if (!isUpdate && mergedToscaDataMap.containsKey(currKey)) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to add tosca data to tosca element {}. The element with the same key {} already exists. ", toscaElement.getUniqueId(), currKey); - status = StorageOperationStatus.BAD_REQUEST; - } - mergedToscaDataMap.put(currKey, toscaDataElement); - return status; - } - -// public StorageOperationStatus updateDataOnGraph(GraphVertex dataVertex) { -// Either<GraphVertex, TitanOperationStatus> updateVertex = titanDao.updateVertex(dataVertex); -// if (updateVertex.isRight()) { -// return DaoStatusConverter.convertTitanStatusToStorageStatus(updateVertex.right().value()); -// } -// return StorageOperationStatus.OK; -// } - + public StorageOperationStatus deleteToscaDataElements(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, List<String> uniqueKeys) { + StorageOperationStatus result = null; + GraphVertex toscaDataVertex; + Map<String, ToscaDataDefinition> existingToscaDataMap; + Either<GraphVertex, TitanOperationStatus> toscaDataVertexRes = titanDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson); + if (toscaDataVertexRes.isRight()) { + TitanOperationStatus status = toscaDataVertexRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, status); + result = DaoStatusConverter.convertTitanStatusToStorageStatus(toscaDataVertexRes.right().value()); + } + if (result == null) { + toscaDataVertex = toscaDataVertexRes.left().value(); + existingToscaDataMap = (Map<String, ToscaDataDefinition>) toscaDataVertex.getJson(); + result = deleteElementsFromDataVertex(toscaElement, edgeLabel, uniqueKeys, toscaDataVertex, existingToscaDataMap); + } + if (result == null) { + result = StorageOperationStatus.OK; + } + return result; + } + + /** + * Adds the map data entry to the graph vertex of the specified type, related with the specified edge to the component specified by ID + * @param componentId The uniqueId of the component + * @param vertexTypeEnum The type of the vertex + * @param edgeLabelEnum The type of the edge + * @param mapDataEntry The map data entry + * @param <T extends MapDataDefinition> + * @return The status of the operation result + */ + public <T extends MapDataDefinition> StorageOperationStatus addElementToComponent(String componentId, VertexTypeEnum vertexTypeEnum, EdgeLabelEnum edgeLabelEnum, Map.Entry<String, T> mapDataEntry){ + if(MapUtils.isNotEmpty(mapDataEntry.getValue().getMapToscaDataDefinition())) + return addToscaDataDeepElementsBlockToToscaElement(componentId, edgeLabelEnum, vertexTypeEnum, mapDataEntry.getValue(), mapDataEntry.getKey()); + return StorageOperationStatus.OK; + } + + private <T extends ToscaDataDefinition> StorageOperationStatus updateToscaDataElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, GraphVertex toscaDataVertex) { + StorageOperationStatus result = StorageOperationStatus.OK; + Either<GraphVertex, TitanOperationStatus> updateOrCopyRes = updateOrCopyOnUpdate(toscaDataVertex, toscaElement, edgeLabel); + if (updateOrCopyRes.isRight()) { + result = DaoStatusConverter.convertTitanStatusToStorageStatus(updateOrCopyRes.right().value()); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update tosca data {} of the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), result); + } + return result; + } + + private <T extends ToscaDataDefinition> StorageOperationStatus removeKeyFromDataVertex(String uniqueKey, Map<String, T> existingToscaDataMap) { + if (!existingToscaDataMap.containsKey(uniqueKey)) { + return StorageOperationStatus.NOT_FOUND; + } + existingToscaDataMap.remove(uniqueKey); + return StorageOperationStatus.OK; + } + + protected <K extends ToscaDataDefinition> StorageOperationStatus handleToscaData(GraphVertex toscaElement, VertexTypeEnum vertexLabel, EdgeLabelEnum edgeLabel, GraphVertex toscaDataVertex, Map<String, K> mergedToscaDataMap) { + + StorageOperationStatus result = StorageOperationStatus.OK; + if (toscaDataVertex == null) { + + Either<GraphVertex, StorageOperationStatus> createRes = associateElementToData(toscaElement, vertexLabel, edgeLabel, mergedToscaDataMap); + if (createRes.isRight()) { + StorageOperationStatus status = createRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to assosiate tosca data {} of the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), status); + result = status; + } + } else { + toscaDataVertex.setJson(mergedToscaDataMap); + Either<GraphVertex, TitanOperationStatus> updateOrCopyRes = updateOrCopyOnUpdate(toscaDataVertex, toscaElement, edgeLabel); + if (updateOrCopyRes.isRight()) { + TitanOperationStatus status = updateOrCopyRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add tosca data {} to the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), status); + result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); + } + } + return result; + } + + private <T extends ToscaDataDefinition> Either<Map<String, T>, StorageOperationStatus> validateMergeToscaData(GraphVertex toscaElement, List<T> toscaDataList, JsonPresentationFields mapKeyField, Map<String, T> existingToscaDataMap, + boolean isUpdate) { + + Map<String, T> mergedToscaDataMap = new HashMap<>(); + StorageOperationStatus status; + Either<Map<String, T>, StorageOperationStatus> result = Either.left(mergedToscaDataMap); + if (MapUtils.isNotEmpty(existingToscaDataMap)) { + mergedToscaDataMap.putAll(existingToscaDataMap); + } + for (T toscaDataElement : toscaDataList) { + status = handleToscaDataElement(toscaElement, mapKeyField, mergedToscaDataMap, toscaDataElement, isUpdate); + if (status != StorageOperationStatus.OK) { + result = Either.right(status); + break; + } + } + return result; + } + + private <T extends ToscaDataDefinition> StorageOperationStatus handleToscaDataElement(GraphVertex toscaElement, JsonPresentationFields mapKeyField, Map<String, T> mergedToscaDataMap, T toscaDataElement, boolean isUpdate) { + + StorageOperationStatus status = StorageOperationStatus.OK; + String currKey = (String) toscaDataElement.getToscaPresentationValue(mapKeyField); + if (StringUtils.isEmpty(currKey)) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add tosca data to tosca element {}. The key is empty. "); + status = StorageOperationStatus.BAD_REQUEST; + } else if (!isUpdate && mergedToscaDataMap.containsKey(currKey)) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add tosca data to tosca element {}. The element with the same key {} already exists. ", toscaElement.getUniqueId(), currKey); + status = StorageOperationStatus.BAD_REQUEST; + } + mergedToscaDataMap.put(currKey, toscaDataElement); + return status; + } + +// public StorageOperationStatus updateDataOnGraph(GraphVertex dataVertex) { +// Either<GraphVertex, TitanOperationStatus> updateVertex = titanDao.updateVertex(dataVertex); +// if (updateVertex.isRight()) { +// return DaoStatusConverter.convertTitanStatusToStorageStatus(updateVertex.right().value()); +// } +// return StorageOperationStatus.OK; +// } + protected GroupInstanceDataDefinition buildGroupInstanceDataDefinition(GroupDataDefinition group, ComponentInstanceDataDefinition componentInstance, Map<String, ArtifactDataDefinition> instDeplArtifMap) { String componentInstanceName = componentInstance.getName(); @@ -1437,22 +1452,25 @@ public abstract class BaseOperation { return groupInstance; } - - protected String buildGroupInstanceName(String instanceName, String groupName) { - return ValidationUtils.normalizeComponentInstanceName(instanceName) + ".." + groupName; - } - protected String generateCustomizationUUID() { - return UUID.randomUUID().toString(); - } - - protected void convertPropertiesToInstanceProperties(List<PropertyDataDefinition> properties){ - properties.forEach(p -> p.convertPropertyDataToInstancePropertyData()); - } + protected String buildGroupInstanceName(String instanceName, String groupName) { + return ValidationUtils.normalizeComponentInstanceName(instanceName) + ".." + groupName; + } + + protected String generateCustomizationUUID() { + return UUID.randomUUID().toString(); + } + + protected void convertPropertiesToInstanceProperties(List<PropertyDataDefinition> properties){ + properties.forEach(PropertyDataDefinition::convertPropertyDataToInstancePropertyData); + } - private TitanOperationStatus logAndReturn(TitanOperationStatus titanOperationStatus, String logMsg, Object ... logParams) { - logger.debug(logMsg, logParams); - return titanOperationStatus; - } + private TitanOperationStatus logAndReturn(TitanOperationStatus titanOperationStatus, String logMsg, Object ... logParams) { + log.debug(logMsg, logParams); + return titanOperationStatus; + } + private GraphVertex throwStorageException(TitanOperationStatus status) { + throw new StorageException(status); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ByToscaNameDerivedNodeTypeResolver.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ByToscaNameDerivedNodeTypeResolver.java index 5e5ee63a59..5748629584 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ByToscaNameDerivedNodeTypeResolver.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ByToscaNameDerivedNodeTypeResolver.java @@ -20,10 +20,7 @@ package org.openecomp.sdc.be.model.jsontitan.operations; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import fj.data.Either; 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; @@ -35,7 +32,9 @@ import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import fj.data.Either; +import java.util.HashMap; +import java.util.List; +import java.util.Map; @Component("derived-resource-resolver") public class ByToscaNameDerivedNodeTypeResolver implements DerivedNodeTypeResolver { @@ -45,7 +44,7 @@ public class ByToscaNameDerivedNodeTypeResolver implements DerivedNodeTypeResolv @Override public Either<List<GraphVertex>, TitanOperationStatus> findDerivedResources(String parentResource) { - Map<GraphPropertyEnum, Object> propertiesToMatch = new HashMap<GraphPropertyEnum, Object>(); + Map<GraphPropertyEnum, Object> propertiesToMatch = new HashMap<>(); propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); propertiesToMatch.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, parentResource); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/CategoryOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/CategoryOperation.java index 5b7022989c..88f0ea3fd7 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/CategoryOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/CategoryOperation.java @@ -20,10 +20,7 @@ package org.openecomp.sdc.be.model.jsontitan.operations; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +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; @@ -33,61 +30,62 @@ import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; 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.log.wrappers.Logger; import org.openecomp.sdc.common.util.ValidationUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import fj.data.Either; +import java.util.HashMap; +import java.util.List; +import java.util.Map; @org.springframework.stereotype.Component("category-operation") public class CategoryOperation extends BaseOperation{ - - private static Logger log = LoggerFactory.getLogger(CategoryOperation.class.getName()); - /** - * - * @param name - * @param type - * @return - */ - public Either<GraphVertex, StorageOperationStatus> getCategory(String name, VertexTypeEnum type) { - if (name != null) { - String categoryUid = UniqueIdBuilder.buildComponentCategoryUid(name, type); - Map<GraphPropertyEnum, Object> props = new HashMap<>(); - props.put(GraphPropertyEnum.NORMALIZED_NAME, ValidationUtils.normalizeCategoryName4Uniqueness(name)); - Either<List<GraphVertex>, TitanOperationStatus> either = titanDao.getByCriteria(type, props); + private static final Logger log = Logger.getLogger(CategoryOperation.class.getName()); + + /** + * + * @param name + * @param type + * @return + */ + public Either<GraphVertex, StorageOperationStatus> getCategory(String name, VertexTypeEnum type) { + if (name != null) { + String categoryUid = UniqueIdBuilder.buildComponentCategoryUid(name, type); + Map<GraphPropertyEnum, Object> props = new HashMap<>(); + props.put(GraphPropertyEnum.NORMALIZED_NAME, ValidationUtils.normalizeCategoryName4Uniqueness(name)); + Either<List<GraphVertex>, TitanOperationStatus> either = titanDao.getByCriteria(type, props); - if (either.isRight()) { - TitanOperationStatus titanOperationStatus = either.right().value(); - log.debug("Problem while geting category with id {}. reason - {}", categoryUid, titanOperationStatus.name()); - if (titanOperationStatus == TitanOperationStatus.NOT_FOUND) { - return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND); - } else { - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - } - return Either.left(either.left().value().get(0)); - } else { - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - } - /** - * - * @param categoryV - * @param name - * @return - */ - public Either<GraphVertex, StorageOperationStatus> getSubCategoryForCategory(GraphVertex categoryV, String name ) { - Either<List<GraphVertex>, TitanOperationStatus> childrenVertecies = titanDao.getChildrenVertecies(categoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse); - if ( childrenVertecies.isRight() ){ - log.debug("Failed to fetch children verticies for category {} error {}", categoryV.getUniqueId(), childrenVertecies.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(childrenVertecies.right().value())); - } - for ( GraphVertex childV : childrenVertecies.left().value() ){ - if ( childV.getMetadataProperty(GraphPropertyEnum.NAME).equals(name) ){ - return Either.left(childV); - } - } - return Either.right(StorageOperationStatus.NOT_FOUND); - } + if (either.isRight()) { + TitanOperationStatus titanOperationStatus = either.right().value(); + log.debug("Problem while geting category with id {}. reason - {}", categoryUid, titanOperationStatus.name()); + if (titanOperationStatus == TitanOperationStatus.NOT_FOUND) { + return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND); + } else { + return Either.right(StorageOperationStatus.GENERAL_ERROR); + } + } + return Either.left(either.left().value().get(0)); + } else { + return Either.right(StorageOperationStatus.GENERAL_ERROR); + } + } + /** + * + * @param categoryV + * @param name + * @return + */ + public Either<GraphVertex, StorageOperationStatus> getSubCategoryForCategory(GraphVertex categoryV, String name ) { + Either<List<GraphVertex>, TitanOperationStatus> childrenVertecies = titanDao.getChildrenVertecies(categoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse); + if ( childrenVertecies.isRight() ){ + log.debug("Failed to fetch children verticies for category {} error {}", categoryV.getUniqueId(), childrenVertecies.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(childrenVertecies.right().value())); + } + for ( GraphVertex childV : childrenVertecies.left().value() ){ + if ( childV.getMetadataProperty(GraphPropertyEnum.NAME).equals(name) ){ + return Either.left(childV); + } + } + return Either.right(StorageOperationStatus.NOT_FOUND); + } } 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 index 2b35699289..70cfc5d238 100644 --- 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 @@ -1,11 +1,7 @@ package org.openecomp.sdc.be.model.jsontitan.operations; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; +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; @@ -14,12 +10,13 @@ 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.openecomp.sdc.be.model.operations.impl.OperationUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import fj.data.Either; +import java.util.*; + +import static java.util.Collections.emptyMap; /** * Created by yavivi on 26/01/2018. @@ -27,18 +24,12 @@ import fj.data.Either; @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 + private IdMapper idMapper; @Autowired - protected IdMapper idMapper; + private OperationUtils operationUtils; + /** * Constructor @@ -51,27 +42,27 @@ public class ExternalReferencesOperation extends BaseOperation { } 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(); + Either<String, ActionStatus> addResult = addExternalReference(serviceUuid, componentInstanceName, objectType, reference); + 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(); + Either<String, ActionStatus> result = deleteExternalReference(serviceUuid, componentInstanceName, objectType, reference); + 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(); + Either<String, ActionStatus> updateResult = updateExternalReference(serviceVertexUuid, componentInstanceName, objectType, oldRef, newRef); + 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); + //Get Container vertex + Either<GraphVertex, TitanOperationStatus> vertexById = titanDao.getVertexById(assetUuid); if (vertexById.isRight()){ return Either.right(ActionStatus.RESOURCE_NOT_FOUND); } @@ -84,37 +75,31 @@ public class ExternalReferencesOperation extends BaseOperation { } //Get the external references map vertex - final Either<GraphVertex, TitanOperationStatus> dataVertexResult = this.getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS); + final Either<GraphVertex, TitanOperationStatus> dataVertexResult = 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; + Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData; if (externalRefsVertex == null) { - //External Refs vertext does not exist, create its map. - externalReferencesFullData = new HashMap<String, MapComponentInstanceExternalRefs>() { - { - MapComponentInstanceExternalRefs externalRefsMap = new MapComponentInstanceExternalRefs(); - put(compInstanceUniqueId, externalRefsMap); - } - }; + //External Refs vertex does not exist, create its map. + externalReferencesFullData = new HashMap<>(); + externalReferencesFullData.put(compInstanceUniqueId, new MapComponentInstanceExternalRefs()); } else { externalReferencesFullData = (Map<String, MapComponentInstanceExternalRefs>) externalRefsVertex.getJson(); - if (externalReferencesFullData.get(compInstanceUniqueId) == null){ - externalReferencesFullData.put(compInstanceUniqueId, new MapComponentInstanceExternalRefs()); - } + externalReferencesFullData.computeIfAbsent(compInstanceUniqueId, k -> new MapComponentInstanceExternalRefs()); } - boolean isAdded = this.addExternalRef(externalReferencesFullData, compInstanceUniqueId, objectType, reference); - this.updateFullToscaData(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS, VertexTypeEnum.EXTERNAL_REF, externalReferencesFullData); + boolean isAdded = addExternalRef(externalReferencesFullData, compInstanceUniqueId, objectType, reference); + 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); + Either<GraphVertex, TitanOperationStatus> vertexById = titanDao.getVertexById(assetUuid); if (vertexById.isRight()){ return Either.right(ActionStatus.RESOURCE_NOT_FOUND); } @@ -126,7 +111,7 @@ public class ExternalReferencesOperation extends BaseOperation { } //Get the external references map vertex - final Either<GraphVertex, TitanOperationStatus> dataVertexResult = this.getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS); + final Either<GraphVertex, TitanOperationStatus> dataVertexResult = getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS); //Check whether data vertex found GraphVertex externalRefsVertex = dataVertexResult.isLeft() ? dataVertexResult.left().value() : null; @@ -134,8 +119,8 @@ public class ExternalReferencesOperation extends BaseOperation { 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 + refDeleted = deleteExternalRef(externalReferencesFullData, compInstanceUniqueId, objectType, reference); + updateFullToscaData(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS, VertexTypeEnum.EXTERNAL_REF, externalReferencesFullData); } } @@ -148,7 +133,7 @@ public class ExternalReferencesOperation extends BaseOperation { 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); + Either<GraphVertex, TitanOperationStatus> vertexById = titanDao.getVertexById(assetUuid); if (vertexById.isRight()){ return Either.right(ActionStatus.RESOURCE_NOT_FOUND); } @@ -162,7 +147,7 @@ public class ExternalReferencesOperation extends BaseOperation { } //Get the external references map vertex - final Either<GraphVertex, TitanOperationStatus> dataVertexResult = this.getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS); + final Either<GraphVertex, TitanOperationStatus> dataVertexResult = getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS); //Check whether data vertex found GraphVertex externalRefsVertex = dataVertexResult.isLeft() ? dataVertexResult.left().value() : null; @@ -170,8 +155,8 @@ public class ExternalReferencesOperation extends BaseOperation { 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); + refReplaced = updateExternalRef(externalReferencesFullData, compInstanceUniqueId, objectType, oldRef, newRef); + updateFullToscaData(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS, VertexTypeEnum.EXTERNAL_REF, externalReferencesFullData); } } if (refReplaced) { @@ -183,7 +168,7 @@ public class ExternalReferencesOperation extends BaseOperation { public Either<Map<String, List<String>>, ActionStatus> getExternalReferences(String assetUuid, String objectType) { //Get Service vertex - Either<GraphVertex, TitanOperationStatus> vertexById = this.titanDao.getVertexById(assetUuid); + Either<GraphVertex, TitanOperationStatus> vertexById = titanDao.getVertexById(assetUuid); if (vertexById.isRight()){ return Either.right(ActionStatus.RESOURCE_NOT_FOUND); } @@ -193,7 +178,7 @@ public class ExternalReferencesOperation extends BaseOperation { Map<String, List<String>> result = new HashMap(); //Get the external references map vertex - final Either<GraphVertex, TitanOperationStatus> dataVertexResult = this.getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS); + final Either<GraphVertex, TitanOperationStatus> dataVertexResult = getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS); //Check whether data vertex found GraphVertex externalRefsVertex = dataVertexResult.isLeft() ? dataVertexResult.left().value() : null; if (externalRefsVertex != null) { @@ -214,9 +199,47 @@ public class ExternalReferencesOperation extends BaseOperation { return Either.left(new HashMap<>()); } + public void addAllExternalReferences(String containerUniqueId, + String compInstanceUniqueId, + Map<String, List<String>> instanceExternalReferences) { + + GraphVertex serviceVertex = titanDao.getVertexById(containerUniqueId) + .left() + .on(operationUtils::onTitanOperationFailure); + Either<GraphVertex, TitanOperationStatus> dataVertex = getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS); + Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData; + if (dataVertex.isLeft()) { + externalReferencesFullData = (Map<String, MapComponentInstanceExternalRefs>) dataVertex.left().value().getJson(); + } else { + externalReferencesFullData = new HashMap<>(); + } + externalReferencesFullData.put(compInstanceUniqueId, new MapComponentInstanceExternalRefs(instanceExternalReferences)); + updateFullToscaData(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS, VertexTypeEnum.EXTERNAL_REF, externalReferencesFullData); + } + + public Map<String, List<String>> getAllExternalReferences(String containerUniqueId, + String compInstanceUniqueId) { + GraphVertex serviceVertex = titanDao.getVertexById(containerUniqueId) + .left() + .on(operationUtils::onTitanOperationFailure); + + Either<GraphVertex, TitanOperationStatus> dataVertex = getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS); + if (dataVertex.isRight()) { + return new HashMap<>(); + } + GraphVertex externalRefsVertex = dataVertex.left().value(); + Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData = externalRefsVertex == null ? null : (Map<String, MapComponentInstanceExternalRefs>) externalRefsVertex.getJson(); + if (externalReferencesFullData != null) { + return externalReferencesFullData + .getOrDefault(compInstanceUniqueId, new MapComponentInstanceExternalRefs()) + .getComponentInstanceExternalRefs(); + } + return emptyMap(); + } + public Either<List<String>, ActionStatus> getExternalReferences(String assetUuid, String componentInstanceName, String objectType) { //Get Service vertex - Either<GraphVertex, TitanOperationStatus> vertexById = this.titanDao.getVertexById(assetUuid); + Either<GraphVertex, TitanOperationStatus> vertexById = titanDao.getVertexById(assetUuid); if (vertexById.isRight()){ return Either.right(ActionStatus.RESOURCE_NOT_FOUND); } @@ -228,14 +251,14 @@ public class ExternalReferencesOperation extends BaseOperation { } //Get the external references map vertex - final Either<GraphVertex, TitanOperationStatus> dataVertexResult = this.getDataVertex(serviceVertex, EdgeLabelEnum.EXTERNAL_REFS); + final Either<GraphVertex, TitanOperationStatus> dataVertexResult = 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)); + return Either.left(getExternalReferencesByObjectId(externalReferencesFullData, compInstanceUniqueId, objectType)); } } @@ -243,10 +266,18 @@ public class ExternalReferencesOperation extends BaseOperation { return Either.left(new LinkedList()); } + public IdMapper getIdMapper() { + return idMapper; + } + + public void setIdMapper(IdMapper idMapper) { + this.idMapper = idMapper; + } + 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>(); + return externalRefsByObjectType != null ? externalRefsByObjectType : new LinkedList<>(); } private boolean updateExternalRef(Map<String, MapComponentInstanceExternalRefs> externalReferencesFullData, String componentInstanceId, String objectType, String oldRef, String newRef) { 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 index ed06704a68..0d82b0f27d 100644 --- 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 @@ -20,12 +20,7 @@ package org.openecomp.sdc.be.model.jsontitan.operations; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Set; -import java.util.UUID; - +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; @@ -37,14 +32,13 @@ 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 org.openecomp.sdc.common.log.wrappers.Logger; -import fj.data.Either; +import java.util.*; @org.springframework.stereotype.Component("forwarding-paths-operations") public class ForwardingPathOperation extends BaseOperation { - private static Logger logger = LoggerFactory.getLogger(ForwardingPathOperation.class.getName()); + private static final Logger log = Logger.getLogger(ForwardingPathOperation.class.getName()); public Either<Set<String>, StorageOperationStatus> deleteForwardingPath(Service service, Set<String> forwardingPathsToDelete) { @@ -89,7 +83,7 @@ public class ForwardingPathOperation extends BaseOperation { 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); + CommonUtility.addRecordToLog(log, CommonUtility.LogLevelEnum.DEBUG, "Failed to get tosca element {} upon adding the properties. Status is {}. ", serviceId, status); statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status); return Either.right(statusRes); } @@ -100,7 +94,7 @@ public class ForwardingPathOperation extends BaseOperation { 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); + log.error("Failed to find the parent capability of capability type {}. status is {}", serviceId, statusRes); return Either.right(statusRes); } return Either.left(currentPath); 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 668a6d973a..b417f83b74 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 @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,288 +20,376 @@ package org.openecomp.sdc.be.model.jsontitan.operations; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; - +import fj.data.Either; +import org.apache.commons.collections.MapUtils; 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.GroupDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.*; +import org.openecomp.sdc.be.datatypes.elements.MapCapabilityProperty; +import org.openecomp.sdc.be.datatypes.elements.MapListCapabilityDataDefinition; 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.*; import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; +import org.openecomp.sdc.be.model.operations.StorageException; 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.jsongraph.util.CommonUtility; import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.wrappers.Logger; -import fj.data.Either; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; +import java.util.stream.Collectors; @org.springframework.stereotype.Component("groups-operation") public class GroupsOperation extends BaseOperation { - private static final Logger log = LoggerFactory.getLogger(GroupsOperation.class); - - public Either<List<GroupDefinition>, StorageOperationStatus> createGroups(Component component, Map<String, GroupDataDefinition> groups) { + private static final Logger log = Logger.getLogger(GroupsOperation.class.getName()); - Either<List<GroupDefinition>, StorageOperationStatus> result = null; - Either<GraphVertex, TitanOperationStatus> getComponentVertex = null; - StorageOperationStatus status = null; - - if (result == null) { - getComponentVertex = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse); - if (getComponentVertex.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentVertex.right().value())); - } - } - if (result == null) { - status = topologyTemplateOperation.associateGroupsToComponent(getComponentVertex.left().value(), groups); - if (status != StorageOperationStatus.OK) { - result = Either.right(status); - } + public StorageOperationStatus deleteCalculatedCapabilitiesWithProperties(String componentId, List<GroupDefinition> groupDefinitions) { + Optional<StorageOperationStatus> error = groupDefinitions.stream().map(g->removeCalculatedCapabilityFromComponent(componentId, g.getUniqueId())).filter(status-> status!=StorageOperationStatus.OK).findFirst(); + if(!error.isPresent()){ + Map<String, MapCapabilityProperty> extractCapabilityPropertiesFromGroups = ModelConverter.extractCapabilityPropertiesFromGroups(groupDefinitions, false); + error = extractCapabilityPropertiesFromGroups.keySet().stream().map(k->removeCalculatedCapabilityPropertiesFromComponent(componentId, k)).filter(status-> status!=StorageOperationStatus.OK).findFirst(); } - if (result == null) { - result = Either.left(ModelConverter.convertToGroupDefinitions(groups)); + if(error.isPresent()){ + return error.get(); } - return result; + return StorageOperationStatus.OK; } - - 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; - - if (result == null) { - getComponentVertex = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse); - if (getComponentVertex.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentVertex.right().value())); - } - } - if (result == null) { - status = addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groups, JsonPresentationFields.NAME); - - if (status != StorageOperationStatus.OK) { - result = Either.right(status); - } + + /** + * Adds the map of the calculated capabilities and the map of the calculated capabilities properties the the component on the graph + * @param componentId + * @param calculatedCapabilities + * @param calculatedCapabilitiesProperties + * @return status of the result the operation + */ + public StorageOperationStatus addCalculatedCapabilitiesWithProperties(String componentId, Map<String, MapListCapabilityDataDefinition> calculatedCapabilities, Map<String, MapCapabilityProperty> calculatedCapabilitiesProperties) { + + Optional<StorageOperationStatus> error = calculatedCapabilities.entrySet().stream().map(e-> addElementToComponent(componentId, VertexTypeEnum.CALCULATED_CAPABILITIES, EdgeLabelEnum.CALCULATED_CAPABILITIES, e)).filter(status-> status!=StorageOperationStatus.OK).findFirst(); + if(!error.isPresent()){ + error = calculatedCapabilitiesProperties.entrySet().stream().map(e->addCalculatedCapabilityPropertiesToComponent(componentId, e)).filter(status-> status!=StorageOperationStatus.OK).findFirst(); } - - if (result == null) { - Map<String, GroupDataDefinition> mapGroup = groups.stream().collect(Collectors.toMap( x-> x.getName(), x->x)); - result = Either.left(ModelConverter.convertToGroupDefinitions(mapGroup)); + if(error.isPresent()){ + return error.get(); } - return result; + return StorageOperationStatus.OK; } - 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; - - if (result == null) { - getComponentVertex = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse); - if (getComponentVertex.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentVertex.right().value())); - } - } - if (result == null) { - List<String> groupName = groups.stream().map(g -> g.getName()).collect(Collectors.toList()); - status = deleteToscaDataElements(component.getUniqueId(), EdgeLabelEnum.GROUPS, groupName); - - if (status != StorageOperationStatus.OK) { - result = Either.right(status); - } + public StorageOperationStatus updateCalculatedCapabilitiesWithProperties(String componentId, Map<String, MapListCapabilityDataDefinition> calculatedCapabilities, Map<String, MapCapabilityProperty> calculatedCapabilitiesProperties) { + + Optional<StorageOperationStatus> error = calculatedCapabilities.entrySet().stream().map(e->updateCalculatedCapabilityOfComponent(componentId, e)).filter(status-> status!=StorageOperationStatus.OK).findFirst(); + if(!error.isPresent()){ + error = calculatedCapabilitiesProperties.entrySet().stream().map(e->updateCalculatedCapabilityPropertiesOnComponent(componentId, e)).filter(status-> status!=StorageOperationStatus.OK).findFirst(); } - - if (result == null) { - Map<String, GroupDataDefinition> mapGroup = groups.stream().collect(Collectors.toMap( x-> x.getName(), x->x)); - result = Either.left(ModelConverter.convertToGroupDefinitions(mapGroup)); + if(error.isPresent()){ + return error.get(); } - return result; + return StorageOperationStatus.OK; + } + + private StorageOperationStatus updateCalculatedCapabilityOfComponent(String componentId, Entry<String, MapListCapabilityDataDefinition> capabilities){ + if(MapUtils.isNotEmpty(capabilities.getValue().getMapToscaDataDefinition())) + return updateToscaDataDeepElementsBlockToToscaElement(componentId, EdgeLabelEnum.CALCULATED_CAPABILITIES, capabilities.getValue(), capabilities.getKey()); + return StorageOperationStatus.OK; } - 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; - - if (result == null) { - getComponentVertex = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse); - if (getComponentVertex.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentVertex.right().value())); - } - } - if (result == null) { - groups.forEach(gr -> { - String version = gr.getVersion(); - String newVersion = increaseMajorVersion(version); - gr.setVersion(newVersion); - String groupUUID = UniqueIdBuilder.generateUUID(); - gr.setGroupUUID(groupUUID); - }); - - status = updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groups, JsonPresentationFields.NAME); - - if (status != StorageOperationStatus.OK) { - result = Either.right(status); - } - } - - if (result == null) { - Map<String, GroupDataDefinition> mapGroup = groups.stream().collect(Collectors.toMap( x-> x.getName(), x->x)); - result = Either.left(ModelConverter.convertToGroupDefinitions(mapGroup)); - } - return result; + private StorageOperationStatus addCalculatedCapabilityPropertiesToComponent(String componentId, Entry<String, MapCapabilityProperty> properties){ + if(MapUtils.isNotEmpty(properties.getValue().getMapToscaDataDefinition())) + return addToscaDataDeepElementsBlockToToscaElement(componentId, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, properties.getValue(), properties.getKey()); + return StorageOperationStatus.OK; } + private StorageOperationStatus updateCalculatedCapabilityPropertiesOnComponent(String componentId, Entry<String, MapCapabilityProperty> properties){ + if(MapUtils.isNotEmpty(properties.getValue().getMapToscaDataDefinition())) + return updateToscaDataDeepElementsBlockToToscaElement(componentId, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, properties.getValue(), properties.getKey()); + return StorageOperationStatus.OK; + } - public Either<List<GroupProperty>, StorageOperationStatus> updateGroupPropertiesOnComponent(String componentId, GroupDefinition group, List<GroupProperty> newGroupProperties) { - - Either<List<GroupProperty>,StorageOperationStatus> result = null; - Either<GraphVertex, TitanOperationStatus> getComponentVertex = null; - GraphVertex componentVertex = null; - - if (result == null) { - getComponentVertex = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata); - if (getComponentVertex.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch component {}. Status is {} ", componentId); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentVertex.right().value())); - } - } - if (result == null) { - componentVertex = getComponentVertex.left().value(); - //update - List<PropertyDataDefinition> properties = group.getProperties(); - newGroupProperties.forEach(np -> { - Optional<PropertyDataDefinition> currentProp = properties.stream().filter(p -> p.getName().equals(np.getName())).findAny(); - if (currentProp.isPresent()) { - currentProp.get().setValue(np.getValue()); - } - }); - - StorageOperationStatus updateDataRes = updateToscaDataOfToscaElement(componentVertex, EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, group, JsonPresentationFields.NAME); - if ( updateDataRes != StorageOperationStatus.OK ){ - log.debug("Failed to update properties for group {} error {}", group.getName(), updateDataRes); - result = Either.right(updateDataRes); - } - } - if (result == null) { - componentVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); - Either<GraphVertex, TitanOperationStatus> updateRes = titanDao.updateVertex(componentVertex); - if (updateRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the component {}. Status is {} ", componentId, updateRes.right().value()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateRes.right().value())); - } - } - if (result == null) { - result = Either.left(newGroupProperties); - } - return result; + private StorageOperationStatus removeCalculatedCapabilityFromComponent(String componentId, String groupId){ + return deleteToscaDataDeepElementsBlockOfToscaElement(componentId, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, groupId); } - /** - * The version of the group is an integer. In order to support BC, we might get a version in a float format. - * - * @param version - * @return - */ - private String increaseMajorVersion(String version) { - - String[] versionParts = version.split(ToscaElementLifecycleOperation.VERSION_DELIMETER_REGEXP); - Integer majorVersion = Integer.parseInt(versionParts[0]); + private StorageOperationStatus removeCalculatedCapabilityPropertiesFromComponent(String componentId, String groupId){ + return deleteToscaDataDeepElementsBlockOfToscaElement(componentId, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, groupId); + } - majorVersion++; - return String.valueOf(majorVersion); + public Either<List<GroupDefinition>, StorageOperationStatus> createGroups(Component component, Map<String, GroupDataDefinition> groups) { - } + Either<List<GroupDefinition>, StorageOperationStatus> result = null; + Either<GraphVertex, TitanOperationStatus> getComponentVertex = null; + StorageOperationStatus status = null; - public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstances(Component component, String instanceId, List<GroupInstance> updatedGroupInstances) { + getComponentVertex = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse); + if (getComponentVertex.isRight()) { + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentVertex.right().value())); + } + if (result == null) { + status = topologyTemplateOperation.associateGroupsToComponent(getComponentVertex.left().value(), groups); + if (status != StorageOperationStatus.OK) { + result = Either.right(status); + } + } + if (result == null) { + result = Either.left(ModelConverter.convertToGroupDefinitions(groups)); + } + return result; + } - Either<List<GroupInstance>, StorageOperationStatus> result = null; - StorageOperationStatus status = null; + public <T extends GroupDataDefinition> Either<List<GroupDefinition>, StorageOperationStatus> addGroups(Component component, List<T> groups) { + Either<List<GroupDefinition>, StorageOperationStatus> result = null; + Either<GraphVertex, TitanOperationStatus> getComponentVertex; + StorageOperationStatus status; - Either<GraphVertex, TitanOperationStatus> getComponentVertex = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse); + getComponentVertex = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse); if (getComponentVertex.isRight()) { result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentVertex.right().value())); } - if (result == null) { - List<String> pathKeys = new ArrayList<>(); - pathKeys.add(instanceId); - status = updateToscaDataDeepElementsOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, updatedGroupInstances, pathKeys, JsonPresentationFields.NAME); - if (status != StorageOperationStatus.OK) { - result = Either.right(status); - } - } - if (result == null) { - result = Either.left(updatedGroupInstances); - } - return result; - } + if (result == null) { + status = addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groups, JsonPresentationFields.NAME); - 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(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); - } + if (status != StorageOperationStatus.OK) { + result = Either.right(status); + } + } + + if (result == null) { + Map<String, GroupDataDefinition> mapGroup = groups.stream().collect(Collectors.toMap(GroupDataDefinition::getName, x->x)); + result = Either.left(ModelConverter.convertToGroupDefinitions(mapGroup)); + } + return result; + } + + 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; - 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(log, LogLevelEnum.DEBUG, "Failed to delete group {} of component {}. The status is}. ", currentGroupName, component.getName(), status); + getComponentVertex = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse); + if (getComponentVertex.isRight()) { + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentVertex.right().value())); } - return status; - } + if (result == null) { + List<String> groupName = groups.stream().map(GroupDataDefinition::getName).collect(Collectors.toList()); + status = deleteToscaDataElements(component.getUniqueId(), EdgeLabelEnum.GROUPS, groupName); - 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(log, LogLevelEnum.DEBUG, "Failed to update group {} of component {}. The status is}. ", currentGroup.getName(), component.getName(), status); - return Either.right(status); + if (status != StorageOperationStatus.OK) { + result = Either.right(status); + } + } + + if (result == null) { + Map<String, GroupDataDefinition> mapGroup = groups.stream().collect(Collectors.toMap( GroupDataDefinition::getName, x->x)); + result = Either.left(ModelConverter.convertToGroupDefinitions(mapGroup)); + } + return result; + } + + public <T extends GroupDataDefinition> Either<List<GroupDefinition>, StorageOperationStatus> updateGroups(Component component, List<T> groups, boolean promoteVersion) { + Either<List<GroupDefinition>, StorageOperationStatus> result = null; + Either<GraphVertex, TitanOperationStatus> getComponentVertex = null; + StorageOperationStatus status = null; + + getComponentVertex = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse); + if (getComponentVertex.isRight()) { + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentVertex.right().value())); } - return Either.left(currentGroup); - } - - public Either<GroupInstance, StorageOperationStatus> updateGroupInstancePropertyValuesOnGraph(String componentId, String instanceId, GroupInstance oldGroupInstance, List<GroupInstanceProperty> newProperties) { + if (result == null) { + groups.forEach(gr -> { + updateVersion(promoteVersion, gr); + String groupUUID = UniqueIdBuilder.generateUUID(); + gr.setGroupUUID(groupUUID); + }); + + status = updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groups, JsonPresentationFields.NAME); + + if (status != StorageOperationStatus.OK) { + result = Either.right(status); + } + } + + if (result == null) { + Map<String, GroupDataDefinition> mapGroup = groups.stream().collect(Collectors.toMap( GroupDataDefinition::getName, x->x)); + result = Either.left(ModelConverter.convertToGroupDefinitions(mapGroup)); + } + return result; + } + + private <T extends GroupDataDefinition> void updateVersion(boolean promoteVersion, T group) { + if(promoteVersion) { + String version = group.getVersion(); + String newVersion = increaseMajorVersion(version); + group.setVersion(newVersion); + } + } + + public void updateGroupOnComponent(String componentId, GroupDefinition groupDefinition) { + GraphVertex componentVertex = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata) + .left() + .on(this::onTitanError); + + StorageOperationStatus updateToscaResult = updateToscaDataOfToscaElement(componentVertex, EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groupDefinition, + JsonPresentationFields.NAME); + + if (StorageOperationStatus.OK != updateToscaResult) { + throw new StorageException(updateToscaResult, groupDefinition.getUniqueId()); + } + + updateLastUpdateDate(componentVertex); + } - Either<GraphVertex, TitanOperationStatus> getComponentVertex = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata); + private void updateLastUpdateDate(GraphVertex componentVertex) { + componentVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); + titanDao.updateVertex(componentVertex) + .left() + .on(this::onTitanError); + } + + GraphVertex onTitanError(TitanOperationStatus titanOperationStatus) { + throw new StorageException( + DaoStatusConverter.convertTitanStatusToStorageStatus(titanOperationStatus)); + } + + public Either<List<GroupProperty>, StorageOperationStatus> updateGroupPropertiesOnComponent(String componentId, GroupDefinition group, List<GroupProperty> newGroupProperties) { + + Either<List<GroupProperty>, StorageOperationStatus> result = null; + Either<GraphVertex, TitanOperationStatus> getComponentVertex = null; + GraphVertex componentVertex = null; + + getComponentVertex = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata); if (getComponentVertex.isRight()) { CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch component {}. Status is {} ", componentId); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentVertex.right().value())); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentVertex.right().value())); } + if (result == null) { + componentVertex = getComponentVertex.left().value(); + //update + List<PropertyDataDefinition> properties = group.getProperties(); + newGroupProperties.forEach(np -> { + Optional<PropertyDataDefinition> currentProp = properties.stream().filter(p -> p.getName().equals(np.getName())).findAny(); + if (currentProp.isPresent()) { + currentProp.get().setValue(np.getValue()); + } + }); - List<PropertyDataDefinition> propertiesOld = oldGroupInstance.getProperties(); - newProperties.forEach(np -> { - Optional<PropertyDataDefinition> prop = propertiesOld.stream().filter(p -> p.getName().equals(np.getName())).findFirst(); - if (prop.isPresent()) { - prop.get().setValue(np.getValue()); - } - }); - GroupInstanceDataDefinition groupInstanceDataDefinition = new GroupInstanceDataDefinition(oldGroupInstance); - List<String> pathKeys = new ArrayList<>(); - pathKeys.add(instanceId); - StorageOperationStatus updateDataRes = updateToscaDataDeepElementOfToscaElement(componentId, EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, groupInstanceDataDefinition, pathKeys, JsonPresentationFields.NAME); - if (updateDataRes != StorageOperationStatus.OK) { - log.debug("Failed to update properties for group instance {} error {}", oldGroupInstance.getName(), updateDataRes); - return Either.right(updateDataRes); - } - return Either.left(oldGroupInstance); - } + StorageOperationStatus updateDataRes = updateToscaDataOfToscaElement(componentVertex, EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, group, JsonPresentationFields.NAME); + if (updateDataRes != StorageOperationStatus.OK) { + log.debug("Failed to update properties for group {} error {}", group.getName(), updateDataRes); + result = Either.right(updateDataRes); + } + } + if (result == null) { + componentVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); + Either<GraphVertex, TitanOperationStatus> updateRes = titanDao.updateVertex(componentVertex); + if (updateRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the component {}. Status is {} ", componentId, updateRes.right().value()); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateRes.right().value())); + } + } + if (result == null) { + result = Either.left(newGroupProperties); + } + return result; + } + + /** + * The version of the group is an integer. In order to support BC, we might get a version in a float format. + * + * @param version + * @return + */ + private String increaseMajorVersion(String version) { + + String[] versionParts = version.split(ToscaElementLifecycleOperation.VERSION_DELIMITER_REGEXP); + Integer majorVersion = Integer.parseInt(versionParts[0]); + + majorVersion++; + + return String.valueOf(majorVersion); + + } + + public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstances(Component component, String instanceId, List<GroupInstance> updatedGroupInstances) { + + Either<List<GroupInstance>, StorageOperationStatus> result = null; + StorageOperationStatus status = null; + + Either<GraphVertex, TitanOperationStatus> getComponentVertex = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse); + if (getComponentVertex.isRight()) { + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentVertex.right().value())); + } + if (result == null) { + List<String> pathKeys = new ArrayList<>(); + pathKeys.add(instanceId); + status = updateToscaDataDeepElementsOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, updatedGroupInstances, pathKeys, JsonPresentationFields.NAME); + if (status != StorageOperationStatus.OK) { + result = Either.right(status); + } + } + if (result == null) { + result = Either.left(updatedGroupInstances); + } + return result; + } + + 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(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); + } + + 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(log, LogLevelEnum.DEBUG, "Failed to delete group {} of component {}. The status is}. ", currentGroupName, component.getName(), status); + } + return status; + } + + 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(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); + } + + public Either<GroupInstance, StorageOperationStatus> updateGroupInstancePropertyValuesOnGraph(String componentId, String instanceId, GroupInstance oldGroupInstance, List<GroupInstanceProperty> newProperties) { + + Either<GraphVertex, TitanOperationStatus> getComponentVertex = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata); + if (getComponentVertex.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch component {}. Status is {} ", componentId); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentVertex.right().value())); + } + List<PropertyDataDefinition> propertiesOld = oldGroupInstance.getProperties(); + newProperties.forEach(np -> { + Optional<PropertyDataDefinition> prop = propertiesOld.stream().filter(p -> p.getName().equals(np.getName())).findFirst(); + if (prop.isPresent()) { + prop.get().setValue(np.getValue()); + } + }); + GroupInstanceDataDefinition groupInstanceDataDefinition = new GroupInstanceDataDefinition(oldGroupInstance); + List<String> pathKeys = new ArrayList<>(); + pathKeys.add(instanceId); + StorageOperationStatus updateDataRes = updateToscaDataDeepElementOfToscaElement(componentId, EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, groupInstanceDataDefinition, pathKeys, JsonPresentationFields.NAME); + if (updateDataRes != StorageOperationStatus.OK) { + 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/InterfaceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/InterfaceOperation.java index ea2f8bc1f7..a7587adae1 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/InterfaceOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/InterfaceOperation.java @@ -16,12 +16,7 @@ package org.openecomp.sdc.be.model.jsontitan.operations; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Set; -import java.util.UUID; - +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; @@ -33,15 +28,14 @@ import org.openecomp.sdc.be.model.Resource; 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 org.openecomp.sdc.common.log.wrappers.Logger; -import fj.data.Either; +import java.util.*; @org.springframework.stereotype.Component("interfaces-operation") public class InterfaceOperation extends BaseOperation { - private static Logger logger = LoggerFactory.getLogger(InterfaceOperation.class.getName()); + private static final Logger logger = Logger.getLogger(InterfaceOperation.class.getName()); public Either<Set<String>, StorageOperationStatus> deleteInterface(Resource resource, 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 561a95b693..eb41232ad0 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 @@ -20,71 +20,33 @@ package org.openecomp.sdc.be.model.jsontitan.operations; -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -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 com.thinkaurelius.titan.core.TitanVertex; +import fj.data.Either; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; +import org.apache.tinkerpop.gremlin.structure.Direction; +import org.apache.tinkerpop.gremlin.structure.Edge; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; 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.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.CompositionDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition; -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.MapDataDefinition; -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.RelationshipInstDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.*; +import org.openecomp.sdc.be.datatypes.elements.MapCapabilityProperty; +import org.openecomp.sdc.be.datatypes.elements.MapListCapabilityDataDefinition; +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.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; @@ -98,1905 +60,2111 @@ import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.openecomp.sdc.common.jsongraph.util.CommonUtility; import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.util.ValidationUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import fj.data.Either; +import java.io.IOException; +import java.util.*; +import java.util.Map.Entry; +import java.util.function.BiConsumer; +import java.util.function.BiPredicate; +import java.util.stream.Collectors; @org.springframework.stereotype.Component("node-template-operation") public class NodeTemplateOperation extends BaseOperation { + private static final String FAILED_TO_FETCH_CONTAINER_VERTEX_ERROR = "Failed to fetch container vertex {} error {}"; + private static final String FAILED_TO_UPDATE_TOPOLOGY_TEMPLATE_WITH_NEW_COMPONENT_INSTANCE = "Failed to update topology template {} with new component instance {}. "; private static final String ARTIFACT_PLACEHOLDER_TYPE = "type"; - private static final String ARTIFACT_PLACEHOLDER_DISPLAY_NAME = "displayName"; - private static final Object ARTIFACT_PLACEHOLDER_DESCRIPTION = "description"; - public static final String HEAT_ENV_NAME = "heatEnv"; - public static final String HEAT_VF_ENV_NAME = "VfHeatEnv"; - public static final String HEAT_ENV_SUFFIX = "env"; - private static Integer defaultHeatTimeout; - public static final Integer NON_HEAT_TIMEOUT = 0; - - private static Logger logger = LoggerFactory.getLogger(NodeTemplateOperation.class.getName()); - - public NodeTemplateOperation() { - defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes(); - if ((defaultHeatTimeout == null) || (defaultHeatTimeout < 1)) { - defaultHeatTimeout = 60; - } - } - - public static Integer getDefaultHeatTimeout() { - return defaultHeatTimeout; - } - - public Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addComponentInstanceToTopologyTemplate(TopologyTemplate container, ToscaElement originToscaElement, String instanceNumberSuffix, ComponentInstance componentInstance, - boolean allowDeleted, User user) { - - Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> result = null; - Either<TopologyTemplate, StorageOperationStatus> addComponentInstanceRes = null; - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Going to create component instance {} in component {}", componentInstance, container.getUniqueId()); - ComponentInstanceDataDefinition componentInstanceData = null; - Either<String, StorageOperationStatus> newInstanceNameRes = null; - - Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(container.getUniqueId(), JsonParseFlagEnum.ParseJson); - if (metadataVertex.isRight()) { - TitanOperationStatus status = metadataVertex.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - - if (result == null) { - - newInstanceNameRes = buildValidateInstanceName(container, originToscaElement, componentInstance, instanceNumberSuffix); - if (newInstanceNameRes.isRight()) { - result = Either.right(newInstanceNameRes.right().value()); - } - } - if (result == null) { - componentInstanceData = buildComponentInstanceDataDefinition(componentInstance, container.getUniqueId(), newInstanceNameRes.left().value(), true, originToscaElement); - - addComponentInstanceRes = addComponentInstanceToTopologyTemplate(container, originToscaElement, componentInstanceData, metadataVertex.left().value(), allowDeleted, user); - - if (addComponentInstanceRes.isRight()) { - StorageOperationStatus status = addComponentInstanceRes.right().value(); - if (status == StorageOperationStatus.NOT_FOUND) { - status = StorageOperationStatus.INVALID_ID; - } - result = Either.right(status); - } - if(componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy){ - TopologyTemplate updatedContainer = addComponentInstanceRes.left().value(); - result = addServerCapAndReqToProxyServerInstance( - updatedContainer, componentInstance, componentInstanceData); - - - - } - } - if (result == null) { - result = Either.left(new ImmutablePair<>(addComponentInstanceRes.left().value(), componentInstanceData.getUniqueId())); - } - return result; - } - - private Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addServerCapAndReqToProxyServerInstance(TopologyTemplate updatedContainer, ComponentInstance componentInstance, - - ComponentInstanceDataDefinition componentInstanceData) { - - Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> result; - - - Map<String, MapListCapabiltyDataDefinition> calcCap = updatedContainer.getCalculatedCapabilities(); - Map<String, MapListRequirementDataDefinition> calcReg = updatedContainer.getCalculatedRequirements(); - Map<String, MapCapabiltyProperty> calcCapProp = updatedContainer.getCalculatedCapabilitiesProperties(); - - - Map<String, List<CapabilityDefinition>> additionalCap = componentInstance.getCapabilities(); - Map<String, List<RequirementDefinition>> additionalReq = componentInstance.getRequirements(); - - MapListCapabiltyDataDefinition allCalculatedCap = calcCap==null ||!calcCap.containsKey(componentInstanceData.getUniqueId())?new MapListCapabiltyDataDefinition() :calcCap.get(componentInstanceData.getUniqueId()); - /********capability****************************/ - StorageOperationStatus status = deleteToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, componentInstanceData.getUniqueId()); - if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove calculated capabilty for instance {} in container {}. error {] ", componentInstanceData.getUniqueId(), updatedContainer.getUniqueId(), status); - return Either.right(status); - } - - if(additionalCap != null && !additionalCap.isEmpty()){ - - Map<String, ListCapabilityDataDefinition> serverCap = additionalCap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, en -> new ListCapabilityDataDefinition(en.getValue().stream().map(iCap -> new CapabilityDataDefinition(iCap)).collect(Collectors.toList())))); - - serverCap.entrySet().forEach(entryPerType -> { - entryPerType.getValue().getListToscaDataDefinition().forEach(cap -> { - cap.addToPath(componentInstance.getUniqueId()); - allCalculatedCap.add(entryPerType.getKey(), cap); - }); - }); - - status = addToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, allCalculatedCap, - componentInstance.getUniqueId()); - - /********capability property****************************/ - status = deleteToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, componentInstanceData.getUniqueId()); - if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove calculated capabilty properties for instance {} in container {}. error {] ", componentInstanceData.getUniqueId(), updatedContainer.getUniqueId(), status); - return Either.right(status); - } - - - MapCapabiltyProperty allCalculatedCapProp = calcCapProp==null ||!calcCapProp.containsKey(componentInstanceData.getUniqueId())?new MapCapabiltyProperty() :calcCapProp.get(componentInstanceData.getUniqueId()); - - - additionalCap.forEach(new BiConsumer<String, List<CapabilityDefinition>>() { - @Override - public void accept(String s, List<CapabilityDefinition> caps) { - - if (caps != null && !caps.isEmpty()) { - - MapPropertiesDataDefinition dataToCreate = new MapPropertiesDataDefinition(); - - for (CapabilityDefinition cap : caps) { - List<ComponentInstanceProperty> capPrps = cap.getProperties(); - if (capPrps != null) { - - for (ComponentInstanceProperty cip : capPrps) { - dataToCreate.put(cip.getName(), new PropertyDataDefinition(cip)); - } - - - StringBuffer sb = new StringBuffer(componentInstance.getUniqueId()); - sb.append(ModelConverter.CAP_PROP_DELIM); - - sb.append(cap.getOwnerId()); - - sb.append(ModelConverter.CAP_PROP_DELIM).append(s).append(ModelConverter.CAP_PROP_DELIM).append(cap.getName()); - allCalculatedCapProp.put(sb.toString(), dataToCreate); - } - } - - } - - } - }); - - status = addToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, allCalculatedCapProp, - componentInstance.getUniqueId()); - } - - /********Requirements property****************************/ - if(additionalReq != null && !additionalReq.isEmpty()){ - - MapListRequirementDataDefinition allCalculatedReq = calcReg==null ||!calcReg.containsKey(componentInstanceData.getUniqueId())?new MapListRequirementDataDefinition() :calcReg.get(componentInstanceData.getUniqueId()); - status = deleteToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, componentInstanceData.getUniqueId()); - if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove calculated Requirements for instance {} in container {}. error {] ", componentInstanceData.getUniqueId(), updatedContainer.getUniqueId(), status); - return Either.right(status); - } - - Map<String, ListRequirementDataDefinition> serverReq = additionalReq.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, en -> new ListRequirementDataDefinition(en.getValue().stream().map(iCap -> new RequirementDataDefinition(iCap)).collect(Collectors.toList())))); - - serverReq.entrySet().forEach(entryPerType -> { - entryPerType.getValue().getListToscaDataDefinition().forEach(cap -> { - cap.addToPath(componentInstance.getUniqueId()); - allCalculatedReq.add(entryPerType.getKey(), cap); - }); - }); - - status = addToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, allCalculatedReq, - componentInstance.getUniqueId()); - - } - - - Either<ToscaElement, StorageOperationStatus> updatedComponentInstanceRes = topologyTemplateOperation.getToscaElement(updatedContainer.getUniqueId()); - if (updatedComponentInstanceRes.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with new component instance {}. ", updatedContainer.getName(), componentInstance.getName()); - result = Either.right(updatedComponentInstanceRes.right().value()); - } - result = Either.left(new ImmutablePair<>((TopologyTemplate)updatedComponentInstanceRes.left().value(), componentInstanceData.getUniqueId())); - return result; - } - - - private Either<String, StorageOperationStatus> buildValidateInstanceName(TopologyTemplate container, ToscaElement originToscaElement, ComponentInstance componentInstance, String instanceNumberSuffix) { - - Either<String, StorageOperationStatus> result = null; - String instanceName = componentInstance.getName(); - if (StringUtils.isEmpty(instanceName) || instanceName.equalsIgnoreCase(originToscaElement.getName()) || componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) { - instanceName = buildComponentInstanceName(instanceNumberSuffix, instanceName); - } else if (!isUniqueInstanceName(container, componentInstance.getName())) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create component instance with name {} on component container {}. The instance with the same name already exists. ", componentInstance.getName(), container.getName()); - result = Either.right(StorageOperationStatus.ENTITY_ALREADY_EXISTS); - } - if (result == null) { - result = Either.left(instanceName); - } - return result; - } - - public Either<TopologyTemplate, StorageOperationStatus> addComponentInstanceToTopologyTemplate(TopologyTemplate container, ToscaElement originToscaElement, ComponentInstanceDataDefinition componentInstance, GraphVertex metadataVertex, - boolean allowDeleted, User user) { - - Either<TopologyTemplate, StorageOperationStatus> result = null; - Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null; - String containerComponentId = container.getUniqueId(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to create component instance {} in component {}", componentInstance, containerComponentId); - String instOriginComponentId = componentInstance.getComponentUid(); - Either<GraphVertex, TitanOperationStatus> updateElement = null; - - Boolean isDeleted = (Boolean) originToscaElement.getMetadataValue(JsonPresentationFields.IS_DELETED); - - if (!allowDeleted && (isDeleted != null) && isDeleted) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Component {} is already deleted. Cannot add component instance", instOriginComponentId); - result = Either.right(StorageOperationStatus.INVALID_ID); - } - if (result == null) { - container.addComponentInstance(componentInstance); - metadataVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); - topologyTemplateOperation.fillToscaElementVertexData(metadataVertex, container, JsonParseFlagEnum.ParseAll); - updateElement = titanDao.updateVertex(metadataVertex); - if (updateElement.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update topology template {} with new component instance {}. ", container.getName(), componentInstance.getName()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value())); - } - } - if (result == null) { - Either<GraphVertex, StorageOperationStatus> addToscaDataRes = addComponentInstanceToscaDataToContainerComponent(originToscaElement, componentInstance, updateElement.left().value(), user); - if (addToscaDataRes.isRight()) { - result = Either.right(addToscaDataRes.right().value()); - } - } - - if (result == null) { - updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponentId); - if (updateContainerComponentRes.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with new component instance {}. ", container.getName(), componentInstance.getName()); - result = Either.right(updateContainerComponentRes.right().value()); - } - } - if (result == null) { - result = Either.left((TopologyTemplate) updateContainerComponentRes.left().value()); - } - return result; - } - - public Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(TopologyTemplate container, ToscaElement originToscaElement, ComponentInstance componentInstance) { - - Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> result = null; - Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null; - - String containerComponentId = container.getUniqueId(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to update component instance metadata {} of container component {}", componentInstance, containerComponentId); - ComponentInstanceDataDefinition componentInstanceData = null; - - Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(container.getUniqueId(), JsonParseFlagEnum.ParseMetadata); - if (metadataVertex.isRight()) { - TitanOperationStatus status = metadataVertex.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - if (result == null) { - componentInstanceData = buildComponentInstanceDataDefinition(componentInstance, container.getUniqueId(), componentInstance.getName(), false, originToscaElement); - container.addComponentInstance(componentInstanceData); - metadataVertex.left().value().setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); - topologyTemplateOperation.fillToscaElementVertexData(metadataVertex.left().value(), container, JsonParseFlagEnum.ParseAll); - Either<GraphVertex, TitanOperationStatus> updateElement = titanDao.updateVertex(metadataVertex.left().value()); - if (updateElement.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update topology template {} with new component instance {}. ", container.getName(), componentInstance.getName()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value())); - } - } - if (result == null) { - updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponentId); - if (updateContainerComponentRes.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with updated component instance {}. ", container.getName(), componentInstance.getName()); - result = Either.right(updateContainerComponentRes.right().value()); - } - } - if (result == null) { - result = Either.left(new ImmutablePair<>((TopologyTemplate) updateContainerComponentRes.left().value(), componentInstanceData.getUniqueId())); - } - return result; - } - - public Either<TopologyTemplate, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(TopologyTemplate container, ComponentParametersView filter) { - - Either<TopologyTemplate, StorageOperationStatus> result = null; - Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null; - - String containerComponentId = container.getUniqueId(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to update component instance metadata of container component {}", containerComponentId); - - Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(container.getUniqueId(), JsonParseFlagEnum.ParseMetadata); - if (metadataVertex.isRight()) { - TitanOperationStatus status = metadataVertex.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - if (result == null) { - metadataVertex.left().value().setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); - topologyTemplateOperation.fillToscaElementVertexData(metadataVertex.left().value(), container, JsonParseFlagEnum.ParseAll); - Either<GraphVertex, TitanOperationStatus> updateElement = titanDao.updateVertex(metadataVertex.left().value()); - if (updateElement.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update topology template {}. ", container.getName()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value())); - } - } - if (result == null) { - updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponentId, filter); - if (updateContainerComponentRes.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {}. ", container.getName()); - result = Either.right(updateContainerComponentRes.right().value()); - } - } - if (result == null) { - result = Either.left((TopologyTemplate) updateContainerComponentRes.left().value()); - } - return result; - } - - public Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> deleteComponentInstanceFromTopologyTemplate(TopologyTemplate container, String componentInstanceId) { - - Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> result = null; - Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null; - - String containerComponentId = container.getUniqueId(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to update component instance metadata {} of container component {}", componentInstanceId, containerComponentId); - - Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(container.getUniqueId(), JsonParseFlagEnum.ParseMetadata); - if (metadataVertex.isRight()) { - TitanOperationStatus status = metadataVertex.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - GraphVertex containerV = null; - if (result == null) { - container.getComponentInstances().remove(componentInstanceId); - containerV = metadataVertex.left().value(); - StorageOperationStatus status = removeRelationsOfInstance(container, componentInstanceId, containerV); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete relation for component instance {} in container. error {}", componentInstanceId, container.getUniqueId(), status); - result = Either.right(status); - } - - containerV.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); - topologyTemplateOperation.fillToscaElementVertexData(containerV, container, JsonParseFlagEnum.ParseAll); - Either<GraphVertex, TitanOperationStatus> updateElement = titanDao.updateVertex(containerV); - if (updateElement.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update topology template {} with new component instance {}. ", container.getName(), componentInstanceId); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value())); - } - } - if (result == null) { - StorageOperationStatus status = deleteComponentInstanceToscaDataFromContainerComponent(containerV, componentInstanceId); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete data for instance {} in container {}. error {] ", componentInstanceId, container.getUniqueId(), status); - return Either.right(status); - } - updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponentId); - if (updateContainerComponentRes.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} after deleting the component instance {}. ", container.getName(), componentInstanceId); - result = Either.right(updateContainerComponentRes.right().value()); - } - } - if (result == null) { - result = Either.left(new ImmutablePair<>((TopologyTemplate) updateContainerComponentRes.left().value(), componentInstanceId)); - } - return result; - } - - private StorageOperationStatus removeRelationsOfInstance(TopologyTemplate container, String ciToRemove, GraphVertex containerV) { - CompositionDataDefinition composition = container.getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()); - if (composition != null) { - Map<String, RelationshipInstDataDefinition> relations = composition.getRelations(); - if (MapUtils.isNotEmpty(relations)) { - Either<Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>>, StorageOperationStatus> capResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES); - if (capResult.isRight()) { - return capResult.right().value(); - - } - Map<String, MapListCapabiltyDataDefinition> calculatedCapabilty = capResult.left().value().getRight(); - - Either<Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>>, StorageOperationStatus> capFullResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES); - if (capFullResult.isRight()) { - return capFullResult.right().value(); - - } - Map<String, MapListCapabiltyDataDefinition> fullFilledCapabilty = capFullResult.left().value().getRight(); - - Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS); - if (reqResult.isRight()) { - return reqResult.right().value(); - } - Map<String, MapListRequirementDataDefinition> calculatedRequirement = reqResult.left().value().getRight(); - - Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqFullResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS); - if (reqResult.isRight()) { - return reqResult.right().value(); - } - Map<String, MapListRequirementDataDefinition> fullfilledRequirement = reqFullResult.left().value().getRight(); - - Iterator<Entry<String, RelationshipInstDataDefinition>> iterator = relations.entrySet().iterator(); - while (iterator.hasNext()) { - Entry<String, RelationshipInstDataDefinition> relation = iterator.next(); - RelationshipInstDataDefinition relationToDelete = relation.getValue(); - if (relationToDelete.getFromId().equals(ciToRemove) || relationToDelete.getToId().equals(ciToRemove)) { - iterator.remove(); - if (relationToDelete.getFromId().equals(ciToRemove)) { - updateCalculatedRequirementsAfterDeleteRelation(calculatedRequirement, fullfilledRequirement, ciToRemove, relationToDelete, null); - updateCalculatedCapabiltyAfterDeleteRelation(calculatedCapabilty, fullFilledCapabilty, relationToDelete.getToId(), relationToDelete, null); - } - if (relationToDelete.getToId().equals(ciToRemove)) { - updateCalculatedRequirementsAfterDeleteRelation(calculatedRequirement, fullfilledRequirement, relationToDelete.getFromId(), relationToDelete, null); - updateCalculatedCapabiltyAfterDeleteRelation(calculatedCapabilty, fullFilledCapabilty, ciToRemove, relationToDelete, null); - } - } - } - return updateAllAndCalculatedCapReqOnGraph(container.getUniqueId(), containerV, capResult, capFullResult, reqResult, reqFullResult); - } - } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus deleteComponentInstanceToscaDataFromContainerComponent(GraphVertex containerV, String componentInstanceId) { - StorageOperationStatus status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, componentInstanceId); - if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove calculated capabilty for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); - return status; - } - status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, componentInstanceId); - if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove calculated capabilty properties for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); - return status; - } - status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, componentInstanceId); - if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove calculated requirement for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); - return status; - } - status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES, VertexTypeEnum.FULLFILLED_CAPABILITIES, componentInstanceId); - if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove fullfilled capabilities for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); - return status; - } - status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, VertexTypeEnum.FULLFILLED_REQUIREMENTS, componentInstanceId); - if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove fullfilled requirement for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); - return status; - } - status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_ATTRIBUTES, VertexTypeEnum.INST_ATTRIBUTES, componentInstanceId); - if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove attributes for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); - return status; - } - status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, componentInstanceId); - if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove properties for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); - return status; - } - status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, componentInstanceId); - if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove instance inputs for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); - return status; - } - status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, componentInstanceId); - if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove fullfilled requirement for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); - return status; - } - status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, componentInstanceId); - if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove instance deployment artifacts for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); - return status; - } - status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INSTANCE_ARTIFACTS, VertexTypeEnum.INSTANCE_ARTIFACTS, componentInstanceId); - if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove instance artifacts for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); - return status; - } - return StorageOperationStatus.OK; - } - - protected Either<GraphVertex, StorageOperationStatus> addComponentInstanceToscaDataToContainerComponent(ToscaElement originToscaElement, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex, User user) { - - Either<GraphVertex, StorageOperationStatus> result; - StorageOperationStatus status; - if (originToscaElement.getToscaType() == ToscaElementTypeEnum.NodeType) { - status = addComponentInstanceToscaDataToNodeTypeContainer((NodeType) originToscaElement, componentInstance, updatedContainerVertex, user, HEAT_VF_ENV_NAME); - } else { - status = addComponentInstanceToscaDataToTopologyTemplateContainer((TopologyTemplate) originToscaElement, componentInstance, updatedContainerVertex); - } - if (status == StorageOperationStatus.OK) { - result = Either.left(updatedContainerVertex); - } else { - result = Either.right(status); - } - return result; - } - - private StorageOperationStatus addComponentInstanceToscaDataToTopologyTemplateContainer(TopologyTemplate originTopologyTemplate, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex) { - - StorageOperationStatus status; - - status = addCalculatedCapReqFromTopologyTemplate(originTopologyTemplate, componentInstance, updatedContainerVertex); - - if (status != StorageOperationStatus.OK) { - - return status; - } - - MapPropertiesDataDefinition instProperties = new MapPropertiesDataDefinition(originTopologyTemplate.getInputs()); - - status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, instProperties, componentInstance.getUniqueId()); - if (status != StorageOperationStatus.OK) { - return status; - } - - return status; - } - - private StorageOperationStatus addCalculatedCapReqFromTopologyTemplate(TopologyTemplate originTopologyTemplate, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex) { - Map<String, MapListCapabiltyDataDefinition> calculatedCapabilities = originTopologyTemplate.getCalculatedCapabilities(); - - if (calculatedCapabilities != null) { - MapListCapabiltyDataDefinition allCalculatedCap = new MapListCapabiltyDataDefinition(); - calculatedCapabilities.entrySet().forEach(enntryPerInstance -> { - Map<String, ListCapabilityDataDefinition> mapByType = enntryPerInstance.getValue().getMapToscaDataDefinition(); - mapByType.entrySet().forEach(entryPerType -> { - entryPerType.getValue().getListToscaDataDefinition().forEach(cap -> { - cap.addToPath(componentInstance.getUniqueId()); - allCalculatedCap.add(entryPerType.getKey(), cap); - }); - }); - }); - - StorageOperationStatus calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, allCalculatedCap, - componentInstance.getUniqueId()); - - if (calculatedResult != StorageOperationStatus.OK) { - return calculatedResult; - } - MapListCapabiltyDataDefinition fullCalculatedCap = new MapListCapabiltyDataDefinition(); - calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.FULLFILLED_CAPABILITIES, VertexTypeEnum.FULLFILLED_CAPABILITIES, fullCalculatedCap, componentInstance.getUniqueId()); - - if (calculatedResult != StorageOperationStatus.OK) { - return calculatedResult; - } - } - Map<String, MapListRequirementDataDefinition> calculatedRequirements = originTopologyTemplate.getCalculatedRequirements(); - if (calculatedRequirements != null) { - - MapListRequirementDataDefinition allCalculatedReq = new MapListRequirementDataDefinition(); - calculatedRequirements.entrySet().forEach(enntryPerInstance -> { - Map<String, ListRequirementDataDefinition> mapByType = enntryPerInstance.getValue().getMapToscaDataDefinition(); - mapByType.entrySet().forEach(entryPerType -> { - entryPerType.getValue().getListToscaDataDefinition().forEach(req -> { - req.addToPath(componentInstance.getUniqueId()); - allCalculatedReq.add(entryPerType.getKey(), req); - }); - }); - }); - - StorageOperationStatus calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, allCalculatedReq, - componentInstance.getUniqueId()); - if (calculatedResult != StorageOperationStatus.OK) { - return calculatedResult; - } - MapListRequirementDataDefinition fullCalculatedReq = new MapListRequirementDataDefinition(); - calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, VertexTypeEnum.FULLFILLED_REQUIREMENTS, fullCalculatedReq, componentInstance.getUniqueId()); - if (calculatedResult != StorageOperationStatus.OK) { - return calculatedResult; - } - } - - Map<String, MapCapabiltyProperty> calculatedCapabilitiesProperties = originTopologyTemplate.getCalculatedCapabilitiesProperties(); - Map<String, MapPropertiesDataDefinition> updateKeyMap = new HashMap<>(); - - if (calculatedCapabilitiesProperties != null && !calculatedCapabilitiesProperties.isEmpty()) { - for (MapCapabiltyProperty map : calculatedCapabilitiesProperties.values()) { - for (Entry<String, MapPropertiesDataDefinition> entry : map.getMapToscaDataDefinition().entrySet()) { - String newKey = new String(componentInstance.getUniqueId() + ModelConverter.CAP_PROP_DELIM + entry.getKey()); - updateKeyMap.put(newKey, entry.getValue()); - } - } - MapCapabiltyProperty mapCapabiltyProperty = new MapCapabiltyProperty(updateKeyMap); - StorageOperationStatus calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, mapCapabiltyProperty, - componentInstance.getUniqueId()); - if (calculatedResult != StorageOperationStatus.OK) { - return calculatedResult; - } - } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus addComponentInstanceToscaDataToNodeTypeContainer(NodeType originNodeType, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex, User user, String envType) { - - MapPropertiesDataDefinition instProperties = new MapPropertiesDataDefinition(originNodeType.getProperties()); - - StorageOperationStatus status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, instProperties, componentInstance.getUniqueId()); - if (status != StorageOperationStatus.OK) { - return status; - } - - MapPropertiesDataDefinition instAttributes = new MapPropertiesDataDefinition(originNodeType.getAttributes()); - - status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.INST_ATTRIBUTES, VertexTypeEnum.INST_ATTRIBUTES, instAttributes, componentInstance.getUniqueId()); - - if (status != StorageOperationStatus.OK) { - return status; - } - - return addCalculatedCapReqFromNodeType(originNodeType, componentInstance, updatedContainerVertex); - } - - public MapArtifactDataDefinition prepareInstDeploymentArtifactPerInstance(Map<String, ArtifactDataDefinition> deploymentArtifacts, String componentInstanceId, User user, String envType) { - if (deploymentArtifacts != null && envType.equals(HEAT_VF_ENV_NAME)) { - Map<String, ArtifactDataDefinition> instDeploymentArtifacts = new HashMap<>(); - - deploymentArtifacts.entrySet().forEach(e -> { - ArtifactDataDefinition artifact = e.getValue(); - String type = artifact.getArtifactType(); - if (type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) { - ArtifactDataDefinition artifactEnv = createArtifactPlaceHolderInfo(artifact, componentInstanceId, user, envType); - instDeploymentArtifacts.put(artifactEnv.getArtifactLabel(), artifactEnv); - } - }); - - deploymentArtifacts.putAll(instDeploymentArtifacts); - MapArtifactDataDefinition instArtifacts = new MapArtifactDataDefinition(deploymentArtifacts); - - return instArtifacts; - } - return null; - } - - @SuppressWarnings({ "unchecked" }) - private ArtifactDataDefinition createArtifactPlaceHolderInfo(ArtifactDataDefinition artifactHeat, String componentId, User user, String heatEnvType) { - Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts(); - if (deploymentResourceArtifacts == null) { - logger.debug("no deployment artifacts are configured for generated artifacts"); - return null; - } - Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(heatEnvType); - if (placeHolderData == null) { - logger.debug("no env type {} are configured for generated artifacts", heatEnvType); - return null; - } - - String envLabel = (artifactHeat.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase(); - - ArtifactDataDefinition artifactInfo = new ArtifactDataDefinition(); - - String artifactName = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_DISPLAY_NAME); - String artifactType = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_TYPE); - String artifactDescription = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_DESCRIPTION); - - artifactInfo.setArtifactDisplayName(artifactName); - artifactInfo.setArtifactLabel(envLabel); - artifactInfo.setArtifactType(artifactType); - artifactInfo.setDescription(artifactDescription); - artifactInfo.setArtifactGroupType(artifactHeat.getArtifactGroupType()); - setDefaultArtifactTimeout(artifactHeat.getArtifactGroupType(), artifactInfo); - artifactInfo.setGeneratedFromId(artifactHeat.getUniqueId()); - // clone heat parameters in case of heat env only not VF heat env - if (heatEnvType.equals(HEAT_ENV_NAME)) { - artifactInfo.setHeatParameters(artifactHeat.getHeatParameters()); - } - setArtifactPlaceholderCommonFields(componentId, user, artifactInfo); - - return artifactInfo; - } - - public void setDefaultArtifactTimeout(ArtifactGroupTypeEnum groupType, ArtifactDataDefinition artifactInfo) { - if (groupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) { - artifactInfo.setTimeout(defaultHeatTimeout); - } else { - artifactInfo.setTimeout(NON_HEAT_TIMEOUT); - } - } - - private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDataDefinition artifactInfo) { - String uniqueId = null; - - if (resourceId != null) { - uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel().toLowerCase()); - artifactInfo.setUniqueId(uniqueId); - } - artifactInfo.setUserIdCreator(user.getUserId()); - String fullName = user.getFullName(); - artifactInfo.setUpdaterFullName(fullName); - - long time = System.currentTimeMillis(); - - artifactInfo.setCreatorFullName(fullName); - artifactInfo.setCreationDate(time); - - artifactInfo.setLastUpdateDate(time); - artifactInfo.setUserIdLastUpdater(user.getUserId()); - - artifactInfo.setMandatory(true); - } - - /** - * - * @param originNodeType - * @param componentInstance - * @param updatedContainerVertex - * @return - */ - private StorageOperationStatus addCalculatedCapReqFromNodeType(NodeType originNodeType, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex) { - - Map<String, ListCapabilityDataDefinition> capabilities = originNodeType.getCapabilties(); - MapListCapabiltyDataDefinition allCalculatedCap = prepareCalculatedCapabiltyForNodeType(capabilities, componentInstance); - StorageOperationStatus calculatedResult; - if (allCalculatedCap != null) { - calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, allCalculatedCap, componentInstance.getUniqueId()); - - if (calculatedResult != StorageOperationStatus.OK) { - return calculatedResult; - } - } - Map<String, MapPropertiesDataDefinition> capabiltiesProperties = originNodeType.getCapabiltiesProperties(); - if (capabiltiesProperties != null) { - Map<String, MapPropertiesDataDefinition> updateKeyMap = capabiltiesProperties.entrySet().stream().collect(Collectors.toMap(e -> createCapPropertyKey(e.getKey(), componentInstance.getUniqueId()), e -> e.getValue())); - MapCapabiltyProperty mapCapabiltyProperty = new MapCapabiltyProperty(updateKeyMap); - calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, mapCapabiltyProperty, componentInstance.getUniqueId()); - if (calculatedResult != StorageOperationStatus.OK) { - return calculatedResult; - } - } - - MapListCapabiltyDataDefinition fullCalculatedCap = new MapListCapabiltyDataDefinition(); - calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.FULLFILLED_CAPABILITIES, VertexTypeEnum.FULLFILLED_CAPABILITIES, fullCalculatedCap, componentInstance.getUniqueId()); - - if (calculatedResult != StorageOperationStatus.OK) { - return calculatedResult; - } - - Map<String, ListRequirementDataDefinition> requirements = originNodeType.getRequirements(); - - MapListRequirementDataDefinition allCalculatedReq = prepareCalculatedRequirementForNodeType(requirements, componentInstance); - - StorageOperationStatus status; - if (allCalculatedReq != null) { - status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, allCalculatedReq, componentInstance.getUniqueId()); - if (status != StorageOperationStatus.OK) { - return status; - } - } - MapListRequirementDataDefinition fullCalculatedReq = new MapListRequirementDataDefinition(); - status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, VertexTypeEnum.FULLFILLED_REQUIREMENTS, fullCalculatedReq, componentInstance.getUniqueId()); - return StorageOperationStatus.OK; - - } - - public static String createCapPropertyKey(String key, String instanceId) { - StringBuffer sb = new StringBuffer(instanceId); - sb.append(ModelConverter.CAP_PROP_DELIM).append(instanceId).append(ModelConverter.CAP_PROP_DELIM).append(key); - return sb.toString(); - } - - /** - * Prepares a map of capabilities lists - * Produces a deep copy of the received map of capabilities - * Sets values to the specific fields according to received component instance - * @param capabilities - * @param componentInstance - * @return - */ - public MapListCapabiltyDataDefinition prepareCalculatedCapabiltyForNodeType(Map<String, ListCapabilityDataDefinition> capabilities, ComponentInstanceDataDefinition componentInstance) { - if (capabilities != null) { - MapListCapabiltyDataDefinition allCalculatedCap = new MapListCapabiltyDataDefinition(); - - capabilities.entrySet().forEach(e -> { - List<CapabilityDataDefinition> listCapabilities = e.getValue().getListToscaDataDefinition().stream().map(c -> new CapabilityDataDefinition(c)).collect(Collectors.toList()); - listCapabilities.forEach(cap -> { - cap.setSource(componentInstance.getComponentUid()); - cap.addToPath(componentInstance.getUniqueId()); - cap.setOwnerId(componentInstance.getUniqueId()); - cap.setOwnerName(componentInstance.getName()); - cap.setLeftOccurrences(cap.getMaxOccurrences()); - allCalculatedCap.add(e.getKey(), cap); - }); - }); - return allCalculatedCap; - } - return null; - } - - /** - * Prepares a map of requirements lists - * Produces a deep copy of the received map of requirements - * Sets values to the specific fields according to received component instance - * @param requirements - * @param componentInstance - * @return - */ - public MapListRequirementDataDefinition prepareCalculatedRequirementForNodeType(Map<String, ListRequirementDataDefinition> requirements, ComponentInstanceDataDefinition componentInstance) { - if (requirements != null) { - MapListRequirementDataDefinition allCalculatedReq = new MapListRequirementDataDefinition(); - - requirements.entrySet().forEach(e -> { - List<RequirementDataDefinition> listRequirements = e.getValue().getListToscaDataDefinition().stream().map(r -> new RequirementDataDefinition(r)).collect(Collectors.toList()); - listRequirements.forEach(req -> { - req.setSource(componentInstance.getComponentUid()); - req.addToPath(componentInstance.getUniqueId()); - req.setOwnerId(componentInstance.getUniqueId()); - req.setOwnerName(componentInstance.getName()); - req.setLeftOccurrences(req.getMaxOccurrences()); - allCalculatedReq.add(e.getKey(), req); - }); - }); - return allCalculatedReq; - } - return null; - } - - public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstanceDataDefinition componentInstance, List<GroupDefinition> groups, Map<String, List<ArtifactDefinition>> groupInstancesArtifacts) { - - StorageOperationStatus result = null; - Map<String, GroupInstanceDataDefinition> groupInstanceToCreate = new HashMap<>(); - if (groupInstancesArtifacts != null && CollectionUtils.isNotEmpty(groups)) { - for (Map.Entry<String, List<ArtifactDefinition>> groupArtifacts : groupInstancesArtifacts.entrySet()) { - Optional<GroupDefinition> groupOptional = groups.stream().filter(g -> g.getUniqueId().equals(groupArtifacts.getKey())).findFirst(); - if (groupOptional.isPresent()) { - GroupInstanceDataDefinition groupInstance = buildGroupInstanceDataDefinition((GroupDataDefinition) groupOptional.get(), (ComponentInstanceDataDefinition) componentInstance, null); - groupInstance.setGroupInstanceArtifacts(groupArtifacts.getValue().stream().map(a -> a.getUniqueId()).collect(Collectors.toList())); - groupInstance.setGroupInstanceArtifactsUuid(groupArtifacts.getValue().stream().map(a -> a.getArtifactUUID()).collect(Collectors.toList())); - groupInstanceToCreate.put(groupInstance.getName(), groupInstance); - } - } - } - if (MapUtils.isNotEmpty(groupInstanceToCreate)) { - result = addToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, new MapDataDefinition<>(groupInstanceToCreate), componentInstance.getUniqueId()); - } - if (result == null) { - result = StorageOperationStatus.OK; - } - return result; - } - - private ComponentInstanceDataDefinition buildComponentInstanceDataDefinition(ComponentInstance resourceInstance, String containerComponentId, String instanceNewName, boolean generateUid, ToscaElement originToscaElement) { - String ciOriginComponentUid = resourceInstance.getComponentUid(); - - if (!ValidationUtils.validateStringNotEmpty(resourceInstance.getCustomizationUUID())) { - resourceInstance.setCustomizationUUID(generateCustomizationUUID()); - } - ComponentInstanceDataDefinition dataDefinition = new ComponentInstanceDataDefinition(resourceInstance); - - Long creationDate = resourceInstance.getCreationTime(); - Long modificationTime; - if (creationDate == null) { - creationDate = System.currentTimeMillis(); - modificationTime = creationDate; - } else { - modificationTime = System.currentTimeMillis(); - } - dataDefinition.setComponentUid(ciOriginComponentUid); - dataDefinition.setCreationTime(creationDate); - dataDefinition.setModificationTime(modificationTime); - if (StringUtils.isNotEmpty(instanceNewName)) { - dataDefinition.setName(instanceNewName); - resourceInstance.setName(instanceNewName); - } - if (StringUtils.isNotEmpty(dataDefinition.getName())) - dataDefinition.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(dataDefinition.getName())); - dataDefinition.setIcon(resourceInstance.getIcon()); - if (generateUid) { - dataDefinition.setUniqueId(UniqueIdBuilder.buildResourceInstanceUniuqeId(containerComponentId, ciOriginComponentUid, dataDefinition.getNormalizedName())); - resourceInstance.setUniqueId(dataDefinition.getUniqueId()); - } - if (StringUtils.isEmpty(dataDefinition.getComponentVersion()) && originToscaElement != null) - dataDefinition.setComponentVersion((String) originToscaElement.getMetadataValue(JsonPresentationFields.VERSION)); - if (StringUtils.isEmpty(dataDefinition.getComponentName()) && originToscaElement != null) - dataDefinition.setComponentName((String) originToscaElement.getMetadataValue(JsonPresentationFields.NAME)); - if (originToscaElement != null && dataDefinition.getToscaComponentName() == null) - dataDefinition.setToscaComponentName((String) originToscaElement.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME)); - if (dataDefinition.getOriginType() == null && originToscaElement != null) { - ResourceTypeEnum resourceType = originToscaElement.getResourceType(); - OriginTypeEnum originType = OriginTypeEnum.findByValue(resourceType.name()); - dataDefinition.setOriginType(originType); - } - if(dataDefinition.getOriginType() == OriginTypeEnum.ServiceProxy) - dataDefinition.setIsProxy(true); - - return dataDefinition; - } - - private Boolean isUniqueInstanceName(TopologyTemplate container, String instanceName) { - Boolean isUniqueName = true; - try { - isUniqueName = !container.getComponentInstances().values().stream().filter(ci -> ci.getName() != null && ci.getName().equals(instanceName)).findAny().isPresent(); - - } catch (Exception e) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during fetching component instance with name {} from component container {}. {} ", instanceName, container.getName(), e.getMessage()); - } - return isUniqueName; - } - - private String buildComponentInstanceName(String instanceSuffixNumber, String instanceName) { - return instanceName + " " + (instanceSuffixNumber == null ? 0 : instanceSuffixNumber); - } - - public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String componentId, RequirementCapabilityRelDef relation) { - List<RequirementCapabilityRelDef> relations = new ArrayList<>(); - relations.add(relation); - Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> associateResourceInstances = associateResourceInstances(componentId, relations); - if (associateResourceInstances.isRight()) { - return Either.right(associateResourceInstances.right().value()); - } - return Either.left(associateResourceInstances.left().value().get(0)); - } - - @SuppressWarnings({ "unchecked" }) - public <T extends ToscaDataDefinition> Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> associateResourceInstances(String componentId, List<RequirementCapabilityRelDef> relations) { - - Either<GraphVertex, TitanOperationStatus> containerVEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll); - if (containerVEither.isRight()) { - TitanOperationStatus error = containerVEither.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch container vertex {} error {}", componentId, error); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error)); - } - GraphVertex containerV = containerVEither.left().value(); - List<CapabilityRequirementRelationship> relationshipsResult = new ArrayList<>(); - Either<Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>>, StorageOperationStatus> capResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES); - if (capResult.isRight()) { - return Either.right(capResult.right().value()); - - } - Map<String, MapListCapabiltyDataDefinition> calculatedCapabilty = capResult.left().value().getRight(); - - Either<Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>>, StorageOperationStatus> capFullResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES); - if (capResult.isRight()) { - return Either.right(capResult.right().value()); - - } - Map<String, MapListCapabiltyDataDefinition> fullFilledCapabilty = capFullResult.left().value().getRight(); - - Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS); - if (reqResult.isRight()) { - return Either.right(reqResult.right().value()); - } - Map<String, MapListRequirementDataDefinition> calculatedRequirement = reqResult.left().value().getRight(); - - Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqFullResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS); - if (reqResult.isRight()) { - return Either.right(reqResult.right().value()); - } - Map<String, MapListRequirementDataDefinition> fullfilledRequirement = reqFullResult.left().value().getRight(); - - Map<String, CompositionDataDefinition> jsonComposition = (Map<String, CompositionDataDefinition>) containerV.getJson(); - CompositionDataDefinition compositionDataDefinition = jsonComposition.get(JsonConstantKeysEnum.COMPOSITION.getValue()); - - StorageOperationStatus status; - List<RequirementCapabilityRelDef> relationsList = new ArrayList<>(); - for (RequirementCapabilityRelDef relation : relations) { - - String fromNode = relation.getFromNode(); - String toNode = relation.getToNode(); - List<CapabilityRequirementRelationship> relationships = relation.getRelationships(); - if (relationships == null || relationships.isEmpty()) { - BeEcompErrorManager.getInstance().logBeFailedAddingResourceInstanceError("AssociateResourceInstances - missing relationship", fromNode, componentId); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No requirement definition sent in order to set the relation between {} to {}", fromNode, toNode); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); - } - - for (CapabilityRequirementRelationship immutablePair : relationships) { - String requirement = immutablePair.getRelation().getRequirement(); - - Either<Map<JsonPresentationFields, T>, StorageOperationStatus> associateRes = connectInstancesInContainer(fromNode, toNode, immutablePair.getRelation(), calculatedCapabilty, calculatedRequirement, fullFilledCapabilty, fullfilledRequirement, - compositionDataDefinition, containerV.getUniqueId()); - - if (associateRes.isRight()) { - status = associateRes.right().value(); - BeEcompErrorManager.getInstance().logBeFailedAddingResourceInstanceError("AssociateResourceInstances - missing relationship", fromNode, componentId); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to associate resource instance {} to resource instance {}. status is {}", fromNode, toNode, status); - return Either.right(status); - } - - RelationshipInstDataDefinition relationshipInstData = (RelationshipInstDataDefinition) associateRes.left().value().get(JsonPresentationFields.RELATIONSHIP); - RelationshipImpl relationshipImplResult = new RelationshipImpl(); - relationshipImplResult.setType(relationshipInstData.getType()); - RelationshipInfo requirementAndRelationshipPair = new RelationshipInfo(requirement, relationshipImplResult); - requirementAndRelationshipPair.setCapability(immutablePair.getRelation().getCapability()); - requirementAndRelationshipPair.setRequirement(immutablePair.getRelation().getRequirement()); - requirementAndRelationshipPair.setCapabilityOwnerId(relationshipInstData.getCapabilityOwnerId()); - requirementAndRelationshipPair.setRequirementOwnerId(relationshipInstData.getRequirementOwnerId()); - requirementAndRelationshipPair.setCapabilityUid(immutablePair.getRelation().getCapabilityUid()); - requirementAndRelationshipPair.setRequirementUid(immutablePair.getRelation().getRequirementUid()); - requirementAndRelationshipPair.setId(relationshipInstData.getUniqueId()); - CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship(); - capReqRel.setRelation(requirementAndRelationshipPair); - capReqRel.setCapability((CapabilityDataDefinition) associateRes.left().value().get(JsonPresentationFields.CAPAPILITY)); - capReqRel.setRequirement((RequirementDataDefinition) associateRes.left().value().get(JsonPresentationFields.REQUIREMENT)); - relationshipsResult.add(capReqRel); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "update customization UUID for from CI {} and to CI {}", relation.getFromNode(), relation.getToNode()); - status = updateCustomizationUUID(relation.getFromNode(), compositionDataDefinition); - if (status != StorageOperationStatus.OK) { - return Either.right(status); - } - status = updateCustomizationUUID(relation.getToNode(), compositionDataDefinition); - if (status != StorageOperationStatus.OK) { - return Either.right(status); - } - } - RequirementCapabilityRelDef capabilityRelDef = new RequirementCapabilityRelDef(); - capabilityRelDef.setFromNode(fromNode); - capabilityRelDef.setToNode(toNode); - capabilityRelDef.setRelationships(relationshipsResult); - relationsList.add(capabilityRelDef); - } - // update metadata of container and composition json - status = updateAllAndCalculatedCapReqOnGraph(componentId, containerV, capResult, capFullResult, reqResult, reqFullResult); - if (status != StorageOperationStatus.OK) { - return Either.right(status); - } - - return Either.left(relationsList); - } - - private StorageOperationStatus updateAllAndCalculatedCapReqOnGraph(String componentId, GraphVertex containerV, Either<Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>>, StorageOperationStatus> capResult, - Either<Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>>, StorageOperationStatus> capFullResult, Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqResult, - Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqFullResult) { - containerV.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); - Either<GraphVertex, TitanOperationStatus> updateElement = titanDao.updateVertex(containerV); - if (updateElement.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update topology template {} with new relations error {}. ", componentId, updateElement.right().value()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value()); - } - // update cap/req jsons, fulfilled cap/req jsons!!!!! - Either<GraphVertex, TitanOperationStatus> status; - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Update calculated capabilty for container {}", containerV.getUniqueId()); - status = updateOrCopyOnUpdate(capResult.left().value().getLeft(), containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES); - if (status.isRight()) { - TitanOperationStatus error = status.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update calculated capabilty for container {} error {}", containerV.getUniqueId(), error); - return DaoStatusConverter.convertTitanStatusToStorageStatus(error); - } - - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Update calculated requirement for container {}", containerV.getUniqueId()); - status = updateOrCopyOnUpdate(reqResult.left().value().getLeft(), containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS); - if (status.isRight()) { - TitanOperationStatus error = status.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update calculated requiremnt for container {} error {}", containerV.getUniqueId(), error); - return DaoStatusConverter.convertTitanStatusToStorageStatus(error); - } - - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Update fullfilled capabilty for container {}", containerV.getUniqueId()); - status = updateOrCopyOnUpdate(capFullResult.left().value().getLeft(), containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES); - if (status.isRight()) { - TitanOperationStatus error = status.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update fullfilled capabilty for container {} error {}", containerV.getUniqueId(), error); - return DaoStatusConverter.convertTitanStatusToStorageStatus(error); - } - - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Update fullfilled requirement for container {}", containerV.getUniqueId()); - status = updateOrCopyOnUpdate(reqFullResult.left().value().getLeft(), containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS); - if (status.isRight()) { - TitanOperationStatus error = status.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update fullfilled requirement for container {} error {}", containerV.getUniqueId(), error); - return DaoStatusConverter.convertTitanStatusToStorageStatus(error); - } - return StorageOperationStatus.OK; - } - - @SuppressWarnings({ "unchecked" }) - public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) { - if (requirementDef.getRelationships() == null) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No relation pair in request [ {} ]", requirementDef); - return Either.right(StorageOperationStatus.BAD_REQUEST); - } - - String fromResInstanceUid = requirementDef.getFromNode(); - String toResInstanceUid = requirementDef.getToNode(); - - Either<GraphVertex, TitanOperationStatus> containerVEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll); - if (containerVEither.isRight()) { - TitanOperationStatus error = containerVEither.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch container vertex {} error {}", componentId, error); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error)); - } - GraphVertex containerV = containerVEither.left().value(); - - // DE191707 - validations - Map<String, CompositionDataDefinition> jsonComposition = (Map<String, CompositionDataDefinition>) containerV.getJson(); - CompositionDataDefinition compositionDataDefinition = jsonComposition.get(JsonConstantKeysEnum.COMPOSITION.getValue()); - Map<String, ComponentInstanceDataDefinition> componentInstances = compositionDataDefinition.getComponentInstances(); - ComponentInstanceDataDefinition ciFrom = componentInstances.get(fromResInstanceUid); - if (ciFrom == null) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "FROM instance {} isn't under container {}", fromResInstanceUid, componentId); - return Either.right(StorageOperationStatus.NOT_FOUND); - - } - ComponentInstanceDataDefinition ciTo = componentInstances.get(toResInstanceUid); - if (ciFrom == ciTo) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "TO instance {} isn't under container {}", toResInstanceUid, componentId); - return Either.right(StorageOperationStatus.NOT_FOUND); - - } - Map<String, RelationshipInstDataDefinition> relations = compositionDataDefinition.getRelations(); - - List<CapabilityRequirementRelationship> relationPairList = requirementDef.getRelationships(); - Either<Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>>, StorageOperationStatus> capResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES); - if (capResult.isRight()) { - return Either.right(capResult.right().value()); - } - Map<String, MapListCapabiltyDataDefinition> calculatedCapability = capResult.left().value().getRight(); - - Either<Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>>, StorageOperationStatus> capFullResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES); - if (capResult.isRight()) { - return Either.right(capResult.right().value()); - - } - Map<String, MapListCapabiltyDataDefinition> fulfilledCapability = capFullResult.left().value().getRight(); - - Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS); - if (reqResult.isRight()) { - return Either.right(reqResult.right().value()); - } - Map<String, MapListRequirementDataDefinition> calculatedRequirement = reqResult.left().value().getRight(); - - Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqFullResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS); - if (reqResult.isRight()) { - return Either.right(reqResult.right().value()); - } - Map<String, MapListRequirementDataDefinition> fulfilledRequirement = reqFullResult.left().value().getRight(); - - for (CapabilityRequirementRelationship relationPair : relationPairList) { - Iterator<Entry<String, RelationshipInstDataDefinition>> iterator = relations.entrySet().iterator(); - boolean isDeleted = false; - while (iterator.hasNext()) { - Entry<String, RelationshipInstDataDefinition> entryInJson = iterator.next(); - RelationshipInstDataDefinition relationInJson = entryInJson.getValue(); - if (relationInJson.getFromId().equals(fromResInstanceUid) && relationInJson.getToId().equals(toResInstanceUid) && relationInJson.getUniqueId().equals(relationPair.getRelation().getId())) { - if (relationPair.getRelation().equalsTo(relationInJson)) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Remove relation from {} to {} capability {} capOwnerId {} reqOwnerId {} ", toResInstanceUid, componentId, relationInJson.getType(), - relationInJson.getCapabilityOwnerId(), relationInJson.getRequirementOwnerId()); - iterator.remove(); - - // update calculated cap/req - StorageOperationStatus status = updateCalculatedCapabiltyAfterDeleteRelation(calculatedCapability, fulfilledCapability, toResInstanceUid, relationInJson, relationPair); - if (status != StorageOperationStatus.OK) { - return Either.right(status); - } - status = updateCalculatedRequirementsAfterDeleteRelation(calculatedRequirement, fulfilledRequirement, fromResInstanceUid, relationInJson, relationPair); - if (status != StorageOperationStatus.OK) { - return Either.right(status); - } - isDeleted = true; - } - } - } - if (!isDeleted) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No relation to delete from {} to {} capabilty {} capOwnerId {} reqOwnerId {} ", toResInstanceUid, componentId, relationPair.getCapability(), - relationPair.getRelation().getCapabilityOwnerId(), relationPair.getRelation().getRequirementOwnerId()); - return Either.right(StorageOperationStatus.NOT_FOUND); - } - } - StorageOperationStatus status = updateCustomizationUUID(fromResInstanceUid, compositionDataDefinition); - if (status != StorageOperationStatus.OK) { - return Either.right(status); - } - status = updateCustomizationUUID(toResInstanceUid, compositionDataDefinition); - if (status != StorageOperationStatus.OK) { - return Either.right(status); - } - - // update jsons - // update metadata of container and composition json - status = updateAllAndCalculatedCapReqOnGraph(componentId, containerV, capResult, capFullResult, reqResult, reqFullResult); - if (status != StorageOperationStatus.OK) { - return Either.right(status); - } - - return Either.left(requirementDef); - } - - /** - * Retrieves fulfilled requirement according to relation and received predicate - * @param componentId - * @param instanceId - * @param foundRelation - * @param predicate - * @return - */ - public Either<RequirementDataDefinition, StorageOperationStatus> getFulfilledRequirementByRelation(String componentId, String instanceId, RequirementCapabilityRelDef foundRelation, BiPredicate<RelationshipInfo, RequirementDataDefinition> predicate) { - - Either<RequirementDataDefinition, StorageOperationStatus> result = null; - Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqFullResult = null; - MapListRequirementDataDefinition reqMapOfLists = null; - Optional<RequirementDataDefinition> foundRequirement; - RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation(); - Either<GraphVertex, TitanOperationStatus> containerVEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll); - if (containerVEither.isRight()) { - TitanOperationStatus error = containerVEither.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch container vertex {} error {}", componentId, error); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error)); - } - if(result == null){ - GraphVertex containerV = containerVEither.left().value(); - reqFullResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS); - if (reqFullResult.isRight()) { - result = Either.right(reqFullResult.right().value()); - } - } - if(result == null){ - Map<String, MapListRequirementDataDefinition> fulfilledRequirement = reqFullResult.left().value().getRight(); - reqMapOfLists = fulfilledRequirement.get(instanceId); - if(reqMapOfLists == null){ - result = Either.right(StorageOperationStatus.NOT_FOUND); - } - } - if(result == null && reqMapOfLists != null){ - for(ListRequirementDataDefinition requirements : reqMapOfLists.getMapToscaDataDefinition().values()){ - foundRequirement = requirements.getListToscaDataDefinition().stream().filter(req -> predicate.test(relationshipInfo, req)).findFirst(); - if(foundRequirement.isPresent()){ - result = Either.left(foundRequirement.get()); - } - } - } - return result; - } - - /** - * Retrieves fulfilled capability according to relation and received predicate - * @param componentId - * @param instanceId - * @param foundRelation - * @param predicate - * @return - */ - public Either<CapabilityDataDefinition, StorageOperationStatus> getFulfilledCapabilityByRelation(String componentId, String instanceId, RequirementCapabilityRelDef foundRelation, BiPredicate<RelationshipInfo, CapabilityDataDefinition> predicate) { - - Either<CapabilityDataDefinition, StorageOperationStatus> result = null; - Either<Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>>, StorageOperationStatus> capFullResult = null; - MapListCapabiltyDataDefinition capMapOfLists = null; - Optional<CapabilityDataDefinition> foundRequirement; - - RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation(); - Either<GraphVertex, TitanOperationStatus> containerVEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll); - if (containerVEither.isRight()) { - TitanOperationStatus error = containerVEither.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch container vertex {} error {}", componentId, error); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error)); - } - if(result == null){ - GraphVertex containerV = containerVEither.left().value(); - capFullResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES); - if (capFullResult.isRight()) { - result = Either.right(capFullResult.right().value()); - } - } - if(result == null){ - Map<String, MapListCapabiltyDataDefinition> fulfilledCapability = capFullResult.left().value().getRight(); - capMapOfLists = fulfilledCapability.get(instanceId); - if(capMapOfLists == null){ - result = Either.right(StorageOperationStatus.NOT_FOUND); - } - } - if(result == null && capMapOfLists != null){ - for(ListCapabilityDataDefinition capabilities : capMapOfLists.getMapToscaDataDefinition().values()){ - foundRequirement = capabilities.getListToscaDataDefinition().stream().filter(cap -> predicate.test(relationshipInfo, cap)).findFirst(); - if(foundRequirement.isPresent()){ - result = Either.left(foundRequirement.get()); - } - } - } - return result; - } - - private StorageOperationStatus updateCalculatedRequirementsAfterDeleteRelation(Map<String, MapListRequirementDataDefinition> calculatedRequirement, Map<String, MapListRequirementDataDefinition> fullFilledRequirement, String fromResInstanceUid, - RelationshipInstDataDefinition relation, CapabilityRequirementRelationship relationship) { - StorageOperationStatus status; - String hereIsTheKey = null; - MapListRequirementDataDefinition reqByInstance = calculatedRequirement.get(fromResInstanceUid); - if (reqByInstance == null || reqByInstance.findKeyByItemUidMatch(relation.getRequirementId()) == null) { - // move from fulfilled - status = moveFromFullFilledRequirement(calculatedRequirement, fullFilledRequirement, fromResInstanceUid, relation, hereIsTheKey, relationship); - } else { - hereIsTheKey = reqByInstance.findKeyByItemUidMatch(relation.getRequirementId()); - ListRequirementDataDefinition reqByType = reqByInstance.findByKey(hereIsTheKey); - Optional<RequirementDataDefinition> requirementOptional = reqByType.getListToscaDataDefinition().stream() - .filter(req -> req.getOwnerId().equals(relation.getRequirementOwnerId()) && req.getName().equals(relation.getRequirement()) && req.getUniqueId().equals(relation.getRequirementId())).findFirst(); - - if (requirementOptional.isPresent()) { - - RequirementDataDefinition requirement = requirementOptional.get(); - String leftOccurrences = requirement.getLeftOccurrences(); - if (leftOccurrences != null && !leftOccurrences.equals(RequirementDataDefinition.MAX_OCCURRENCES)) { - Integer leftIntValue = Integer.parseInt(leftOccurrences); - ++leftIntValue; - requirement.setLeftOccurrences(String.valueOf(leftIntValue)); - } - if(relationship != null){ - relationship.setRequirement(requirement); - } - status = StorageOperationStatus.OK; - } else { - // move from fulfilled - status = moveFromFullFilledRequirement(calculatedRequirement, fullFilledRequirement, fromResInstanceUid, relation, hereIsTheKey, relationship); - } - } - return status; - } - - private StorageOperationStatus updateCalculatedCapabiltyAfterDeleteRelation(Map<String, MapListCapabiltyDataDefinition> calculatedCapability, Map<String, MapListCapabiltyDataDefinition> fullFilledCapability, String toResInstanceUid, - RelationshipInstDataDefinition relation, CapabilityRequirementRelationship relationship) { - StorageOperationStatus status; - String hereIsTheKey = null; - MapListCapabiltyDataDefinition capByInstance = calculatedCapability.get(toResInstanceUid); - if (capByInstance == null || capByInstance.findKeyByItemUidMatch(relation.getCapabilityId()) == null) { - // move from fulfilled - status = moveFromFullFilledCapabilty(calculatedCapability, fullFilledCapability, toResInstanceUid, relation, hereIsTheKey, relationship); - } else { - hereIsTheKey = capByInstance.findKeyByItemUidMatch(relation.getCapabilityId()); - ListCapabilityDataDefinition capByType = capByInstance.findByKey(hereIsTheKey); - Optional<CapabilityDataDefinition> capabilityOptional = capByType.getListToscaDataDefinition().stream().filter(cap -> cap.getOwnerId().equals(relation.getCapabilityOwnerId()) && cap.getUniqueId().equals(relation.getCapabilityId())) - .findFirst(); - - if (capabilityOptional.isPresent()) { - - CapabilityDataDefinition capability = capabilityOptional.get(); - String leftOccurrences = capability.getLeftOccurrences(); - if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) { - Integer leftIntValue = Integer.parseInt(leftOccurrences); - ++leftIntValue; - capability.setLeftOccurrences(String.valueOf(leftIntValue)); - } - if(relationship != null){ - relationship.setCapability(capability); - } - status = StorageOperationStatus.OK; - } else { - // move from fulfilled - status = moveFromFullFilledCapabilty(calculatedCapability, fullFilledCapability, toResInstanceUid, relation, hereIsTheKey, relationship); - } - } - return status; - } - - private StorageOperationStatus moveFromFullFilledCapabilty(Map<String, MapListCapabiltyDataDefinition> calculatedCapability, Map<String, MapListCapabiltyDataDefinition> fullFilledCapability, String toResInstanceUid, - RelationshipInstDataDefinition relation, String hereIsTheKey, CapabilityRequirementRelationship relationship) { - MapListCapabiltyDataDefinition capByInstance = fullFilledCapability.get(toResInstanceUid); - if (capByInstance == null) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No capability in fulfilled list for instance {} ", toResInstanceUid); - return StorageOperationStatus.GENERAL_ERROR; - } - if (null == hereIsTheKey) - hereIsTheKey = capByInstance.findKeyByItemUidMatch(relation.getCapabilityId()); - if (null == hereIsTheKey) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No capability with id {} in fulfilled list for instance {} ", relation.getCapabilityId(), toResInstanceUid); - return StorageOperationStatus.GENERAL_ERROR; - } - ListCapabilityDataDefinition capByType = capByInstance.findByKey(hereIsTheKey); - Iterator<CapabilityDataDefinition> iterator = capByType.getListToscaDataDefinition().iterator(); - boolean found = false; - while (iterator.hasNext()) { - CapabilityDataDefinition cap = iterator.next(); - if (cap.getOwnerId().equals(relation.getCapabilityOwnerId()) && cap.getUniqueId().equals(relation.getCapabilityId())) { - found = true; - iterator.remove(); - // return to calculated list - String leftOccurrences = cap.getLeftOccurrences(); - Integer leftIntValue = Integer.parseInt(leftOccurrences); - ++leftIntValue; - cap.setLeftOccurrences(String.valueOf(leftIntValue)); - - MapListCapabiltyDataDefinition mapListCapaDataDef = calculatedCapability.get(toResInstanceUid); - if (mapListCapaDataDef == null) { - mapListCapaDataDef = new MapListCapabiltyDataDefinition(); - } - ListCapabilityDataDefinition findByKey = mapListCapaDataDef.findByKey(hereIsTheKey); - if (findByKey == null) { - findByKey = new ListCapabilityDataDefinition(); - mapListCapaDataDef.put(hereIsTheKey, findByKey); - } - findByKey.add(cap); - if(relationship!= null) - relationship.setCapability(cap); - break; - } - } - if (found == false) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No capability type {} with ownerId {} in fulfilled list for instance {} ", hereIsTheKey, relation.getCapabilityOwnerId(), toResInstanceUid); - return StorageOperationStatus.GENERAL_ERROR; - } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus moveFromFullFilledRequirement(Map<String, MapListRequirementDataDefinition> calculatedRequirement, Map<String, MapListRequirementDataDefinition> fullFilledRequirement, String fromResInstanceUid, - RelationshipInstDataDefinition relation, String hereIsTheKey, CapabilityRequirementRelationship relationship) { - MapListRequirementDataDefinition reqByInstance = fullFilledRequirement.get(fromResInstanceUid); - if (reqByInstance == null) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No requirement in fullfilled list for instance {} ", fromResInstanceUid); - return StorageOperationStatus.GENERAL_ERROR; - } - if (null == hereIsTheKey) - hereIsTheKey = reqByInstance.findKeyByItemUidMatch(relation.getRequirementId()); - if (null == hereIsTheKey) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No requirement with id {} in fulfilled list for instance {} ", relation.getRequirementId(), fromResInstanceUid); - return StorageOperationStatus.GENERAL_ERROR; - } - ListRequirementDataDefinition reqByType = reqByInstance.findByKey(hereIsTheKey); - Iterator<RequirementDataDefinition> iterator = reqByType.getListToscaDataDefinition().iterator(); - boolean found = false; - while (iterator.hasNext()) { - RequirementDataDefinition req = iterator.next(); - if (req.getOwnerId().equals(relation.getRequirementOwnerId()) && req.getName().equals(relation.getRequirement()) && req.getUniqueId().equals(relation.getRequirementId())) { - found = true; - iterator.remove(); - // return to calculated list - String leftOccurrences = req.getLeftOccurrences(); - Integer leftIntValue = Integer.parseInt(leftOccurrences); - ++leftIntValue; - req.setLeftOccurrences(String.valueOf(leftIntValue)); - - MapListRequirementDataDefinition mapListReqDataDef = calculatedRequirement.get(fromResInstanceUid); - if (mapListReqDataDef == null) { - mapListReqDataDef = new MapListRequirementDataDefinition(); - } - ListRequirementDataDefinition findByKey = mapListReqDataDef.findByKey(hereIsTheKey); - if (findByKey == null) { - findByKey = new ListRequirementDataDefinition(); - mapListReqDataDef.put(hereIsTheKey, findByKey); - } - findByKey.add(req); - if(relationship!= null) - relationship.setRequirement(req); - break; - } - } - if (found == false) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No requirement type {} with ownerId {} in fulfilled list for instance {} ", hereIsTheKey, relation.getRequirementOwnerId(), fromResInstanceUid); - return StorageOperationStatus.GENERAL_ERROR; - } - return StorageOperationStatus.OK; - - } - - public StorageOperationStatus updateCustomizationUUID(String componentInstanceId, CompositionDataDefinition compositionDataDefinition) { - ComponentInstanceDataDefinition componentInstance = compositionDataDefinition.getComponentInstances().get(componentInstanceId); - - if (componentInstance == null) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch component instance by id {} from map of instances ", componentInstanceId); - return StorageOperationStatus.NOT_FOUND; - } - UUID uuid = UUID.randomUUID(); - componentInstance.setCustomizationUUID(uuid.toString()); - - return StorageOperationStatus.OK; - } - - public <T extends ToscaDataDefinition> Either<Map<JsonPresentationFields, T>, StorageOperationStatus> connectInstancesInContainer(String fromResInstanceUid, String toResInstanceUid, RelationshipInfo relationPair, - Map<String, MapListCapabiltyDataDefinition> calculatedCapabilty, Map<String, MapListRequirementDataDefinition> calculatedRequirement, Map<String, MapListCapabiltyDataDefinition> fullfilledCapabilty, - Map<String, MapListRequirementDataDefinition> fullfilledRequirement, CompositionDataDefinition compositionDataDefinition, String containerId) { - String requirement = relationPair.getRequirement(); - Map<String, ComponentInstanceDataDefinition> componentInstances = compositionDataDefinition.getComponentInstances(); - - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Going to associate resource instance {} to resource instance {} under component {}. Requirement is {}.", fromResInstanceUid, toResInstanceUid, containerId, requirement); - - ComponentInstanceDataDefinition fromResourceInstData = componentInstances.get(fromResInstanceUid); - if (fromResourceInstData == null) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to find from resource instance {}.", fromResInstanceUid); - return Either.right(StorageOperationStatus.NOT_FOUND); - } - ComponentInstanceDataDefinition toResourceInstData = componentInstances.get(toResInstanceUid); - if (toResourceInstData == null) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to find to resource instance {}.", toResInstanceUid); - return Either.right(StorageOperationStatus.NOT_FOUND); - } - - Either<Map<JsonPresentationFields, T>, StorageOperationStatus> reqVsCap = connectRequirementVsCapability(fromResourceInstData, toResourceInstData, relationPair, calculatedCapabilty, calculatedRequirement, fullfilledCapabilty, - fullfilledRequirement, containerId); - if (reqVsCap.isRight()) { - StorageOperationStatus status = reqVsCap.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to connect requirement {} between resource instance {} to resource instance {}. status is {}", requirement, fromResInstanceUid, toResInstanceUid, status); - return Either.right(status); - } - Map<JsonPresentationFields, T> relationship = reqVsCap.left().value(); - - // add to json new relations - compositionDataDefinition.addRelation(((RelationshipInstDataDefinition)relationship.get(JsonPresentationFields.RELATIONSHIP)).getUniqueId(), (RelationshipInstDataDefinition)relationship.get(JsonPresentationFields.RELATIONSHIP)); - - return Either.left(relationship); - } - - private Either<Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>>, StorageOperationStatus> fetchContainerCalculatedCapability(GraphVertex containerV, EdgeLabelEnum capLabel) { - - Either<Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>>, TitanOperationStatus> calculatedCapabiltyEither = getDataAndVertexFromGraph(containerV, capLabel); - if (calculatedCapabiltyEither.isRight()) { - TitanOperationStatus error = calculatedCapabiltyEither.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch calculated capabilties for container {}.", containerV.getUniqueId(), error); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error)); - } - Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>> calculatedCapabilty = calculatedCapabiltyEither.left().value(); - return Either.left(calculatedCapabilty); - } - - private Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> fetchContainerCalculatedRequirement(GraphVertex containerV, EdgeLabelEnum reqLabel) { - Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, TitanOperationStatus> calculatedRequirementEither = getDataAndVertexFromGraph(containerV, reqLabel); - if (calculatedRequirementEither.isRight()) { - TitanOperationStatus error = calculatedRequirementEither.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch calculated requirements for container {}.", containerV.getUniqueId(), error); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error)); - } - Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>> calculatedRequirement = calculatedRequirementEither.left().value(); - return Either.left(calculatedRequirement); - } - - @SuppressWarnings("unchecked") - private <T extends ToscaDataDefinition> Either<Map<JsonPresentationFields, T>, StorageOperationStatus> connectRequirementVsCapability(ComponentInstanceDataDefinition fromResInstance, ComponentInstanceDataDefinition toResInstance, RelationshipInfo relationPair, - Map<String, MapListCapabiltyDataDefinition> calculatedCapabilty, Map<String, MapListRequirementDataDefinition> calculatedRequirement, Map<String, MapListCapabiltyDataDefinition> fullfilledCapabilty, - Map<String, MapListRequirementDataDefinition> fullfilledRequirement, String containerId) { - String type = relationPair.getRelationship().getType(); - // capability - - String toInstId = toResInstance.getUniqueId(); - MapListCapabiltyDataDefinition mapListCapabiltyDataDefinition = calculatedCapabilty.get(toInstId); - Map<JsonPresentationFields, T> capReqRelationship = new EnumMap<>(JsonPresentationFields.class); - - if (mapListCapabiltyDataDefinition == null) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch calculated capabilities for instance {} in container {}.", toInstId, containerId); - return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); - } - ListCapabilityDataDefinition listCapabilityDataDefinition = mapListCapabiltyDataDefinition.getMapToscaDataDefinition().get(type); - if (listCapabilityDataDefinition == null) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch calculated capabilities for type {} for instance {} in container {}.", type, toInstId, containerId); - return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); - } - CapabilityDataDefinition capabilityForRelation = null; - Iterator<CapabilityDataDefinition> iteratorCap = listCapabilityDataDefinition.getListToscaDataDefinition().iterator(); - while (iteratorCap.hasNext()) { - CapabilityDataDefinition cap = iteratorCap.next(); - if (cap.getUniqueId().equals(relationPair.getCapabilityUid()) && cap.getOwnerId().equals(relationPair.getCapabilityOwnerId())) { - capabilityForRelation = cap; - capReqRelationship.put(JsonPresentationFields.CAPAPILITY, (T)capabilityForRelation); - String leftOccurrences = cap.getLeftOccurrences(); - if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) { - Integer leftIntValue = Integer.parseInt(leftOccurrences); - if (leftIntValue > 0) { - --leftIntValue; - capabilityForRelation.setLeftOccurrences(String.valueOf(leftIntValue)); - if (leftIntValue == 0) { - // remove from calculated - iteratorCap.remove(); - // move to fulfilled - MapListCapabiltyDataDefinition mapListCapabiltyFullFilledInst = fullfilledCapabilty.get(toInstId); - if (mapListCapabiltyFullFilledInst == null) { - mapListCapabiltyFullFilledInst = new MapListCapabiltyDataDefinition(); - fullfilledCapabilty.put(toInstId, mapListCapabiltyFullFilledInst); - } - - ListCapabilityDataDefinition listCapabilityFull = mapListCapabiltyFullFilledInst.findByKey(type); - if (listCapabilityFull == null) { - listCapabilityFull = new ListCapabilityDataDefinition(); - mapListCapabiltyFullFilledInst.put(type, listCapabilityFull); - } - listCapabilityFull.add(capabilityForRelation); - } - break; - } else { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No left occurrences capabilty {} to {} in container {}.", capabilityForRelation.getType(), toInstId, containerId); - return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); - } - } - } - } - if (capabilityForRelation == null) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch capabilty for type {} for instance {} in container {}.", type, toInstId, containerId); - return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); - } - - // requirements - String fromInstId = fromResInstance.getUniqueId(); - MapListRequirementDataDefinition mapListRequirementDataDefinition = calculatedRequirement.get(fromInstId); - if (mapListRequirementDataDefinition == null) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch calculated requirements for instance {} in container {}.", fromInstId, containerId); - return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); - } - ListRequirementDataDefinition listRequirementDataDefinition = mapListRequirementDataDefinition.getMapToscaDataDefinition().get(type); - if (listRequirementDataDefinition == null) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch calculated requirements for type {} for instance {} in container {}.", type, fromInstId, containerId); - return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); - } - - RequirementDataDefinition requirementForRelation = null; - Iterator<RequirementDataDefinition> iteratorReq = listRequirementDataDefinition.getListToscaDataDefinition().iterator(); - while (iteratorReq.hasNext()) { - RequirementDataDefinition req = iteratorReq.next(); - if (req.getUniqueId().equals(relationPair.getRequirementUid()) && req.getOwnerId().equals(relationPair.getRequirementOwnerId())) { - requirementForRelation = req; - capReqRelationship.put(JsonPresentationFields.REQUIREMENT, (T)requirementForRelation); - String leftOccurrences = req.getLeftOccurrences(); - if (leftOccurrences != null && !leftOccurrences.equals(RequirementDataDefinition.MAX_OCCURRENCES)) { - Integer leftIntValue = Integer.parseInt(leftOccurrences); - if (leftIntValue > 0) { - --leftIntValue; - req.setLeftOccurrences(String.valueOf(leftIntValue)); - if (leftIntValue == 0) { - // remove from calculated - iteratorReq.remove(); - // move to fulfilled - MapListRequirementDataDefinition mapListRequirementFullFilledInst = fullfilledRequirement.get(fromInstId); - if (mapListRequirementFullFilledInst == null) { - mapListRequirementFullFilledInst = new MapListRequirementDataDefinition(); - fullfilledRequirement.put(fromInstId, mapListRequirementFullFilledInst); - } - - ListRequirementDataDefinition listRequirementFull = mapListRequirementFullFilledInst.findByKey(type); - if (listRequirementFull == null) { - listRequirementFull = new ListRequirementDataDefinition(); - mapListRequirementFullFilledInst.put(type, listRequirementFull); - } - listRequirementFull.add(requirementForRelation); - } - break; - } else { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No left occurrences requirement {} from {} to {} in container {}.", requirementForRelation.getCapability(), fromInstId, toInstId, containerId); - return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); - } - } - } - } - 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 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); - } - - RelationshipInstDataDefinition relationshipTypeData = buildRelationshipInstData(fromInstId, toInstId, relationPair); - if(requirementForRelation.getRelationship() != null) - relationshipTypeData.setType(requirementForRelation.getRelationship()); - capReqRelationship.put(JsonPresentationFields.RELATIONSHIP, (T)relationshipTypeData); - return Either.left(capReqRelationship); - } - - private RelationshipInstDataDefinition buildRelationshipInstData(String fromResInstanceUid, String toInstId, RelationshipInfo relationPair) { - - RelationshipInstDataDefinition relationshipInstData = new RelationshipInstDataDefinition(); - relationshipInstData.setUniqueId(UniqueIdBuilder.buildRelationsipInstInstanceUid(fromResInstanceUid, toInstId)); - - relationshipInstData.setType(relationPair.getRelationship().getType()); - Long creationDate = System.currentTimeMillis(); - relationshipInstData.setCreationTime(creationDate); - relationshipInstData.setModificationTime(creationDate); - relationshipInstData.setCapabilityOwnerId(relationPair.getCapabilityOwnerId()); - relationshipInstData.setRequirementOwnerId(relationPair.getRequirementOwnerId()); - relationshipInstData.setCapabilityId(relationPair.getCapabilityUid()); - relationshipInstData.setRequirementId(relationPair.getRequirementUid()); - relationshipInstData.setFromId(fromResInstanceUid); - relationshipInstData.setToId(toInstId); - relationshipInstData.setRequirement(relationPair.getRequirement()); - relationshipInstData.setCapability(relationPair.getCapability()); - - return relationshipInstData; - } - - public StorageOperationStatus associateComponentInstancesToComponent(Component containerComponent, Map<ComponentInstance, Resource> resourcesInstancesMap, GraphVertex containerVertex, boolean allowDeleted) { - - StorageOperationStatus result = null; - String containerId = containerComponent.getUniqueId(); - Map<String, ComponentInstanceDataDefinition> instancesJsonData = null; - Either<GraphVertex, TitanOperationStatus> updateElement = null; - if (!validateInstanceNames(resourcesInstancesMap)) { - result = StorageOperationStatus.INCONSISTENCY; - } - if (result == null) { - if (!validateInstanceNames(resourcesInstancesMap)) { - result = StorageOperationStatus.INCONSISTENCY; - } - } - if (result == null && !allowDeleted) { - if (!validateDeletedResources(resourcesInstancesMap)) { - result = StorageOperationStatus.INCONSISTENCY; - } - } - if (result == null) { - instancesJsonData = convertToComponentInstanceDataDefinition(resourcesInstancesMap, containerId); - } - if (result == null && MapUtils.isNotEmpty(instancesJsonData)) { - containerVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); - Map<String, CompositionDataDefinition> compositions = new HashMap<>(); - CompositionDataDefinition composition = new CompositionDataDefinition(); - composition.setComponentInstances(instancesJsonData); - compositions.put(JsonConstantKeysEnum.COMPOSITION.getValue(), composition); - containerVertex.setJson(compositions); - updateElement = titanDao.updateVertex(containerVertex); - if (updateElement.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update topology template {} with new component instances. ", containerComponent.getName()); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value()); - } - } - if (result == null) { - result = StorageOperationStatus.OK; - } - return result; - } - - private Map<String, ComponentInstanceDataDefinition> convertToComponentInstanceDataDefinition(Map<ComponentInstance, Resource> resourcesInstancesMap, String containerId) { - - Map<String, ComponentInstanceDataDefinition> instances = new HashMap<>(); - for (Entry<ComponentInstance, Resource> entry : resourcesInstancesMap.entrySet()) { - ComponentInstanceDataDefinition instance = buildComponentInstanceDataDefinition(entry.getKey(), containerId, null, true, ModelConverter.convertToToscaElement(entry.getValue())); - instances.put(instance.getUniqueId(), instance); - } - return instances; - } - - private boolean validateDeletedResources(Map<ComponentInstance, Resource> resourcesInstancesMap) { - boolean result = true; - for (Resource resource : resourcesInstancesMap.values()) { - if (resource.getIsDeleted() != null && resource.getIsDeleted()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Component {} is already deleted. Cannot add component instance. ", resource.getName()); - result = false; - break; - } - } - return result; - } - - private boolean validateInstanceNames(Map<ComponentInstance, Resource> resourcesInstancesMap) { - boolean result = true; - Set<String> names = new HashSet<>(); - for (ComponentInstance instance : resourcesInstancesMap.keySet()) { - if (StringUtils.isEmpty(instance.getName())) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Component instance {} name is empty. Cannot add component instance. ", instance.getUniqueId()); - result = false; - break; - } else if (names.contains(instance.getName())) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Component instance with the name {} already exsists. Cannot add component instance. ", instance.getName()); - result = false; - break; - } else { - names.add(instance.getName()); - } - } - return result; - } - - public StorageOperationStatus addDeploymentArtifactsToInstance(String toscaElementId, String instanceId, Map<String, ArtifactDataDefinition> instDeplArtifacts) { - return addArtifactsToInstance(toscaElementId, instanceId, instDeplArtifacts, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS); - } - - public StorageOperationStatus addInformationalArtifactsToInstance(String toscaElementId, String instanceId, Map<String, ArtifactDataDefinition> instDeplArtifacts) { - return addArtifactsToInstance(toscaElementId, instanceId, instDeplArtifacts, EdgeLabelEnum.INSTANCE_ARTIFACTS, VertexTypeEnum.INSTANCE_ARTIFACTS); - } - - public StorageOperationStatus addArtifactsToInstance(String toscaElementId, String instanceId, Map<String, ArtifactDataDefinition> instDeplArtifacts, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexType) { - Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(toscaElementId, JsonParseFlagEnum.NoParse); - if (metadataVertex.isRight()) { - TitanOperationStatus status = metadataVertex.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - return DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - MapArtifactDataDefinition instArtifacts = new MapArtifactDataDefinition(instDeplArtifacts); - return addToscaDataDeepElementsBlockToToscaElement(metadataVertex.left().value(), edgeLabel, vertexType, instArtifacts, instanceId); - - } - - @SuppressWarnings({ "unchecked" }) - public StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId) { - Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll); - if (metadataVertex.isRight()) { - TitanOperationStatus status = metadataVertex.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - return DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - GraphVertex metaVertex = metadataVertex.left().value(); - Map<String, CompositionDataDefinition> json = (Map<String, CompositionDataDefinition>) metaVertex.getJson(); - CompositionDataDefinition compositionDataDefinition = json.get(JsonConstantKeysEnum.COMPOSITION.getValue()); - StorageOperationStatus status = updateCustomizationUUID(instanceId, compositionDataDefinition); - if (status != StorageOperationStatus.OK) { - logger.debug("Failed to update customization UUID for instance {} in component {} error {}", instanceId, componentId, status); - return status; - } - Either<GraphVertex, TitanOperationStatus> updateVertex = titanDao.updateVertex(metaVertex); - if (updateVertex.isRight()) { - logger.debug("Failed to update vertex of component {} error {}", componentId, updateVertex.right().value()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(updateVertex.right().value()); - } - return StorageOperationStatus.OK; - } - - public StorageOperationStatus generateCustomizationUUIDOnInstanceGroup(String componentId, String instanceId, List<String> groupInstances) { - if (groupInstances != null) { - Either<Map<String, MapGroupsDataDefinition>, TitanOperationStatus> dataFromGraph = getDataFromGraph(componentId, EdgeLabelEnum.INST_GROUPS); - if (dataFromGraph.isRight()) { - return DaoStatusConverter.convertTitanStatusToStorageStatus(dataFromGraph.right().value()); - } - MapGroupsDataDefinition grInstPerInstance = dataFromGraph.left().value().get(instanceId); - if (grInstPerInstance == null) { - logger.debug("No instance groups for instance {} in component {}", instanceId, componentId); - return StorageOperationStatus.NOT_FOUND; - } - for (String instGroupForUpdate : groupInstances) { - GroupInstanceDataDefinition groupInst = grInstPerInstance.findByKey(instGroupForUpdate); - if (groupInst == null) { - logger.debug("No group instance {} in group list for instance {} in component {}", instGroupForUpdate, instanceId, componentId); - continue; - } - UUID uuid = UUID.randomUUID(); - groupInst.setCustomizationUUID(uuid.toString()); - } - - } - return StorageOperationStatus.OK; - } - - public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupInstance> groupInstances) { - - return addToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, - new MapDataDefinition<>(groupInstances.stream().collect(Collectors.toMap(gi -> gi.getName(), gi -> gi))), componentInstance.getUniqueId()); - } - - public StorageOperationStatus addDeploymentArtifactsToComponentInstance(Component containerComponent, ComponentInstance componentInstance, Map<String, ArtifactDefinition> deploymentArtifacts) { - - return addToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, new MapDataDefinition<>(deploymentArtifacts), - componentInstance.getUniqueId()); - } - - public StorageOperationStatus updateComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) { - - List<String> pathKeys = new ArrayList<>(); - pathKeys.add(componentInstanceId); - return updateToscaDataDeepElementOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, property, pathKeys, JsonPresentationFields.NAME); - } - - public StorageOperationStatus updateComponentInstanceCapabilityProperty(Component containerComponent, String componentInstanceId, String capabilityUniqueId, ComponentInstanceProperty property) { - List<String> pathKeys = new ArrayList<>(); - pathKeys.add(componentInstanceId); - pathKeys.add(capabilityUniqueId); - 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); - return addToscaDataDeepElementToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, property, pathKeys, JsonPresentationFields.NAME); - } - - public StorageOperationStatus updateComponentInstanceProperties(Component containerComponent, String componentInstanceId, List<ComponentInstanceProperty> properties) { - List<String> pathKeys = new ArrayList<>(); - pathKeys.add(componentInstanceId); - return updateToscaDataDeepElementsOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, properties, pathKeys, JsonPresentationFields.NAME); - } - - public StorageOperationStatus updateComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) { - - List<String> pathKeys = new ArrayList<>(); - pathKeys.add(componentInstanceId); - return updateToscaDataDeepElementOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, property, pathKeys, JsonPresentationFields.NAME); - } - - public StorageOperationStatus updateComponentInstanceInputs(Component containerComponent, String componentInstanceId, List<ComponentInstanceInput> properties) { - List<String> pathKeys = new ArrayList<>(); - pathKeys.add(componentInstanceId); - return updateToscaDataDeepElementsOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, properties, pathKeys, JsonPresentationFields.NAME); - } - - public StorageOperationStatus addComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) { - List<String> pathKeys = new ArrayList<>(); - pathKeys.add(componentInstanceId); - return addToscaDataDeepElementToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, property, pathKeys, JsonPresentationFields.NAME); - } - + private static final String ARTIFACT_PLACEHOLDER_DISPLAY_NAME = "displayName"; + private static final Object ARTIFACT_PLACEHOLDER_DESCRIPTION = "description"; + public static final String HEAT_ENV_NAME = "heatEnv"; + public static final String HEAT_VF_ENV_NAME = "VfHeatEnv"; + public static final String HEAT_ENV_SUFFIX = "env"; + private static Integer defaultHeatTimeout; + public static final Integer NON_HEAT_TIMEOUT = 0; + + private static final Logger log = Logger.getLogger(NodeTemplateOperation.class.getName()); + + public NodeTemplateOperation() { + defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes(); + if ((defaultHeatTimeout == null) || (defaultHeatTimeout < 1)) { + defaultHeatTimeout = 60; + } + } + + public static Integer getDefaultHeatTimeout() { + return defaultHeatTimeout; + } + + public Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addComponentInstanceToTopologyTemplate(TopologyTemplate container, ToscaElement originToscaElement, String instanceNumberSuffix, ComponentInstance componentInstance, + boolean allowDeleted, User user) { + + Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> result = null; + Either<TopologyTemplate, StorageOperationStatus> addComponentInstanceRes = null; + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to create component instance {} in component {}", componentInstance, container.getUniqueId()); + ComponentInstanceDataDefinition componentInstanceData = null; + Either<String, StorageOperationStatus> newInstanceNameRes = null; + + Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(container.getUniqueId(), JsonParseFlagEnum.ParseJson); + if (metadataVertex.isRight()) { + TitanOperationStatus status = metadataVertex.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + + if (result == null) { + + newInstanceNameRes = buildValidateInstanceName(container, originToscaElement, componentInstance, instanceNumberSuffix); + if (newInstanceNameRes.isRight()) { + result = Either.right(newInstanceNameRes.right().value()); + } + } + if (result == null) { + componentInstanceData = buildComponentInstanceDataDefinition(componentInstance, container.getUniqueId(), newInstanceNameRes.left().value(), true, originToscaElement); + + addComponentInstanceRes = addComponentInstanceToTopologyTemplate(container, originToscaElement, componentInstanceData, metadataVertex.left().value(), allowDeleted, user); + + if (addComponentInstanceRes.isRight()) { + StorageOperationStatus status = addComponentInstanceRes.right().value(); + if (status == StorageOperationStatus.NOT_FOUND) { + status = StorageOperationStatus.INVALID_ID; + } + result = Either.right(status); + } + if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) { + TopologyTemplate updatedContainer = addComponentInstanceRes.left().value(); + result = addServerCapAndReqToProxyServerInstance(updatedContainer, componentInstance, componentInstanceData); + + } + } + if (result == null) { + result = Either.left(new ImmutablePair<>(addComponentInstanceRes.left().value(), componentInstanceData.getUniqueId())); + } + return result; + } + + private Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addServerCapAndReqToProxyServerInstance(TopologyTemplate updatedContainer, ComponentInstance componentInstance, + + ComponentInstanceDataDefinition componentInstanceData) { + + Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> result; + + Map<String, MapListCapabilityDataDefinition> calcCap = updatedContainer.getCalculatedCapabilities(); + Map<String, MapListRequirementDataDefinition> calcReg = updatedContainer.getCalculatedRequirements(); + Map<String, MapCapabilityProperty> calcCapProp = updatedContainer.getCalculatedCapabilitiesProperties(); + + Map<String, List<CapabilityDefinition>> additionalCap = componentInstance.getCapabilities(); + Map<String, List<RequirementDefinition>> additionalReq = componentInstance.getRequirements(); + + MapListCapabilityDataDefinition allCalculatedCap = calcCap == null || !calcCap.containsKey(componentInstanceData.getUniqueId()) ? new MapListCapabilityDataDefinition() : calcCap.get(componentInstanceData.getUniqueId()); + /******** capability ****************************/ + StorageOperationStatus status = deleteToscaDataDeepElementsBlockOfToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, componentInstanceData.getUniqueId()); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove calculated capabilty for instance {} in container {}. error {] ", componentInstanceData.getUniqueId(), updatedContainer.getUniqueId(), status); + return Either.right(status); + } + + if (additionalCap != null && !additionalCap.isEmpty()) { + + Map<String, ListCapabilityDataDefinition> serverCap = additionalCap.entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, en -> new ListCapabilityDataDefinition(en.getValue().stream().map(CapabilityDataDefinition::new).collect(Collectors.toList())))); + + serverCap.entrySet().forEach(entryPerType -> { + entryPerType.getValue().getListToscaDataDefinition().forEach(cap -> { + cap.addToPath(componentInstance.getUniqueId()); + allCalculatedCap.add(entryPerType.getKey(), cap); + }); + }); + + status = addToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, allCalculatedCap, componentInstance.getUniqueId()); + + /******** capability property ****************************/ + status = deleteToscaDataDeepElementsBlockOfToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, componentInstanceData.getUniqueId()); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove calculated capabilty properties for instance {} in container {}. error {] ", componentInstanceData.getUniqueId(), updatedContainer.getUniqueId(), status); + return Either.right(status); + } + + MapCapabilityProperty allCalculatedCapProp = calcCapProp == null || !calcCapProp.containsKey(componentInstanceData.getUniqueId()) ? new MapCapabilityProperty() : calcCapProp.get(componentInstanceData.getUniqueId()); + + additionalCap.forEach(new BiConsumer<String, List<CapabilityDefinition>>() { + @Override + public void accept(String s, List<CapabilityDefinition> caps) { + + if (caps != null && !caps.isEmpty()) { + + MapPropertiesDataDefinition dataToCreate = new MapPropertiesDataDefinition(); + + for (CapabilityDefinition cap : caps) { + List<ComponentInstanceProperty> capPrps = cap.getProperties(); + if (capPrps != null) { + + for (ComponentInstanceProperty cip : capPrps) { + dataToCreate.put(cip.getName(), new PropertyDataDefinition(cip)); + } + + StringBuffer sb = new StringBuffer(componentInstance.getUniqueId()); + sb.append(ModelConverter.CAP_PROP_DELIM); + + sb.append(cap.getOwnerId()); + + sb.append(ModelConverter.CAP_PROP_DELIM).append(s).append(ModelConverter.CAP_PROP_DELIM).append(cap.getName()); + allCalculatedCapProp.put(sb.toString(), dataToCreate); + } + } + + } + + } + }); + + status = addToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, allCalculatedCapProp, componentInstance.getUniqueId()); + } + + /******** Requirements property ****************************/ + if (additionalReq != null && !additionalReq.isEmpty()) { + + MapListRequirementDataDefinition allCalculatedReq = calcReg == null || !calcReg.containsKey(componentInstanceData.getUniqueId()) ? new MapListRequirementDataDefinition() : calcReg.get(componentInstanceData.getUniqueId()); + status = deleteToscaDataDeepElementsBlockOfToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, componentInstanceData.getUniqueId()); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove calculated Requirements for instance {} in container {}. error {] ", componentInstanceData.getUniqueId(), updatedContainer.getUniqueId(), status); + return Either.right(status); + } + + Map<String, ListRequirementDataDefinition> serverReq = additionalReq.entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, en -> new ListRequirementDataDefinition(en.getValue().stream().map(RequirementDataDefinition::new).collect(Collectors.toList())))); + + serverReq.entrySet().forEach(entryPerType -> { + entryPerType.getValue().getListToscaDataDefinition().forEach(cap -> { + cap.addToPath(componentInstance.getUniqueId()); + allCalculatedReq.add(entryPerType.getKey(), cap); + }); + }); + + status = addToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, allCalculatedReq, componentInstance.getUniqueId()); + + } + + Either<ToscaElement, StorageOperationStatus> updatedComponentInstanceRes = topologyTemplateOperation.getToscaElement(updatedContainer.getUniqueId()); + if (updatedComponentInstanceRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with new component instance {}. ", updatedContainer.getName(), componentInstance.getName()); + result = Either.right(updatedComponentInstanceRes.right().value()); + } + result = Either.left(new ImmutablePair<>((TopologyTemplate) updatedComponentInstanceRes.left().value(), componentInstanceData.getUniqueId())); + return result; + } + + private Either<String, StorageOperationStatus> buildValidateInstanceName(TopologyTemplate container, ToscaElement originToscaElement, ComponentInstance componentInstance, String instanceNumberSuffix) { + + Either<String, StorageOperationStatus> result = null; + String instanceName = componentInstance.getName(); + if (StringUtils.isEmpty(instanceName) || instanceName.equalsIgnoreCase(originToscaElement.getName()) || componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) { + instanceName = buildComponentInstanceName(instanceNumberSuffix, instanceName); + } else if (!isUniqueInstanceName(container, componentInstance.getName())) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create component instance with name {} on component container {}. The instance with the same name already exists. ", componentInstance.getName(), container.getName()); + result = Either.right(StorageOperationStatus.ENTITY_ALREADY_EXISTS); + } + if (result == null) { + result = Either.left(instanceName); + } + return result; + } + + public Either<TopologyTemplate, StorageOperationStatus> addComponentInstanceToTopologyTemplate(TopologyTemplate container, ToscaElement originToscaElement, ComponentInstanceDataDefinition componentInstance, GraphVertex metadataVertex, + boolean allowDeleted, User user) { + + Either<TopologyTemplate, StorageOperationStatus> result = null; + Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null; + String containerComponentId = container.getUniqueId(); + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to create component instance {} in component {}", componentInstance, containerComponentId); + String instOriginComponentId = componentInstance.getComponentUid(); + Either<GraphVertex, TitanOperationStatus> updateElement = null; + + Boolean isDeleted = (Boolean) originToscaElement.getMetadataValue(JsonPresentationFields.IS_DELETED); + + if (!allowDeleted && (isDeleted != null) && isDeleted) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Component {} is already deleted. Cannot add component instance", instOriginComponentId); + result = Either.right(StorageOperationStatus.INVALID_ID); + } + Boolean isArchived = originToscaElement.isArchived(); + if ( isArchived != null && isArchived ){ + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create instance {}. Origin {} component is archived . ", componentInstance.getName(), originToscaElement.getName()); + result = Either.right(StorageOperationStatus.COMPONENT_IS_ARCHIVED); + } + + if (result == null) { + container.addComponentInstance(componentInstance); + metadataVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); + topologyTemplateOperation.fillToscaElementVertexData(metadataVertex, container, JsonParseFlagEnum.ParseAll); + updateElement = titanDao.updateVertex(metadataVertex); + if (updateElement.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_UPDATE_TOPOLOGY_TEMPLATE_WITH_NEW_COMPONENT_INSTANCE, container.getName(), componentInstance.getName()); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value())); + } + } + if (result == null) { + Either<GraphVertex, StorageOperationStatus> addToscaDataRes = addComponentInstanceToscaDataToContainerComponent(originToscaElement, componentInstance, updateElement.left().value(), user); + if (addToscaDataRes.isRight()) { + result = Either.right(addToscaDataRes.right().value()); + } + } + if (result == null) { + StorageOperationStatus createInstanceEdge = createInstanceEdge(metadataVertex, componentInstance); + result = createInstanceEdge == StorageOperationStatus.OK ? null : Either.right(createInstanceEdge); + } + + if (result == null) { + updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponentId); + if (updateContainerComponentRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with new component instance {}. ", container.getName(), componentInstance.getName()); + result = Either.right(updateContainerComponentRes.right().value()); + } + } + if (result == null) { + result = Either.left((TopologyTemplate) updateContainerComponentRes.left().value()); + } + return result; + } + + public Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(TopologyTemplate container, ToscaElement originToscaElement, ComponentInstance componentInstance) { + + Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> result = null; + Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null; + + String containerComponentId = container.getUniqueId(); + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update component instance metadata {} of container component {}", componentInstance, containerComponentId); + ComponentInstanceDataDefinition componentInstanceData = null; + + Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(container.getUniqueId(), JsonParseFlagEnum.ParseMetadata); + if (metadataVertex.isRight()) { + TitanOperationStatus status = metadataVertex.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + if (result == null) { + componentInstanceData = buildComponentInstanceDataDefinition(componentInstance, container.getUniqueId(), componentInstance.getName(), false, originToscaElement); + container.addComponentInstance(componentInstanceData); + metadataVertex.left().value().setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); + topologyTemplateOperation.fillToscaElementVertexData(metadataVertex.left().value(), container, JsonParseFlagEnum.ParseAll); + Either<GraphVertex, TitanOperationStatus> updateElement = titanDao.updateVertex(metadataVertex.left().value()); + if (updateElement.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_UPDATE_TOPOLOGY_TEMPLATE_WITH_NEW_COMPONENT_INSTANCE, container.getName(), componentInstance.getName()); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value())); + } + } + if (result == null) { + updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponentId); + if (updateContainerComponentRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with updated component instance {}. ", container.getName(), componentInstance.getName()); + result = Either.right(updateContainerComponentRes.right().value()); + } + } + if (result == null) { + result = Either.left(new ImmutablePair<>((TopologyTemplate) updateContainerComponentRes.left().value(), componentInstanceData.getUniqueId())); + } + return result; + } + + public Either<TopologyTemplate, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(TopologyTemplate container, ComponentParametersView filter) { + + Either<TopologyTemplate, StorageOperationStatus> result = null; + Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null; + + String containerComponentId = container.getUniqueId(); + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update component instance metadata of container component {}", containerComponentId); + + Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(container.getUniqueId(), JsonParseFlagEnum.ParseMetadata); + if (metadataVertex.isRight()) { + TitanOperationStatus status = metadataVertex.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + if (result == null) { + metadataVertex.left().value().setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); + topologyTemplateOperation.fillToscaElementVertexData(metadataVertex.left().value(), container, JsonParseFlagEnum.ParseAll); + Either<GraphVertex, TitanOperationStatus> updateElement = titanDao.updateVertex(metadataVertex.left().value()); + if (updateElement.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update topology template {}. ", container.getName()); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value())); + } + } + if (result == null) { + updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponentId, filter); + if (updateContainerComponentRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {}. ", container.getName()); + result = Either.right(updateContainerComponentRes.right().value()); + } + } + if (result == null) { + result = Either.left((TopologyTemplate) updateContainerComponentRes.left().value()); + } + return result; + } + + public Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> deleteComponentInstanceFromTopologyTemplate(TopologyTemplate container, String componentInstanceId) { + + Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> result = null; + Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null; + + String containerComponentId = container.getUniqueId(); + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update component instance metadata {} of container component {}", componentInstanceId, containerComponentId); + + Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(container.getUniqueId(), JsonParseFlagEnum.ParseMetadata); + if (metadataVertex.isRight()) { + TitanOperationStatus status = metadataVertex.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + GraphVertex containerV = null; + ComponentInstanceDataDefinition removedComponentInstance = null; + if (result == null) { + removedComponentInstance = container.getComponentInstances().remove(componentInstanceId); + containerV = metadataVertex.left().value(); + StorageOperationStatus status = removeRelationsOfInstance(container, componentInstanceId, containerV); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete relation for component instance {} in container. error {}", componentInstanceId, container.getUniqueId(), status); + result = Either.right(status); + } + + containerV.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); + topologyTemplateOperation.fillToscaElementVertexData(containerV, container, JsonParseFlagEnum.ParseAll); + Either<GraphVertex, TitanOperationStatus> updateElement = titanDao.updateVertex(containerV); + if (updateElement.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_UPDATE_TOPOLOGY_TEMPLATE_WITH_NEW_COMPONENT_INSTANCE, container.getName(), componentInstanceId); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value())); + } + } + if (result == null) { + StorageOperationStatus status = deleteComponentInstanceToscaDataFromContainerComponent(containerV, componentInstanceId); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete data for instance {} in container {}. error {] ", componentInstanceId, container.getUniqueId(), status); + return Either.right(status); + } + ComponentInstance componentInstance = new ComponentInstance(removedComponentInstance); + StorageOperationStatus createInstanceEdge = removeInstanceEdge(containerV, componentInstance); + result = createInstanceEdge == StorageOperationStatus.OK ? null : Either.right(createInstanceEdge); + } + if (result == null) { + updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponentId); + if (updateContainerComponentRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} after deleting the component instance {}. ", container.getName(), componentInstanceId); + result = Either.right(updateContainerComponentRes.right().value()); + } + } + if (result == null) { + result = Either.left(new ImmutablePair<>((TopologyTemplate) updateContainerComponentRes.left().value(), componentInstanceId)); + } + return result; + } + + private StorageOperationStatus removeRelationsOfInstance(TopologyTemplate container, String ciToRemove, GraphVertex containerV) { + CompositionDataDefinition composition = container.getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue()); + if (composition != null) { + Map<String, RelationshipInstDataDefinition> relations = composition.getRelations(); + if (MapUtils.isNotEmpty(relations)) { + Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> capResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES); + if (capResult.isRight()) { + return capResult.right().value(); + + } + Map<String, MapListCapabilityDataDefinition> calculatedCapabilty = capResult.left().value().getRight(); + + Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> capFullResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES); + if (capFullResult.isRight()) { + return capFullResult.right().value(); + + } + Map<String, MapListCapabilityDataDefinition> fullFilledCapabilty = capFullResult.left().value().getRight(); + + Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS); + if (reqResult.isRight()) { + return reqResult.right().value(); + } + Map<String, MapListRequirementDataDefinition> calculatedRequirement = reqResult.left().value().getRight(); + + Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqFullResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS); + if (reqResult.isRight()) { + return reqResult.right().value(); + } + Map<String, MapListRequirementDataDefinition> fullfilledRequirement = reqFullResult.left().value().getRight(); + + Iterator<Entry<String, RelationshipInstDataDefinition>> iterator = relations.entrySet().iterator(); + while (iterator.hasNext()) { + Entry<String, RelationshipInstDataDefinition> relation = iterator.next(); + RelationshipInstDataDefinition relationToDelete = relation.getValue(); + if (relationToDelete.getFromId().equals(ciToRemove) || relationToDelete.getToId().equals(ciToRemove)) { + iterator.remove(); + if (relationToDelete.getFromId().equals(ciToRemove)) { + updateCalculatedRequirementsAfterDeleteRelation(calculatedRequirement, fullfilledRequirement, ciToRemove, relationToDelete, null); + updateCalculatedCapabiltyAfterDeleteRelation(calculatedCapabilty, fullFilledCapabilty, relationToDelete.getToId(), relationToDelete, null); + } + if (relationToDelete.getToId().equals(ciToRemove)) { + updateCalculatedRequirementsAfterDeleteRelation(calculatedRequirement, fullfilledRequirement, relationToDelete.getFromId(), relationToDelete, null); + updateCalculatedCapabiltyAfterDeleteRelation(calculatedCapabilty, fullFilledCapabilty, ciToRemove, relationToDelete, null); + } + } + } + return updateAllAndCalculatedCapReqOnGraph(container.getUniqueId(), containerV, capResult, capFullResult, reqResult, reqFullResult); + } + } + return StorageOperationStatus.OK; + } + + private StorageOperationStatus deleteComponentInstanceToscaDataFromContainerComponent(GraphVertex containerV, String componentInstanceId) { + StorageOperationStatus status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, componentInstanceId); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove calculated capabilty for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); + return status; + } + status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, componentInstanceId); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove calculated capabilty properties for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); + return status; + } + status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, componentInstanceId); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove calculated requirement for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); + return status; + } + status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES, VertexTypeEnum.FULLFILLED_CAPABILITIES, componentInstanceId); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove fullfilled capabilities for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); + return status; + } + status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, VertexTypeEnum.FULLFILLED_REQUIREMENTS, componentInstanceId); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove fullfilled requirement for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); + return status; + } + status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_ATTRIBUTES, VertexTypeEnum.INST_ATTRIBUTES, componentInstanceId); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove attributes for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); + return status; + } + status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, componentInstanceId); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove properties for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); + return status; + } + status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, componentInstanceId); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove instance inputs for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); + return status; + } + status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, componentInstanceId); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove fullfilled requirement for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); + return status; + } + status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, componentInstanceId); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove instance deployment artifacts for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); + return status; + } + status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INSTANCE_ARTIFACTS, VertexTypeEnum.INSTANCE_ARTIFACTS, componentInstanceId); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove instance artifacts for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); + return status; + } + status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.EXTERNAL_REFS, VertexTypeEnum.EXTERNAL_REF, componentInstanceId); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove instance external refs for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); + return status; + } + return StorageOperationStatus.OK; + } + + protected Either<GraphVertex, StorageOperationStatus> addComponentInstanceToscaDataToContainerComponent(ToscaElement originToscaElement, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex, User user) { + + Either<GraphVertex, StorageOperationStatus> result; + StorageOperationStatus status; + if (originToscaElement.getToscaType() == ToscaElementTypeEnum.NODE_TYPE) { + status = addComponentInstanceToscaDataToNodeTypeContainer((NodeType) originToscaElement, componentInstance, updatedContainerVertex, user, HEAT_VF_ENV_NAME); + } else { + status = addComponentInstanceToscaDataToTopologyTemplateContainer((TopologyTemplate) originToscaElement, componentInstance, updatedContainerVertex); + } + if (status == StorageOperationStatus.OK) { + result = Either.left(updatedContainerVertex); + } else { + result = Either.right(status); + } + return result; + } + + private StorageOperationStatus addComponentInstanceToscaDataToTopologyTemplateContainer(TopologyTemplate originTopologyTemplate, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex) { + + StorageOperationStatus status; + + status = addCalculatedCapReqFromTopologyTemplate(originTopologyTemplate, componentInstance, updatedContainerVertex); + + if (status != StorageOperationStatus.OK) { + + return status; + } + + MapPropertiesDataDefinition instInputs = new MapPropertiesDataDefinition(originTopologyTemplate.getInputs()); + MapPropertiesDataDefinition instInputsAsProperties = turnInputsIntoProperties(instInputs); + + status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, instInputsAsProperties, componentInstance.getUniqueId()); + if (status != StorageOperationStatus.OK) { + return status; + } + + return status; + } + + private MapPropertiesDataDefinition turnInputsIntoProperties(MapPropertiesDataDefinition instInput){ + if (instInput.getMapToscaDataDefinition() != null) { + for (PropertyDataDefinition currProp : instInput.getMapToscaDataDefinition().values()){ + String temp = currProp.getValue(); + currProp.setValue(currProp.getDefaultValue()); + currProp.setDefaultValue(temp); + } + } + return instInput; + } + + private StorageOperationStatus addCalculatedCapReqFromTopologyTemplate(TopologyTemplate originTopologyTemplate, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex) { + Map<String, MapListCapabilityDataDefinition> calculatedCapabilities = originTopologyTemplate.getCalculatedCapabilities(); + + if (calculatedCapabilities != null) { + MapListCapabilityDataDefinition allCalculatedCap = new MapListCapabilityDataDefinition(); + calculatedCapabilities.entrySet().forEach(enntryPerInstance -> { + Map<String, ListCapabilityDataDefinition> mapByType = enntryPerInstance.getValue().getMapToscaDataDefinition(); + mapByType.entrySet().forEach(entryPerType -> { + entryPerType.getValue().getListToscaDataDefinition().forEach(cap -> { + cap.addToPath(componentInstance.getUniqueId()); + allCalculatedCap.add(entryPerType.getKey(), cap); + }); + }); + }); + + StorageOperationStatus calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, allCalculatedCap, + componentInstance.getUniqueId()); + + if (calculatedResult != StorageOperationStatus.OK) { + return calculatedResult; + } + MapListCapabilityDataDefinition fullCalculatedCap = new MapListCapabilityDataDefinition(); + calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.FULLFILLED_CAPABILITIES, VertexTypeEnum.FULLFILLED_CAPABILITIES, fullCalculatedCap, componentInstance.getUniqueId()); + + if (calculatedResult != StorageOperationStatus.OK) { + return calculatedResult; + } + } + Map<String, MapListRequirementDataDefinition> calculatedRequirements = originTopologyTemplate.getCalculatedRequirements(); + if (calculatedRequirements != null) { + + MapListRequirementDataDefinition allCalculatedReq = new MapListRequirementDataDefinition(); + calculatedRequirements.entrySet().forEach(enntryPerInstance -> { + Map<String, ListRequirementDataDefinition> mapByType = enntryPerInstance.getValue().getMapToscaDataDefinition(); + mapByType.entrySet().forEach(entryPerType -> { + entryPerType.getValue().getListToscaDataDefinition().forEach(req -> { + req.addToPath(componentInstance.getUniqueId()); + allCalculatedReq.add(entryPerType.getKey(), req); + }); + }); + }); + + StorageOperationStatus calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, allCalculatedReq, + componentInstance.getUniqueId()); + if (calculatedResult != StorageOperationStatus.OK) { + return calculatedResult; + } + MapListRequirementDataDefinition fullCalculatedReq = new MapListRequirementDataDefinition(); + calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, VertexTypeEnum.FULLFILLED_REQUIREMENTS, fullCalculatedReq, componentInstance.getUniqueId()); + if (calculatedResult != StorageOperationStatus.OK) { + return calculatedResult; + } + } + + Map<String, MapCapabilityProperty> calculatedCapabilitiesProperties = originTopologyTemplate.getCalculatedCapabilitiesProperties(); + Map<String, MapPropertiesDataDefinition> updateKeyMap = new HashMap<>(); + + if (calculatedCapabilitiesProperties != null && !calculatedCapabilitiesProperties.isEmpty()) { + for (MapCapabilityProperty map : calculatedCapabilitiesProperties.values()) { + for (Entry<String, MapPropertiesDataDefinition> entry : map.getMapToscaDataDefinition().entrySet()) { + String newKey = (componentInstance.getUniqueId() + ModelConverter.CAP_PROP_DELIM + entry.getKey()); + updateKeyMap.put(newKey, entry.getValue()); + } + } + MapCapabilityProperty MapCapabilityProperty = new MapCapabilityProperty(updateKeyMap); + StorageOperationStatus calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, MapCapabilityProperty, + componentInstance.getUniqueId()); + if (calculatedResult != StorageOperationStatus.OK) { + return calculatedResult; + } + } + return StorageOperationStatus.OK; + } + + private StorageOperationStatus addComponentInstanceToscaDataToNodeTypeContainer(NodeType originNodeType, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex, User user, String envType) { + + MapPropertiesDataDefinition instProperties = new MapPropertiesDataDefinition(originNodeType.getProperties()); + + StorageOperationStatus status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, instProperties, componentInstance.getUniqueId()); + if (status != StorageOperationStatus.OK) { + return status; + } + + MapPropertiesDataDefinition instAttributes = new MapPropertiesDataDefinition(originNodeType.getAttributes()); + + status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.INST_ATTRIBUTES, VertexTypeEnum.INST_ATTRIBUTES, instAttributes, componentInstance.getUniqueId()); + + if (status != StorageOperationStatus.OK) { + return status; + } + + return addCalculatedCapReqFromNodeType(originNodeType, componentInstance, updatedContainerVertex); + } + + public MapArtifactDataDefinition prepareInstDeploymentArtifactPerInstance(Map<String, ArtifactDataDefinition> deploymentArtifacts, String componentInstanceId, User user, String envType) { + if (deploymentArtifacts != null && envType.equals(HEAT_VF_ENV_NAME)) { + Map<String, ArtifactDataDefinition> instDeploymentArtifacts = new HashMap<>(); + + deploymentArtifacts.entrySet().forEach(e -> { + ArtifactDataDefinition artifact = e.getValue(); + String type = artifact.getArtifactType(); + if (type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) { + ArtifactDataDefinition artifactEnv = createArtifactPlaceHolderInfo(artifact, componentInstanceId, user, envType); + instDeploymentArtifacts.put(artifactEnv.getArtifactLabel(), artifactEnv); + } + }); + + deploymentArtifacts.putAll(instDeploymentArtifacts); + + return new MapArtifactDataDefinition(deploymentArtifacts); + + } + return null; + } + + @SuppressWarnings({ "unchecked" }) + private ArtifactDataDefinition createArtifactPlaceHolderInfo(ArtifactDataDefinition artifactHeat, String componentId, User user, String heatEnvType) { + Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts(); + if (deploymentResourceArtifacts == null) { + log.debug("no deployment artifacts are configured for generated artifacts"); + return null; + } + Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(heatEnvType); + if (placeHolderData == null) { + log.debug("no env type {} are configured for generated artifacts", heatEnvType); + return null; + } + + String envLabel = (artifactHeat.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase(); + + ArtifactDataDefinition artifactInfo = new ArtifactDataDefinition(); + + String artifactName = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_DISPLAY_NAME); + String artifactType = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_TYPE); + String artifactDescription = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_DESCRIPTION); + + artifactInfo.setArtifactDisplayName(artifactName); + artifactInfo.setArtifactLabel(envLabel); + artifactInfo.setArtifactType(artifactType); + artifactInfo.setDescription(artifactDescription); + artifactInfo.setArtifactGroupType(artifactHeat.getArtifactGroupType()); + setDefaultArtifactTimeout(artifactHeat.getArtifactGroupType(), artifactInfo); + artifactInfo.setGeneratedFromId(artifactHeat.getUniqueId()); + // clone heat parameters in case of heat env only not VF heat env + if (heatEnvType.equals(HEAT_ENV_NAME)) { + artifactInfo.setHeatParameters(artifactHeat.getHeatParameters()); + } + setArtifactPlaceholderCommonFields(componentId, user, artifactInfo); + + return artifactInfo; + } + + public void setDefaultArtifactTimeout(ArtifactGroupTypeEnum groupType, ArtifactDataDefinition artifactInfo) { + if (groupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) { + artifactInfo.setTimeout(defaultHeatTimeout); + } else { + artifactInfo.setTimeout(NON_HEAT_TIMEOUT); + } + } + + private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDataDefinition artifactInfo) { + String uniqueId = null; + + if (resourceId != null) { + uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel().toLowerCase()); + artifactInfo.setUniqueId(uniqueId); + } + artifactInfo.setUserIdCreator(user.getUserId()); + String fullName = user.getFullName(); + artifactInfo.setUpdaterFullName(fullName); + + long time = System.currentTimeMillis(); + + artifactInfo.setCreatorFullName(fullName); + artifactInfo.setCreationDate(time); + + artifactInfo.setLastUpdateDate(time); + artifactInfo.setUserIdLastUpdater(user.getUserId()); + + artifactInfo.setMandatory(true); + } + + /** + * + * @param originNodeType + * @param componentInstance + * @param updatedContainerVertex + * @return + */ + private StorageOperationStatus addCalculatedCapReqFromNodeType(NodeType originNodeType, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex) { + + Map<String, ListCapabilityDataDefinition> capabilities = originNodeType.getCapabilties(); + MapListCapabilityDataDefinition allCalculatedCap = prepareCalculatedCapabiltyForNodeType(capabilities, componentInstance); + StorageOperationStatus calculatedResult; + if (allCalculatedCap != null) { + calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, allCalculatedCap, componentInstance.getUniqueId()); + + if (calculatedResult != StorageOperationStatus.OK) { + return calculatedResult; + } + } + Map<String, MapPropertiesDataDefinition> capabiltiesProperties = originNodeType.getCapabiltiesProperties(); + if (capabiltiesProperties != null) { + Map<String, MapPropertiesDataDefinition> updateKeyMap = capabiltiesProperties.entrySet().stream().collect(Collectors.toMap(e -> createCapPropertyKey(e.getKey(), componentInstance.getUniqueId()), Entry::getValue)); + MapCapabilityProperty MapCapabilityProperty = new MapCapabilityProperty(updateKeyMap); + calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, MapCapabilityProperty, componentInstance.getUniqueId()); + if (calculatedResult != StorageOperationStatus.OK) { + return calculatedResult; + } + } + + MapListCapabilityDataDefinition fullCalculatedCap = new MapListCapabilityDataDefinition(); + calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.FULLFILLED_CAPABILITIES, VertexTypeEnum.FULLFILLED_CAPABILITIES, fullCalculatedCap, componentInstance.getUniqueId()); + + if (calculatedResult != StorageOperationStatus.OK) { + return calculatedResult; + } + + Map<String, ListRequirementDataDefinition> requirements = originNodeType.getRequirements(); + + MapListRequirementDataDefinition allCalculatedReq = prepareCalculatedRequirementForNodeType(requirements, componentInstance); + + StorageOperationStatus status; + if (allCalculatedReq != null) { + status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, allCalculatedReq, componentInstance.getUniqueId()); + if (status != StorageOperationStatus.OK) { + return status; + } + } + MapListRequirementDataDefinition fullCalculatedReq = new MapListRequirementDataDefinition(); + status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, VertexTypeEnum.FULLFILLED_REQUIREMENTS, fullCalculatedReq, componentInstance.getUniqueId()); + return StorageOperationStatus.OK; + + } + + public static String createCapPropertyKey(String key, String instanceId) { + StringBuffer sb = new StringBuffer(instanceId); + sb.append(ModelConverter.CAP_PROP_DELIM).append(instanceId).append(ModelConverter.CAP_PROP_DELIM).append(key); + return sb.toString(); + } + + /** + * Prepares a map of capabilities lists Produces a deep copy of the received map of capabilities Sets values to the specific fields according to received component instance + * + * @param capabilities + * @param componentInstance + * @return + */ + public MapListCapabilityDataDefinition prepareCalculatedCapabiltyForNodeType(Map<String, ListCapabilityDataDefinition> capabilities, ComponentInstanceDataDefinition componentInstance) { + if (capabilities != null) { + MapListCapabilityDataDefinition allCalculatedCap = new MapListCapabilityDataDefinition(); + + capabilities.entrySet().forEach(e -> { + List<CapabilityDataDefinition> listCapabilities = e.getValue().getListToscaDataDefinition().stream().map(CapabilityDataDefinition::new).collect(Collectors.toList()); + listCapabilities.forEach(cap -> { + cap.setSource(componentInstance.getComponentUid()); + cap.addToPath(componentInstance.getUniqueId()); + cap.setOwnerId(componentInstance.getUniqueId()); + cap.setOwnerName(componentInstance.getName()); + cap.setLeftOccurrences(cap.getMaxOccurrences()); + allCalculatedCap.add(e.getKey(), cap); + }); + }); + return allCalculatedCap; + } + return null; + } + + /** + * Prepares a map of requirements lists Produces a deep copy of the received map of requirements Sets values to the specific fields according to received component instance + * + * @param requirements + * @param componentInstance + * @return + */ + public MapListRequirementDataDefinition prepareCalculatedRequirementForNodeType(Map<String, ListRequirementDataDefinition> requirements, ComponentInstanceDataDefinition componentInstance) { + if (requirements != null) { + MapListRequirementDataDefinition allCalculatedReq = new MapListRequirementDataDefinition(); + + requirements.entrySet().forEach(e -> { + List<RequirementDataDefinition> listRequirements = e.getValue().getListToscaDataDefinition().stream().map(RequirementDataDefinition::new).collect(Collectors.toList()); + listRequirements.forEach(req -> { + req.setSource(componentInstance.getComponentUid()); + req.addToPath(componentInstance.getUniqueId()); + req.setOwnerId(componentInstance.getUniqueId()); + req.setOwnerName(componentInstance.getName()); + req.setLeftOccurrences(req.getMaxOccurrences()); + allCalculatedReq.add(e.getKey(), req); + }); + }); + return allCalculatedReq; + } + return null; + } + + public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstanceDataDefinition componentInstance, List<GroupDefinition> groups, Map<String, List<ArtifactDefinition>> groupInstancesArtifacts) { + + StorageOperationStatus result = null; + Map<String, GroupInstanceDataDefinition> groupInstanceToCreate = new HashMap<>(); + if (groupInstancesArtifacts != null && CollectionUtils.isNotEmpty(groups)) { + for (Map.Entry<String, List<ArtifactDefinition>> groupArtifacts : groupInstancesArtifacts.entrySet()) { + Optional<GroupDefinition> groupOptional = groups.stream().filter(g -> g.getUniqueId().equals(groupArtifacts.getKey())).findFirst(); + if (groupOptional.isPresent()) { + GroupInstanceDataDefinition groupInstance = buildGroupInstanceDataDefinition((GroupDataDefinition) groupOptional.get(), (ComponentInstanceDataDefinition) componentInstance, null); + groupInstance.setGroupInstanceArtifacts(groupArtifacts.getValue().stream().map(ArtifactDataDefinition::getUniqueId).collect(Collectors.toList())); + groupInstance.setGroupInstanceArtifactsUuid(groupArtifacts.getValue().stream().map(ArtifactDataDefinition::getArtifactUUID).collect(Collectors.toList())); + groupInstanceToCreate.put(groupInstance.getName(), groupInstance); + } + } + } + if (MapUtils.isNotEmpty(groupInstanceToCreate)) { + result = addToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, new MapDataDefinition<>(groupInstanceToCreate), componentInstance.getUniqueId()); + } + if (result == null) { + result = StorageOperationStatus.OK; + } + return result; + } + + private ComponentInstanceDataDefinition buildComponentInstanceDataDefinition(ComponentInstance resourceInstance, String containerComponentId, String instanceNewName, boolean generateUid, ToscaElement originToscaElement) { + String ciOriginComponentUid = resourceInstance.getComponentUid(); + + if (!ValidationUtils.validateStringNotEmpty(resourceInstance.getCustomizationUUID())) { + resourceInstance.setCustomizationUUID(generateCustomizationUUID()); + } + ComponentInstanceDataDefinition dataDefinition = new ComponentInstanceDataDefinition(resourceInstance); + + Long creationDate = resourceInstance.getCreationTime(); + Long modificationTime; + if (creationDate == null) { + creationDate = System.currentTimeMillis(); + modificationTime = creationDate; + } else { + modificationTime = System.currentTimeMillis(); + } + dataDefinition.setComponentUid(ciOriginComponentUid); + dataDefinition.setCreationTime(creationDate); + dataDefinition.setModificationTime(modificationTime); + if (StringUtils.isNotEmpty(instanceNewName)) { + dataDefinition.setName(instanceNewName); + resourceInstance.setName(instanceNewName); + } + if (StringUtils.isNotEmpty(dataDefinition.getName())) + dataDefinition.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(dataDefinition.getName())); + dataDefinition.setIcon(resourceInstance.getIcon()); + if (generateUid) { + dataDefinition.setUniqueId(UniqueIdBuilder.buildResourceInstanceUniuqeId(containerComponentId, ciOriginComponentUid, dataDefinition.getNormalizedName())); + resourceInstance.setUniqueId(dataDefinition.getUniqueId()); + } + if (StringUtils.isEmpty(dataDefinition.getComponentVersion()) && originToscaElement != null) + dataDefinition.setComponentVersion((String) originToscaElement.getMetadataValue(JsonPresentationFields.VERSION)); + if (StringUtils.isEmpty(dataDefinition.getComponentName()) && originToscaElement != null) + dataDefinition.setComponentName((String) originToscaElement.getMetadataValue(JsonPresentationFields.NAME)); + if (originToscaElement != null && dataDefinition.getToscaComponentName() == null) + dataDefinition.setToscaComponentName((String) originToscaElement.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME)); + if (dataDefinition.getOriginType() == null && originToscaElement != null) { + ResourceTypeEnum resourceType = originToscaElement.getResourceType(); + OriginTypeEnum originType = OriginTypeEnum.findByValue(resourceType.name()); + dataDefinition.setOriginType(originType); + } + if (dataDefinition.getOriginType() == OriginTypeEnum.ServiceProxy) + dataDefinition.setIsProxy(true); + + return dataDefinition; + } + + private Boolean isUniqueInstanceName(TopologyTemplate container, String instanceName) { + Boolean isUniqueName = true; + try { + isUniqueName = !container.getComponentInstances().values().stream().filter(ci -> ci.getName() != null && ci.getName().equals(instanceName)).findAny().isPresent(); + + } catch (Exception e) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during fetching component instance with name {} from component container {}. {} ", instanceName, container.getName(), e.getMessage()); + } + return isUniqueName; + } + + private String buildComponentInstanceName(String instanceSuffixNumber, String instanceName) { + return instanceName + " " + (instanceSuffixNumber == null ? 0 : instanceSuffixNumber); + } + + public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String componentId, RequirementCapabilityRelDef relation) { + List<RequirementCapabilityRelDef> relations = new ArrayList<>(); + relations.add(relation); + Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> associateResourceInstances = associateResourceInstances(componentId, relations); + if (associateResourceInstances.isRight()) { + return Either.right(associateResourceInstances.right().value()); + } + return Either.left(associateResourceInstances.left().value().get(0)); + } + + @SuppressWarnings({ "unchecked" }) + public <T extends ToscaDataDefinition> Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> associateResourceInstances(String componentId, List<RequirementCapabilityRelDef> relations) { + + Either<GraphVertex, TitanOperationStatus> containerVEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll); + if (containerVEither.isRight()) { + TitanOperationStatus error = containerVEither.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FETCH_CONTAINER_VERTEX_ERROR, componentId, error); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error)); + } + GraphVertex containerV = containerVEither.left().value(); + Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> capResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES); + if (capResult.isRight()) { + return Either.right(capResult.right().value()); + + } + Map<String, MapListCapabilityDataDefinition> calculatedCapabilty = capResult.left().value().getRight(); + + Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> capFullResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES); + if (capResult.isRight()) { + return Either.right(capResult.right().value()); + + } + Map<String, MapListCapabilityDataDefinition> fullFilledCapabilty = capFullResult.left().value().getRight(); + + Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS); + if (reqResult.isRight()) { + return Either.right(reqResult.right().value()); + } + Map<String, MapListRequirementDataDefinition> calculatedRequirement = reqResult.left().value().getRight(); + + Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqFullResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS); + if (reqResult.isRight()) { + return Either.right(reqResult.right().value()); + } + Map<String, MapListRequirementDataDefinition> fullfilledRequirement = reqFullResult.left().value().getRight(); + + Map<String, CompositionDataDefinition> jsonComposition = (Map<String, CompositionDataDefinition>) containerV.getJson(); + CompositionDataDefinition compositionDataDefinition = jsonComposition.get(JsonConstantKeysEnum.COMPOSITION.getValue()); + + StorageOperationStatus status; + List<RequirementCapabilityRelDef> relationsList = new ArrayList<>(); + for (RequirementCapabilityRelDef relation : relations) { + List<CapabilityRequirementRelationship> relationshipsResult = new ArrayList<>(); + String fromNode = relation.getFromNode(); + String toNode = relation.getToNode(); + List<CapabilityRequirementRelationship> relationships = relation.getRelationships(); + if (relationships == null || relationships.isEmpty()) { + BeEcompErrorManager.getInstance().logBeFailedAddingResourceInstanceError("AssociateResourceInstances - missing relationship", fromNode, componentId); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No requirement definition sent in order to set the relation between {} to {}", fromNode, toNode); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT)); + } + + for (CapabilityRequirementRelationship immutablePair : relationships) { + String requirement = immutablePair.getRelation().getRequirement(); + + Either<Map<JsonPresentationFields, T>, StorageOperationStatus> associateRes = connectInstancesInContainer(fromNode, toNode, immutablePair.getRelation(), relation.isOriginUI(), calculatedCapabilty, calculatedRequirement, + fullFilledCapabilty, fullfilledRequirement, compositionDataDefinition, containerV.getUniqueId()); + + if (associateRes.isRight()) { + status = associateRes.right().value(); + BeEcompErrorManager.getInstance().logBeFailedAddingResourceInstanceError("AssociateResourceInstances - missing relationship", fromNode, componentId); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to associate resource instance {} to resource instance {}. status is {}", fromNode, toNode, status); + return Either.right(status); + } + + RelationshipInstDataDefinition relationshipInstData = (RelationshipInstDataDefinition) associateRes.left().value().get(JsonPresentationFields.RELATIONSHIP); + RelationshipImpl relationshipImplResult = new RelationshipImpl(); + relationshipImplResult.setType(relationshipInstData.getType()); + RelationshipInfo requirementAndRelationshipPair = new RelationshipInfo(requirement, relationshipImplResult); + requirementAndRelationshipPair.setCapability(immutablePair.getRelation().getCapability()); + requirementAndRelationshipPair.setRequirement(immutablePair.getRelation().getRequirement()); + requirementAndRelationshipPair.setCapabilityOwnerId(relationshipInstData.getCapabilityOwnerId()); + requirementAndRelationshipPair.setRequirementOwnerId(relationshipInstData.getRequirementOwnerId()); + requirementAndRelationshipPair.setCapabilityUid(immutablePair.getRelation().getCapabilityUid()); + requirementAndRelationshipPair.setRequirementUid(immutablePair.getRelation().getRequirementUid()); + requirementAndRelationshipPair.setId(relationshipInstData.getUniqueId()); + CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship(); + capReqRel.setRelation(requirementAndRelationshipPair); + capReqRel.setCapability((CapabilityDataDefinition) associateRes.left().value().get(JsonPresentationFields.CAPAPILITY)); + capReqRel.setRequirement((RequirementDataDefinition) associateRes.left().value().get(JsonPresentationFields.REQUIREMENT)); + relationshipsResult.add(capReqRel); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "update customization UUID for from CI {} and to CI {}", relation.getFromNode(), relation.getToNode()); + status = updateCustomizationUUID(relation.getFromNode(), compositionDataDefinition); + if (status != StorageOperationStatus.OK) { + return Either.right(status); + } + status = updateCustomizationUUID(relation.getToNode(), compositionDataDefinition); + if (status != StorageOperationStatus.OK) { + return Either.right(status); + } + } + RequirementCapabilityRelDef reqCapRelDef = new RequirementCapabilityRelDef(relation); + reqCapRelDef.setRelationships(relationshipsResult); + relationsList.add(reqCapRelDef); + } + // update metadata of container and composition json + status = updateAllAndCalculatedCapReqOnGraph(componentId, containerV, capResult, capFullResult, reqResult, reqFullResult); + if (status != StorageOperationStatus.OK) { + return Either.right(status); + } + + return Either.left(relationsList); + } + + private StorageOperationStatus updateAllAndCalculatedCapReqOnGraph(String componentId, GraphVertex containerV, Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> capResult, + Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> capFullResult, Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqResult, + Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqFullResult) { + containerV.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); + Either<GraphVertex, TitanOperationStatus> updateElement = titanDao.updateVertex(containerV); + if (updateElement.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update topology template {} with new relations error {}. ", componentId, updateElement.right().value()); + return DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value()); + } + // update cap/req jsons, fulfilled cap/req jsons!!!!! + Either<GraphVertex, TitanOperationStatus> status; + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Update calculated capabilty for container {}", containerV.getUniqueId()); + status = updateOrCopyOnUpdate(capResult.left().value().getLeft(), containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES); + if (status.isRight()) { + TitanOperationStatus error = status.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update calculated capabilty for container {} error {}", containerV.getUniqueId(), error); + return DaoStatusConverter.convertTitanStatusToStorageStatus(error); + } + + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Update calculated requirement for container {}", containerV.getUniqueId()); + status = updateOrCopyOnUpdate(reqResult.left().value().getLeft(), containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS); + if (status.isRight()) { + TitanOperationStatus error = status.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update calculated requiremnt for container {} error {}", containerV.getUniqueId(), error); + return DaoStatusConverter.convertTitanStatusToStorageStatus(error); + } + + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Update fullfilled capabilty for container {}", containerV.getUniqueId()); + status = updateOrCopyOnUpdate(capFullResult.left().value().getLeft(), containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES); + if (status.isRight()) { + TitanOperationStatus error = status.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update fullfilled capabilty for container {} error {}", containerV.getUniqueId(), error); + return DaoStatusConverter.convertTitanStatusToStorageStatus(error); + } + + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Update fullfilled requirement for container {}", containerV.getUniqueId()); + status = updateOrCopyOnUpdate(reqFullResult.left().value().getLeft(), containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS); + if (status.isRight()) { + TitanOperationStatus error = status.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update fullfilled requirement for container {} error {}", containerV.getUniqueId(), error); + return DaoStatusConverter.convertTitanStatusToStorageStatus(error); + } + return StorageOperationStatus.OK; + } + + @SuppressWarnings({ "unchecked" }) + public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) { + if (requirementDef.getRelationships() == null) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No relation pair in request [ {} ]", requirementDef); + return Either.right(StorageOperationStatus.BAD_REQUEST); + } + + String fromResInstanceUid = requirementDef.getFromNode(); + String toResInstanceUid = requirementDef.getToNode(); + + Either<GraphVertex, TitanOperationStatus> containerVEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll); + if (containerVEither.isRight()) { + TitanOperationStatus error = containerVEither.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FETCH_CONTAINER_VERTEX_ERROR, componentId, error); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error)); + } + GraphVertex containerV = containerVEither.left().value(); + + // DE191707 - validations + Map<String, CompositionDataDefinition> jsonComposition = (Map<String, CompositionDataDefinition>) containerV.getJson(); + CompositionDataDefinition compositionDataDefinition = jsonComposition.get(JsonConstantKeysEnum.COMPOSITION.getValue()); + Map<String, ComponentInstanceDataDefinition> componentInstances = compositionDataDefinition.getComponentInstances(); + ComponentInstanceDataDefinition ciFrom = componentInstances.get(fromResInstanceUid); + if (ciFrom == null) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "FROM instance {} isn't under container {}", fromResInstanceUid, componentId); + return Either.right(StorageOperationStatus.NOT_FOUND); + + } + ComponentInstanceDataDefinition ciTo = componentInstances.get(toResInstanceUid); + if (ciFrom == ciTo) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "TO instance {} isn't under container {}", toResInstanceUid, componentId); + return Either.right(StorageOperationStatus.NOT_FOUND); + + } + Map<String, RelationshipInstDataDefinition> relations = compositionDataDefinition.getRelations(); + + List<CapabilityRequirementRelationship> relationPairList = requirementDef.getRelationships(); + Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> capResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES); + if (capResult.isRight()) { + return Either.right(capResult.right().value()); + } + Map<String, MapListCapabilityDataDefinition> calculatedCapability = capResult.left().value().getRight(); + + Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> capFullResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES); + if (capResult.isRight()) { + return Either.right(capResult.right().value()); + + } + Map<String, MapListCapabilityDataDefinition> fulfilledCapability = capFullResult.left().value().getRight(); + + Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS); + if (reqResult.isRight()) { + return Either.right(reqResult.right().value()); + } + Map<String, MapListRequirementDataDefinition> calculatedRequirement = reqResult.left().value().getRight(); + + Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqFullResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS); + if (reqResult.isRight()) { + return Either.right(reqResult.right().value()); + } + Map<String, MapListRequirementDataDefinition> fulfilledRequirement = reqFullResult.left().value().getRight(); + + for (CapabilityRequirementRelationship relationPair : relationPairList) { + Iterator<Entry<String, RelationshipInstDataDefinition>> iterator = relations.entrySet().iterator(); + boolean isDeleted = false; + while (iterator.hasNext()) { + Entry<String, RelationshipInstDataDefinition> entryInJson = iterator.next(); + RelationshipInstDataDefinition relationInJson = entryInJson.getValue(); + if (relationInJson.getFromId().equals(fromResInstanceUid) && relationInJson.getToId().equals(toResInstanceUid) && relationInJson.getUniqueId().equals(relationPair.getRelation().getId())) { + if (relationPair.getRelation().equalsTo(relationInJson)) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Remove relation from {} to {} capability {} capOwnerId {} reqOwnerId {} ", toResInstanceUid, componentId, relationInJson.getType(), relationInJson.getCapabilityOwnerId(), + relationInJson.getRequirementOwnerId()); + iterator.remove(); + + // update calculated cap/req + StorageOperationStatus status = updateCalculatedCapabiltyAfterDeleteRelation(calculatedCapability, fulfilledCapability, toResInstanceUid, relationInJson, relationPair); + if (status != StorageOperationStatus.OK) { + return Either.right(status); + } + status = updateCalculatedRequirementsAfterDeleteRelation(calculatedRequirement, fulfilledRequirement, fromResInstanceUid, relationInJson, relationPair); + if (status != StorageOperationStatus.OK) { + return Either.right(status); + } + isDeleted = true; + } + } + } + if (!isDeleted) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No relation to delete from {} to {} capabilty {} capOwnerId {} reqOwnerId {} ", toResInstanceUid, componentId, relationPair.getCapability(), + relationPair.getRelation().getCapabilityOwnerId(), relationPair.getRelation().getRequirementOwnerId()); + return Either.right(StorageOperationStatus.NOT_FOUND); + } + } + StorageOperationStatus status = updateCustomizationUUID(fromResInstanceUid, compositionDataDefinition); + if (status != StorageOperationStatus.OK) { + return Either.right(status); + } + status = updateCustomizationUUID(toResInstanceUid, compositionDataDefinition); + if (status != StorageOperationStatus.OK) { + return Either.right(status); + } + + // update jsons + // update metadata of container and composition json + status = updateAllAndCalculatedCapReqOnGraph(componentId, containerV, capResult, capFullResult, reqResult, reqFullResult); + if (status != StorageOperationStatus.OK) { + return Either.right(status); + } + + return Either.left(requirementDef); + } + + /** + * Retrieves fulfilled requirement according to relation and received predicate + * + * @param componentId + * @param instanceId + * @param foundRelation + * @param predicate + * @return + */ + public Either<RequirementDataDefinition, StorageOperationStatus> getFulfilledRequirementByRelation(String componentId, String instanceId, RequirementCapabilityRelDef foundRelation, + BiPredicate<RelationshipInfo, RequirementDataDefinition> predicate) { + + Either<RequirementDataDefinition, StorageOperationStatus> result = null; + Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqFullResult = null; + MapListRequirementDataDefinition reqMapOfLists = null; + Optional<RequirementDataDefinition> foundRequirement; + RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation(); + Either<GraphVertex, TitanOperationStatus> containerVEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll); + if (containerVEither.isRight()) { + TitanOperationStatus error = containerVEither.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FETCH_CONTAINER_VERTEX_ERROR, componentId, error); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error)); + } + if (result == null) { + GraphVertex containerV = containerVEither.left().value(); + reqFullResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS); + if (reqFullResult.isRight()) { + result = Either.right(reqFullResult.right().value()); + } + } + if (result == null) { + Map<String, MapListRequirementDataDefinition> fulfilledRequirement = reqFullResult.left().value().getRight(); + reqMapOfLists = fulfilledRequirement.get(instanceId); + if (reqMapOfLists == null) { + result = Either.right(StorageOperationStatus.NOT_FOUND); + } + } + if (result == null && reqMapOfLists != null) { + for (ListRequirementDataDefinition requirements : reqMapOfLists.getMapToscaDataDefinition().values()) { + foundRequirement = requirements.getListToscaDataDefinition().stream().filter(req -> predicate.test(relationshipInfo, req)).findFirst(); + if (foundRequirement.isPresent()) { + result = Either.left(foundRequirement.get()); + } + } + } + return result; + } + + /** + * Retrieves fulfilled capability according to relation and received predicate + * + * @param componentId + * @param instanceId + * @param foundRelation + * @param predicate + * @return + */ + public Either<CapabilityDataDefinition, StorageOperationStatus> getFulfilledCapabilityByRelation(String componentId, String instanceId, RequirementCapabilityRelDef foundRelation, + BiPredicate<RelationshipInfo, CapabilityDataDefinition> predicate) { + + Either<CapabilityDataDefinition, StorageOperationStatus> result = null; + Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> capFullResult = null; + MapListCapabilityDataDefinition capMapOfLists = null; + Optional<CapabilityDataDefinition> foundRequirement; + + RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation(); + Either<GraphVertex, TitanOperationStatus> containerVEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll); + if (containerVEither.isRight()) { + TitanOperationStatus error = containerVEither.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FETCH_CONTAINER_VERTEX_ERROR, componentId, error); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error)); + } + if (result == null) { + GraphVertex containerV = containerVEither.left().value(); + capFullResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES); + if (capFullResult.isRight()) { + result = Either.right(capFullResult.right().value()); + } + } + if (result == null) { + Map<String, MapListCapabilityDataDefinition> fulfilledCapability = capFullResult.left().value().getRight(); + capMapOfLists = fulfilledCapability.get(instanceId); + if (capMapOfLists == null) { + result = Either.right(StorageOperationStatus.NOT_FOUND); + } + } + if (result == null && capMapOfLists != null) { + for (ListCapabilityDataDefinition capabilities : capMapOfLists.getMapToscaDataDefinition().values()) { + foundRequirement = capabilities.getListToscaDataDefinition().stream().filter(cap -> predicate.test(relationshipInfo, cap)).findFirst(); + if (foundRequirement.isPresent()) { + result = Either.left(foundRequirement.get()); + } + } + } + return result; + } + + private StorageOperationStatus updateCalculatedRequirementsAfterDeleteRelation(Map<String, MapListRequirementDataDefinition> calculatedRequirement, Map<String, MapListRequirementDataDefinition> fullFilledRequirement, String fromResInstanceUid, + RelationshipInstDataDefinition relation, CapabilityRequirementRelationship relationship) { + StorageOperationStatus status; + String hereIsTheKey = null; + MapListRequirementDataDefinition reqByInstance = calculatedRequirement.get(fromResInstanceUid); + if (reqByInstance == null || reqByInstance.findKeyByItemUidMatch(relation.getRequirementId()) == null) { + // move from fulfilled + status = moveFromFullFilledRequirement(calculatedRequirement, fullFilledRequirement, fromResInstanceUid, relation, hereIsTheKey, relationship); + } else { + hereIsTheKey = reqByInstance.findKeyByItemUidMatch(relation.getRequirementId()); + ListRequirementDataDefinition reqByType = reqByInstance.findByKey(hereIsTheKey); + Optional<RequirementDataDefinition> requirementOptional = reqByType.getListToscaDataDefinition().stream() + .filter(req -> req.getOwnerId().equals(relation.getRequirementOwnerId()) && req.getName().equals(relation.getRequirement()) && req.getUniqueId().equals(relation.getRequirementId())).findFirst(); + + if (requirementOptional.isPresent()) { + + RequirementDataDefinition requirement = requirementOptional.get(); + String leftOccurrences = requirement.getLeftOccurrences(); + if (leftOccurrences != null && !leftOccurrences.equals(RequirementDataDefinition.MAX_OCCURRENCES)) { + Integer leftIntValue = Integer.parseInt(leftOccurrences); + ++leftIntValue; + requirement.setLeftOccurrences(String.valueOf(leftIntValue)); + } + if (relationship != null) { + relationship.setRequirement(requirement); + } + status = StorageOperationStatus.OK; + } else { + // move from fulfilled + status = moveFromFullFilledRequirement(calculatedRequirement, fullFilledRequirement, fromResInstanceUid, relation, hereIsTheKey, relationship); + } + } + return status; + } + + private StorageOperationStatus updateCalculatedCapabiltyAfterDeleteRelation(Map<String, MapListCapabilityDataDefinition> calculatedCapability, Map<String, MapListCapabilityDataDefinition> fullFilledCapability, String toResInstanceUid, + RelationshipInstDataDefinition relation, CapabilityRequirementRelationship relationship) { + StorageOperationStatus status; + String hereIsTheKey = null; + MapListCapabilityDataDefinition capByInstance = calculatedCapability.get(toResInstanceUid); + if (capByInstance == null || capByInstance.findKeyByItemUidMatch(relation.getCapabilityId()) == null) { + // move from fulfilled + status = moveFromFullFilledCapabilty(calculatedCapability, fullFilledCapability, toResInstanceUid, relation, hereIsTheKey, relationship); + } else { + hereIsTheKey = capByInstance.findKeyByItemUidMatch(relation.getCapabilityId()); + ListCapabilityDataDefinition capByType = capByInstance.findByKey(hereIsTheKey); + Optional<CapabilityDataDefinition> capabilityOptional = capByType.getListToscaDataDefinition().stream().filter(cap -> cap.getOwnerId().equals(relation.getCapabilityOwnerId()) && cap.getUniqueId().equals(relation.getCapabilityId())) + .findFirst(); + + if (capabilityOptional.isPresent()) { + + CapabilityDataDefinition capability = capabilityOptional.get(); + String leftOccurrences = capability.getLeftOccurrences(); + if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) { + Integer leftIntValue = Integer.parseInt(leftOccurrences); + ++leftIntValue; + capability.setLeftOccurrences(String.valueOf(leftIntValue)); + } + if (relationship != null) { + relationship.setCapability(capability); + } + status = StorageOperationStatus.OK; + } else { + // move from fulfilled + status = moveFromFullFilledCapabilty(calculatedCapability, fullFilledCapability, toResInstanceUid, relation, hereIsTheKey, relationship); + } + } + return status; + } + + private StorageOperationStatus moveFromFullFilledCapabilty(Map<String, MapListCapabilityDataDefinition> calculatedCapability, Map<String, MapListCapabilityDataDefinition> fullFilledCapability, String toResInstanceUid, + RelationshipInstDataDefinition relation, String hereIsTheKey, CapabilityRequirementRelationship relationship) { + MapListCapabilityDataDefinition capByInstance = fullFilledCapability.get(toResInstanceUid); + if (capByInstance == null) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No capability in fulfilled list for instance {} ", toResInstanceUid); + return StorageOperationStatus.GENERAL_ERROR; + } + if (null == hereIsTheKey) + hereIsTheKey = capByInstance.findKeyByItemUidMatch(relation.getCapabilityId()); + if (null == hereIsTheKey) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No capability with id {} in fulfilled list for instance {} ", relation.getCapabilityId(), toResInstanceUid); + return StorageOperationStatus.GENERAL_ERROR; + } + ListCapabilityDataDefinition capByType = capByInstance.findByKey(hereIsTheKey); + Iterator<CapabilityDataDefinition> iterator = capByType.getListToscaDataDefinition().iterator(); + boolean found = false; + while (iterator.hasNext()) { + CapabilityDataDefinition cap = iterator.next(); + if (cap.getOwnerId().equals(relation.getCapabilityOwnerId()) && cap.getUniqueId().equals(relation.getCapabilityId())) { + found = true; + iterator.remove(); + // return to calculated list + String leftOccurrences = cap.getLeftOccurrences(); + Integer leftIntValue = Integer.parseInt(leftOccurrences); + ++leftIntValue; + cap.setLeftOccurrences(String.valueOf(leftIntValue)); + + MapListCapabilityDataDefinition mapListCapaDataDef = calculatedCapability.get(toResInstanceUid); + if (mapListCapaDataDef == null) { + mapListCapaDataDef = new MapListCapabilityDataDefinition(); + } + ListCapabilityDataDefinition findByKey = mapListCapaDataDef.findByKey(hereIsTheKey); + if (findByKey == null) { + findByKey = new ListCapabilityDataDefinition(); + mapListCapaDataDef.put(hereIsTheKey, findByKey); + } + findByKey.add(cap); + if (relationship != null) + relationship.setCapability(cap); + break; + } + } + if (!found) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No capability type {} with ownerId {} in fulfilled list for instance {} ", hereIsTheKey, relation.getCapabilityOwnerId(), toResInstanceUid); + return StorageOperationStatus.GENERAL_ERROR; + } + return StorageOperationStatus.OK; + } + + private StorageOperationStatus moveFromFullFilledRequirement(Map<String, MapListRequirementDataDefinition> calculatedRequirement, Map<String, MapListRequirementDataDefinition> fullFilledRequirement, String fromResInstanceUid, + RelationshipInstDataDefinition relation, String hereIsTheKey, CapabilityRequirementRelationship relationship) { + MapListRequirementDataDefinition reqByInstance = fullFilledRequirement.get(fromResInstanceUid); + if (reqByInstance == null) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No requirement in fullfilled list for instance {} ", fromResInstanceUid); + return StorageOperationStatus.GENERAL_ERROR; + } + if (null == hereIsTheKey) + hereIsTheKey = reqByInstance.findKeyByItemUidMatch(relation.getRequirementId()); + if (null == hereIsTheKey) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No requirement with id {} in fulfilled list for instance {} ", relation.getRequirementId(), fromResInstanceUid); + return StorageOperationStatus.GENERAL_ERROR; + } + ListRequirementDataDefinition reqByType = reqByInstance.findByKey(hereIsTheKey); + Iterator<RequirementDataDefinition> iterator = reqByType.getListToscaDataDefinition().iterator(); + boolean found = false; + while (iterator.hasNext()) { + RequirementDataDefinition req = iterator.next(); + if (req.getOwnerId().equals(relation.getRequirementOwnerId()) && req.getName().equals(relation.getRequirement()) && req.getUniqueId().equals(relation.getRequirementId())) { + found = true; + iterator.remove(); + // return to calculated list + String leftOccurrences = req.getLeftOccurrences(); + Integer leftIntValue = Integer.parseInt(leftOccurrences); + ++leftIntValue; + req.setLeftOccurrences(String.valueOf(leftIntValue)); + + MapListRequirementDataDefinition mapListReqDataDef = calculatedRequirement.get(fromResInstanceUid); + if (mapListReqDataDef == null) { + mapListReqDataDef = new MapListRequirementDataDefinition(); + } + ListRequirementDataDefinition findByKey = mapListReqDataDef.findByKey(hereIsTheKey); + if (findByKey == null) { + findByKey = new ListRequirementDataDefinition(); + mapListReqDataDef.put(hereIsTheKey, findByKey); + } + findByKey.add(req); + if (relationship != null) + relationship.setRequirement(req); + break; + } + } + if (!found) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No requirement type {} with ownerId {} in fulfilled list for instance {} ", hereIsTheKey, relation.getRequirementOwnerId(), fromResInstanceUid); + return StorageOperationStatus.GENERAL_ERROR; + } + return StorageOperationStatus.OK; + + } + + public StorageOperationStatus updateCustomizationUUID(String componentInstanceId, CompositionDataDefinition compositionDataDefinition) { + ComponentInstanceDataDefinition componentInstance = compositionDataDefinition.getComponentInstances().get(componentInstanceId); + + if (componentInstance == null) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch component instance by id {} from map of instances ", componentInstanceId); + return StorageOperationStatus.NOT_FOUND; + } + UUID uuid = UUID.randomUUID(); + componentInstance.setCustomizationUUID(uuid.toString()); + + return StorageOperationStatus.OK; + } + + public <T extends ToscaDataDefinition> Either<Map<JsonPresentationFields, T>, StorageOperationStatus> connectInstancesInContainer(String fromResInstanceUid, String toResInstanceUid, RelationshipInfo relationPair, boolean originUI, + Map<String, MapListCapabilityDataDefinition> calculatedCapabilty, Map<String, MapListRequirementDataDefinition> calculatedRequirement, Map<String, MapListCapabilityDataDefinition> fullfilledCapabilty, + Map<String, MapListRequirementDataDefinition> fullfilledRequirement, CompositionDataDefinition compositionDataDefinition, String containerId) { + String requirement = relationPair.getRequirement(); + Map<String, ComponentInstanceDataDefinition> componentInstances = compositionDataDefinition.getComponentInstances(); + + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to associate resource instance {} to resource instance {} under component {}. Requirement is {}.", fromResInstanceUid, toResInstanceUid, containerId, requirement); + + ComponentInstanceDataDefinition fromResourceInstData = componentInstances.get(fromResInstanceUid); + if (fromResourceInstData == null) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find from resource instance {}.", fromResInstanceUid); + return Either.right(StorageOperationStatus.NOT_FOUND); + } + ComponentInstanceDataDefinition toResourceInstData = componentInstances.get(toResInstanceUid); + if (toResourceInstData == null) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find to resource instance {}.", toResInstanceUid); + return Either.right(StorageOperationStatus.NOT_FOUND); + } + + Either<Map<JsonPresentationFields, T>, StorageOperationStatus> reqVsCap = connectRequirementVsCapability(fromResourceInstData, toResourceInstData, relationPair, originUI, calculatedCapabilty, calculatedRequirement, fullfilledCapabilty, + fullfilledRequirement, containerId); + if (reqVsCap.isRight()) { + StorageOperationStatus status = reqVsCap.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to connect requirement {} between resource instance {} to resource instance {}. status is {}", requirement, fromResInstanceUid, toResInstanceUid, status); + return Either.right(status); + } + Map<JsonPresentationFields, T> relationship = reqVsCap.left().value(); + + // add to json new relations + compositionDataDefinition.addRelation(((RelationshipInstDataDefinition) relationship.get(JsonPresentationFields.RELATIONSHIP)).getUniqueId(), (RelationshipInstDataDefinition) relationship.get(JsonPresentationFields.RELATIONSHIP)); + + return Either.left(relationship); + } + + private Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> fetchContainerCalculatedCapability(GraphVertex containerV, EdgeLabelEnum capLabel) { + + Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, TitanOperationStatus> calculatedCapabiltyEither = getDataAndVertexFromGraph(containerV, capLabel); + if (calculatedCapabiltyEither.isRight()) { + TitanOperationStatus error = calculatedCapabiltyEither.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch calculated capabilties for container {}.", containerV.getUniqueId(), error); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error)); + } + Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>> calculatedCapabilty = calculatedCapabiltyEither.left().value(); + return Either.left(calculatedCapabilty); + } + + private Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> fetchContainerCalculatedRequirement(GraphVertex containerV, EdgeLabelEnum reqLabel) { + Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, TitanOperationStatus> calculatedRequirementEither = getDataAndVertexFromGraph(containerV, reqLabel); + if (calculatedRequirementEither.isRight()) { + TitanOperationStatus error = calculatedRequirementEither.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch calculated requirements for container {}.", containerV.getUniqueId(), error); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error)); + } + Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>> calculatedRequirement = calculatedRequirementEither.left().value(); + return Either.left(calculatedRequirement); + } + + @SuppressWarnings("unchecked") + private <T extends ToscaDataDefinition> Either<Map<JsonPresentationFields, T>, StorageOperationStatus> connectRequirementVsCapability(ComponentInstanceDataDefinition fromResInstance, ComponentInstanceDataDefinition toResInstance, + RelationshipInfo relationPair, boolean originUI, Map<String, MapListCapabilityDataDefinition> calculatedCapabilty, Map<String, MapListRequirementDataDefinition> calculatedRequirement, + Map<String, MapListCapabilityDataDefinition> fullfilledCapabilty, Map<String, MapListRequirementDataDefinition> fullfilledRequirement, String containerId) { + String type = relationPair.getRelationship().getType(); + // capability + + String toInstId = toResInstance.getUniqueId(); + MapListCapabilityDataDefinition MapListCapabilityDataDefinition = calculatedCapabilty.get(toInstId); + Map<JsonPresentationFields, T> capReqRelationship = new EnumMap<>(JsonPresentationFields.class); + + if (MapListCapabilityDataDefinition == null) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch calculated capabilities for instance {} in container {}.", toInstId, containerId); + return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); + } + ListCapabilityDataDefinition listCapabilityDataDefinition = MapListCapabilityDataDefinition.getMapToscaDataDefinition().get(type); + if (listCapabilityDataDefinition == null) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch calculated capabilities for type {} for instance {} in container {}.", type, toInstId, containerId); + return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); + } + CapabilityDataDefinition capabilityForRelation = null; + Iterator<CapabilityDataDefinition> iteratorCap = listCapabilityDataDefinition.getListToscaDataDefinition().iterator(); + while (iteratorCap.hasNext()) { + CapabilityDataDefinition cap = iteratorCap.next(); + if (cap.getUniqueId().equals(relationPair.getCapabilityUid()) && cap.getOwnerId().equals(relationPair.getCapabilityOwnerId())) { + capabilityForRelation = cap; + capReqRelationship.put(JsonPresentationFields.CAPAPILITY, (T) capabilityForRelation); + String leftOccurrences = cap.getLeftOccurrences(); + if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) { + Integer leftIntValue = Integer.parseInt(leftOccurrences); + if (leftIntValue > 0) { + --leftIntValue; + capabilityForRelation.setLeftOccurrences(String.valueOf(leftIntValue)); + if (leftIntValue == 0) { + // remove from calculated + iteratorCap.remove(); + // move to fulfilled + MapListCapabilityDataDefinition mapListCapabiltyFullFilledInst = fullfilledCapabilty.get(toInstId); + if (mapListCapabiltyFullFilledInst == null) { + mapListCapabiltyFullFilledInst = new MapListCapabilityDataDefinition(); + fullfilledCapabilty.put(toInstId, mapListCapabiltyFullFilledInst); + } + + ListCapabilityDataDefinition listCapabilityFull = mapListCapabiltyFullFilledInst.findByKey(type); + if (listCapabilityFull == null) { + listCapabilityFull = new ListCapabilityDataDefinition(); + mapListCapabiltyFullFilledInst.put(type, listCapabilityFull); + } + listCapabilityFull.add(capabilityForRelation); + } + break; + } else { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No left occurrences capabilty {} to {} in container {}.", capabilityForRelation.getType(), toInstId, containerId); + return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); + } + } + } + } + if (capabilityForRelation == null) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch capabilty for type {} for instance {} in container {}.", type, toInstId, containerId); + return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); + } + + // requirements + String fromInstId = fromResInstance.getUniqueId(); + MapListRequirementDataDefinition mapListRequirementDataDefinition = calculatedRequirement.get(fromInstId); + if (mapListRequirementDataDefinition == null) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch calculated requirements for instance {} in container {}.", fromInstId, containerId); + return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); + } + ListRequirementDataDefinition listRequirementDataDefinition = mapListRequirementDataDefinition.getMapToscaDataDefinition().get(type); + if (listRequirementDataDefinition == null) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch calculated requirements for type {} for instance {} in container {}.", type, fromInstId, containerId); + return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); + } + + RequirementDataDefinition requirementForRelation = null; + Iterator<RequirementDataDefinition> iteratorReq = listRequirementDataDefinition.getListToscaDataDefinition().iterator(); + while (iteratorReq.hasNext()) { + RequirementDataDefinition req = iteratorReq.next(); + if (req.getUniqueId().equals(relationPair.getRequirementUid()) && req.getOwnerId().equals(relationPair.getRequirementOwnerId())) { + requirementForRelation = req; + capReqRelationship.put(JsonPresentationFields.REQUIREMENT, (T) requirementForRelation); + String leftOccurrences = req.getLeftOccurrences(); + if (leftOccurrences != null && !leftOccurrences.equals(RequirementDataDefinition.MAX_OCCURRENCES)) { + Integer leftIntValue = Integer.parseInt(leftOccurrences); + if (leftIntValue > 0) { + --leftIntValue; + req.setLeftOccurrences(String.valueOf(leftIntValue)); + if (leftIntValue == 0) { + // remove from calculated + iteratorReq.remove(); + // move to fulfilled + MapListRequirementDataDefinition mapListRequirementFullFilledInst = fullfilledRequirement.get(fromInstId); + if (mapListRequirementFullFilledInst == null) { + mapListRequirementFullFilledInst = new MapListRequirementDataDefinition(); + fullfilledRequirement.put(fromInstId, mapListRequirementFullFilledInst); + } + + ListRequirementDataDefinition listRequirementFull = mapListRequirementFullFilledInst.findByKey(type); + if (listRequirementFull == null) { + listRequirementFull = new ListRequirementDataDefinition(); + mapListRequirementFullFilledInst.put(type, listRequirementFull); + } + listRequirementFull.add(requirementForRelation); + } + break; + } else { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No left occurrences requirement {} from {} to {} in container {}.", requirementForRelation.getCapability(), fromInstId, toInstId, containerId); + return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); + } + } + } + } + if (requirementForRelation == null) { + CommonUtility.addRecordToLog(log, 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(log, 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); + } + + RelationshipInstDataDefinition relationshipTypeData = buildRelationshipInstData(fromInstId, toInstId, relationPair, originUI); + if (requirementForRelation.getRelationship() != null) + relationshipTypeData.setType(requirementForRelation.getRelationship()); + capReqRelationship.put(JsonPresentationFields.RELATIONSHIP, (T) relationshipTypeData); + return Either.left(capReqRelationship); + } + + private RelationshipInstDataDefinition buildRelationshipInstData(String fromResInstanceUid, String toInstId, RelationshipInfo relationPair, boolean originUI) { + + RelationshipInstDataDefinition relationshipInstData = new RelationshipInstDataDefinition(); + relationshipInstData.setUniqueId(UniqueIdBuilder.buildRelationsipInstInstanceUid(fromResInstanceUid, toInstId)); + + relationshipInstData.setType(relationPair.getRelationship().getType()); + Long creationDate = System.currentTimeMillis(); + relationshipInstData.setCreationTime(creationDate); + relationshipInstData.setModificationTime(creationDate); + relationshipInstData.setCapabilityOwnerId(relationPair.getCapabilityOwnerId()); + relationshipInstData.setRequirementOwnerId(relationPair.getRequirementOwnerId()); + relationshipInstData.setCapabilityId(relationPair.getCapabilityUid()); + relationshipInstData.setRequirementId(relationPair.getRequirementUid()); + relationshipInstData.setFromId(fromResInstanceUid); + relationshipInstData.setToId(toInstId); + relationshipInstData.setRequirement(relationPair.getRequirement()); + relationshipInstData.setCapability(relationPair.getCapability()); + relationshipInstData.setOriginUI(originUI); + + return relationshipInstData; + } + + public StorageOperationStatus associateComponentInstancesToComponent(Component containerComponent, Map<ComponentInstance, Resource> resourcesInstancesMap, GraphVertex containerVertex, boolean allowDeleted) { + + StorageOperationStatus result = null; + String containerId = containerComponent.getUniqueId(); + Map<String, ComponentInstanceDataDefinition> instancesJsonData = null; + Either<GraphVertex, TitanOperationStatus> updateElement = null; + if (!validateInstanceNames(resourcesInstancesMap)) { + result = StorageOperationStatus.INCONSISTENCY; + } + if (result == null) { + if (!validateInstanceNames(resourcesInstancesMap)) { + result = StorageOperationStatus.INCONSISTENCY; + } + } + if (result == null && !allowDeleted) { + if (!validateDeletedResources(resourcesInstancesMap)) { + result = StorageOperationStatus.INCONSISTENCY; + } + } + if (result == null) { + instancesJsonData = convertToComponentInstanceDataDefinition(resourcesInstancesMap, containerId); + } + if (result == null && MapUtils.isNotEmpty(instancesJsonData)) { + containerVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); + Map<String, CompositionDataDefinition> compositions = new HashMap<>(); + CompositionDataDefinition composition = new CompositionDataDefinition(); + composition.setComponentInstances(instancesJsonData); + compositions.put(JsonConstantKeysEnum.COMPOSITION.getValue(), composition); + containerVertex.setJson(compositions); + updateElement = titanDao.updateVertex(containerVertex); + if (updateElement.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update topology template {} with new component instances. ", containerComponent.getName()); + result = DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value()); + } + } + if (result == null && updateElement != null) { + GraphVertex vertexC = updateElement.left().value(); + instancesJsonData.entrySet().forEach(i ->createInstanceEdge(vertexC, i.getValue())); + result = StorageOperationStatus.OK; + } + return result; + } + + private Map<String, ComponentInstanceDataDefinition> convertToComponentInstanceDataDefinition(Map<ComponentInstance, Resource> resourcesInstancesMap, String containerId) { + + Map<String, ComponentInstanceDataDefinition> instances = new HashMap<>(); + for (Entry<ComponentInstance, Resource> entry : resourcesInstancesMap.entrySet()) { + ComponentInstanceDataDefinition instance = buildComponentInstanceDataDefinition(entry.getKey(), containerId, null, true, ModelConverter.convertToToscaElement(entry.getValue())); + instances.put(instance.getUniqueId(), instance); + } + return instances; + } + + private boolean validateDeletedResources(Map<ComponentInstance, Resource> resourcesInstancesMap) { + boolean result = true; + for (Resource resource : resourcesInstancesMap.values()) { + if (resource.getIsDeleted() != null && resource.getIsDeleted()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Component {} is already deleted. Cannot add component instance. ", resource.getName()); + result = false; + break; + } + } + return result; + } + + private boolean validateInstanceNames(Map<ComponentInstance, Resource> resourcesInstancesMap) { + boolean result = true; + Set<String> names = new HashSet<>(); + for (ComponentInstance instance : resourcesInstancesMap.keySet()) { + if (StringUtils.isEmpty(instance.getName())) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Component instance {} name is empty. Cannot add component instance. ", instance.getUniqueId()); + result = false; + break; + } else if (names.contains(instance.getName())) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Component instance with the name {} already exsists. Cannot add component instance. ", instance.getName()); + result = false; + break; + } else { + names.add(instance.getName()); + } + } + return result; + } + + public StorageOperationStatus addDeploymentArtifactsToInstance(String toscaElementId, String instanceId, Map<String, ArtifactDataDefinition> instDeplArtifacts) { + return addArtifactsToInstance(toscaElementId, instanceId, instDeplArtifacts, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS); + } + + public StorageOperationStatus addInformationalArtifactsToInstance(String toscaElementId, String instanceId, Map<String, ArtifactDataDefinition> instDeplArtifacts) { + return addArtifactsToInstance(toscaElementId, instanceId, instDeplArtifacts, EdgeLabelEnum.INSTANCE_ARTIFACTS, VertexTypeEnum.INSTANCE_ARTIFACTS); + } + + public StorageOperationStatus addArtifactsToInstance(String toscaElementId, String instanceId, Map<String, ArtifactDataDefinition> instDeplArtifacts, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexType) { + Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(toscaElementId, JsonParseFlagEnum.NoParse); + if (metadataVertex.isRight()) { + TitanOperationStatus status = metadataVertex.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + return DaoStatusConverter.convertTitanStatusToStorageStatus(status); + } + MapArtifactDataDefinition instArtifacts = new MapArtifactDataDefinition(instDeplArtifacts); + return addToscaDataDeepElementsBlockToToscaElement(metadataVertex.left().value(), edgeLabel, vertexType, instArtifacts, instanceId); + + } + + @SuppressWarnings({ "unchecked" }) + public StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId) { + Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll); + if (metadataVertex.isRight()) { + TitanOperationStatus status = metadataVertex.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + return DaoStatusConverter.convertTitanStatusToStorageStatus(status); + } + GraphVertex metaVertex = metadataVertex.left().value(); + Map<String, CompositionDataDefinition> json = (Map<String, CompositionDataDefinition>) metaVertex.getJson(); + CompositionDataDefinition compositionDataDefinition = json.get(JsonConstantKeysEnum.COMPOSITION.getValue()); + StorageOperationStatus status = updateCustomizationUUID(instanceId, compositionDataDefinition); + if (status != StorageOperationStatus.OK) { + log.debug("Failed to update customization UUID for instance {} in component {} error {}", instanceId, componentId, status); + return status; + } + Either<GraphVertex, TitanOperationStatus> updateVertex = titanDao.updateVertex(metaVertex); + if (updateVertex.isRight()) { + log.debug("Failed to update vertex of component {} error {}", componentId, updateVertex.right().value()); + return DaoStatusConverter.convertTitanStatusToStorageStatus(updateVertex.right().value()); + } + return StorageOperationStatus.OK; + } + + public StorageOperationStatus generateCustomizationUUIDOnInstanceGroup(String componentId, String instanceId, List<String> groupInstances) { + if (groupInstances != null) { + Either<Map<String, MapGroupsDataDefinition>, TitanOperationStatus> dataFromGraph = getDataFromGraph(componentId, EdgeLabelEnum.INST_GROUPS); + if (dataFromGraph.isRight()) { + return DaoStatusConverter.convertTitanStatusToStorageStatus(dataFromGraph.right().value()); + } + MapGroupsDataDefinition grInstPerInstance = dataFromGraph.left().value().get(instanceId); + if (grInstPerInstance == null) { + log.debug("No instance groups for instance {} in component {}", instanceId, componentId); + return StorageOperationStatus.NOT_FOUND; + } + for (String instGroupForUpdate : groupInstances) { + GroupInstanceDataDefinition groupInst = grInstPerInstance.findByKey(instGroupForUpdate); + if (groupInst == null) { + log.debug("No group instance {} in group list for instance {} in component {}", instGroupForUpdate, instanceId, componentId); + continue; + } + UUID uuid = UUID.randomUUID(); + groupInst.setCustomizationUUID(uuid.toString()); + } + + } + return StorageOperationStatus.OK; + } + + public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupInstance> groupInstances) { + + return addToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, + new MapDataDefinition<>(groupInstances.stream().collect(Collectors.toMap(GroupInstanceDataDefinition::getName, gi -> gi))), componentInstance.getUniqueId()); + } + + public StorageOperationStatus addDeploymentArtifactsToComponentInstance(Component containerComponent, ComponentInstance componentInstance, Map<String, ArtifactDefinition> deploymentArtifacts) { + + return addToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, new MapDataDefinition<>(deploymentArtifacts), + componentInstance.getUniqueId()); + } + + public StorageOperationStatus updateComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) { + + List<String> pathKeys = new ArrayList<>(); + pathKeys.add(componentInstanceId); + return updateToscaDataDeepElementOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, property, pathKeys, JsonPresentationFields.NAME); + } + + public StorageOperationStatus updateComponentInstanceCapabilityProperty(Component containerComponent, String componentInstanceId, String capabilityUniqueId, ComponentInstanceProperty property) { + List<String> pathKeys = new ArrayList<>(); + pathKeys.add(componentInstanceId); + pathKeys.add(capabilityUniqueId); + return updateToscaDataDeepElementOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, property, pathKeys, JsonPresentationFields.NAME); + } + + public StorageOperationStatus overrideComponentCapabilitiesProperties(Component containerComponent, Map<String, MapCapabilityProperty> 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); + return addToscaDataDeepElementToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, property, pathKeys, JsonPresentationFields.NAME); + } + + public StorageOperationStatus updateComponentInstanceProperties(Component containerComponent, String componentInstanceId, List<ComponentInstanceProperty> properties) { + List<String> pathKeys = new ArrayList<>(); + pathKeys.add(componentInstanceId); + return updateToscaDataDeepElementsOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, properties, pathKeys, JsonPresentationFields.NAME); + } + + public StorageOperationStatus updateComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) { + + List<String> pathKeys = new ArrayList<>(); + pathKeys.add(componentInstanceId); + return updateToscaDataDeepElementOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, property, pathKeys, JsonPresentationFields.NAME); + } + + public StorageOperationStatus updateComponentInstanceInputs(Component containerComponent, String componentInstanceId, List<ComponentInstanceInput> properties) { + List<String> pathKeys = new ArrayList<>(); + pathKeys.add(componentInstanceId); + return updateToscaDataDeepElementsOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, properties, pathKeys, JsonPresentationFields.NAME); + } + + public StorageOperationStatus addComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) { + List<String> pathKeys = new ArrayList<>(); + pathKeys.add(componentInstanceId); + return addToscaDataDeepElementToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, property, pathKeys, JsonPresentationFields.NAME); + } + + public StorageOperationStatus createInstanceEdge(GraphVertex metadataVertex, ComponentInstanceDataDefinition componentInstance) { + String instUniqueId = componentInstance.getUniqueId(); + + // create edge between container and origin ( in case of proxy this edge will be to ProxyService node type) + StorageOperationStatus result = createOrUpdateInstanceEdge(metadataVertex, EdgeLabelEnum.INSTANCE_OF, componentInstance.getComponentUid(), instUniqueId).either(v -> StorageOperationStatus.OK, + DaoStatusConverter::convertTitanStatusToStorageStatus); + + if (result == StorageOperationStatus.OK && componentInstance.getIsProxy()) { + // create edge between container and service origin + result = createOrUpdateInstanceEdge(metadataVertex, EdgeLabelEnum.PROXY_OF, componentInstance.getSourceModelUid(), instUniqueId) + .either(v -> StorageOperationStatus.OK, DaoStatusConverter::convertTitanStatusToStorageStatus); + } + return result; + } + + public StorageOperationStatus createAllottedOfEdge(String componentId, String instanceId, String serviceUUID) { + Either<GraphVertex, TitanOperationStatus> vertexById = titanDao.getVertexById(componentId); + if ( vertexById.isRight() ){ + log.debug("Failed to fetch component metadata vertex for id {} error {}", componentId, vertexById.right().value()); + return DaoStatusConverter.convertTitanStatusToStorageStatus(vertexById.right().value()); + } + GraphVertex metadataVertex = vertexById.left().value(); + + EnumMap<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class); + props.put(GraphPropertyEnum.UUID, serviceUUID); + props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + + EnumMap<GraphPropertyEnum, Object> hasNot = new EnumMap<>(GraphPropertyEnum.class); + hasNot.put(GraphPropertyEnum.IS_DELETED, true); + + Either<List<GraphVertex>, TitanOperationStatus> byCriteria = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, props,hasNot, JsonParseFlagEnum.ParseMetadata ); + if ( byCriteria.isRight() ){ + log.debug("Failed to fetch vertex by criteria {} error {}", props, byCriteria.right().value()); + return DaoStatusConverter.convertTitanStatusToStorageStatus(byCriteria.right().value()); + } + List<GraphVertex> vertecies = byCriteria.left().value(); + StorageOperationStatus result = StorageOperationStatus.OK; + if ( vertecies != null ){ + GraphVertex serviceVertex = vertecies.get(0); + //remove previous edges + + log.debug("Try to create or update edge between resource {} and service {} ", metadataVertex, serviceVertex.getUniqueId()); + // create edge between container and service reference + result = createOrUpdateInstanceEdge(metadataVertex, EdgeLabelEnum.ALLOTTED_OF, serviceVertex.getUniqueId(), instanceId).either(v -> StorageOperationStatus.OK, + DaoStatusConverter::convertTitanStatusToStorageStatus); + } + return result; + } + + + public StorageOperationStatus removeInstanceEdge(GraphVertex metadataVertex, ComponentInstanceDataDefinition componentInstance) { + String instUniqueId = componentInstance.getUniqueId(); + + // create edge between container and origin ( in case of proxy this edge will be to ProxyService node type) + StorageOperationStatus result = removeOrUpdateInstanceEdge(metadataVertex, EdgeLabelEnum.INSTANCE_OF, componentInstance.getComponentUid(), instUniqueId) + .either(v -> StorageOperationStatus.OK, + DaoStatusConverter::convertTitanStatusToStorageStatus); + + if (componentInstance.getIsProxy()) { + // create edge between container and service origin + result = removeOrUpdateInstanceEdge(metadataVertex, EdgeLabelEnum.PROXY_OF, componentInstance.getSourceModelUid(), instUniqueId) + .either(v -> StorageOperationStatus.OK, DaoStatusConverter::convertTitanStatusToStorageStatus); + } + return result; + } + + private Either<GraphVertex, TitanOperationStatus> createOrUpdateInstanceEdge(GraphVertex metadataVertex, EdgeLabelEnum edgeLabel, String componentUid, String instUniqueId) { + Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class); + properties.put(GraphPropertyEnum.UNIQUE_ID, componentUid); + + return titanDao.getEdgeByChildrenVertexProperties(metadataVertex, edgeLabel, properties) + .left() + .bind(v -> addInstanceToPropertyOnEdge(instUniqueId, v, metadataVertex)) + .right() + .bind(s -> createInstanceEdge(metadataVertex, edgeLabel, componentUid, instUniqueId, s)); + } + + private Either<GraphVertex, TitanOperationStatus> removeOrUpdateInstanceEdge(GraphVertex metadataVertex, EdgeLabelEnum edgeLabel, String componentUid, String instUniqueId) { + Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class); + properties.put(GraphPropertyEnum.UNIQUE_ID, componentUid); + + return titanDao.getEdgeByChildrenVertexProperties(metadataVertex, edgeLabel, properties).left().bind(v -> removeInstanceFromPropertyOnEdge(instUniqueId, v, metadataVertex)).right() + .map(err -> removeInstanceEdgeLogError(metadataVertex, edgeLabel, componentUid, err)); + } + + private Either<GraphVertex, TitanOperationStatus> addInstanceToPropertyOnEdge(String instUniqueId, Edge edge, GraphVertex metadataVertex) { + // edge exist need to add instance id to list on edge's property + List<String> property = (List<String>) titanDao.getProperty(edge, EdgePropertyEnum.INSTANCES); + if (property == null) { + property = new ArrayList<>(); + } + Optional<String> findFirst = property.stream().filter(a -> a.equals(instUniqueId)).findFirst(); + if (!findFirst.isPresent()) { + property.add(instUniqueId); + } + try { + String jsonArr = JsonParserUtils.toJson(property); + log.debug("Update INSTANCES edge property with value {} ", jsonArr ); + + edge.property(EdgePropertyEnum.INSTANCES.getProperty(), jsonArr); + } catch (IOException e) { + log.debug("Failed to convert INSTANCES edge property to json for container {}", metadataVertex.getUniqueId(), e ); + return Either.right(TitanOperationStatus.GENERAL_ERROR); + } + return Either.left(metadataVertex); + } + + private Either<GraphVertex, TitanOperationStatus> removeInstanceFromPropertyOnEdge(String instUniqueId, Edge edge, GraphVertex metadataVertex) { + // edge exist need to add instance id to list on edge's property + List<String> property = (List<String>) titanDao.getProperty(edge, EdgePropertyEnum.INSTANCES); + if (property == null) { + property = new ArrayList<>(); + } + Optional<String> findFirst = property.stream().filter(a -> a.equals(instUniqueId)).findFirst(); + if (findFirst.isPresent()) { + property.remove(instUniqueId); + } + if (property.isEmpty()) { + // For last instance need to remove edge + edge.remove(); + } else { + try { + String jsonArr = JsonParserUtils.toJson(property); + edge.property(EdgePropertyEnum.INSTANCES.getProperty(), jsonArr); + } catch (IOException e) { + log.debug("Failed to convert INSTANCES edge property to json for container {}", metadataVertex.getUniqueId(), e ); + return Either.right(TitanOperationStatus.GENERAL_ERROR); + } + } + return Either.left(metadataVertex); + } + + private Either<GraphVertex, TitanOperationStatus> createInstanceEdge(GraphVertex metadataVertex, EdgeLabelEnum edgeLabel, String componentUid, String instUniqueId, TitanOperationStatus retrieveEdgeStatus) { + if (retrieveEdgeStatus == TitanOperationStatus.NOT_FOUND) { + // create new edge + Either<GraphVertex, TitanOperationStatus> vertexById = titanDao.getVertexById(componentUid); + if (vertexById.isRight()) { + return vertexById; + } + GraphVertex originVertex = vertexById.left().value(); + Map<EdgePropertyEnum, Object> edgeProps = new EnumMap<>(EdgePropertyEnum.class); + List<String> instList = new ArrayList<>(); + instList.add(instUniqueId); + edgeProps.put(EdgePropertyEnum.INSTANCES, instList); + + log.debug("Create new edge {} between {} and {} and properties {} ", edgeLabel, metadataVertex.getUniqueId(), originVertex.getUniqueId(), edgeProps); + TitanOperationStatus edgeResult = titanDao.createEdge(metadataVertex, originVertex, edgeLabel, edgeProps); + return edgeResult == TitanOperationStatus.OK ? Either.left(metadataVertex) : Either.right(edgeResult); + } + // error + log.debug("Failed to fetch edge with label {} and to vertex with id {} error {} ", edgeLabel, componentUid, retrieveEdgeStatus); + return Either.right(retrieveEdgeStatus); + } + + private TitanOperationStatus removeInstanceEdgeLogError(GraphVertex metadataVertex, EdgeLabelEnum edgeLabel, String componentUid, TitanOperationStatus retrieveEdgeStatus) { + if (retrieveEdgeStatus == TitanOperationStatus.NOT_FOUND) { + log.debug("No edge {} to remove between container {} and origin {}", edgeLabel, metadataVertex.getUniqueId(), componentUid); + } else { + // error + log.debug("Failed to fetch edge with label {} and to vertex with id {} error {} ", edgeLabel, componentUid, retrieveEdgeStatus); + } + return retrieveEdgeStatus; + } + + public void removeAllAllotedEdges(String uniqueId) { + Either<GraphVertex, TitanOperationStatus> vertexById = titanDao.getVertexById(uniqueId); + if (vertexById.isLeft()) { + GraphVertex originVertex = vertexById.left().value(); + TitanVertex vertex = originVertex.getVertex(); + Iterator<Edge> edges = vertex.edges(Direction.OUT, EdgeLabelEnum.ALLOTTED_OF.name()); + while ( edges != null && edges.hasNext() ){ + Edge edge = edges.next(); + edge.remove(); + } + } + } } 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 d9318f5510..d9ced8c249 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 @@ -20,17 +20,7 @@ package org.openecomp.sdc.be.model.jsontitan.operations; -import java.util.ArrayList; -import java.util.Collection; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.Pattern; -import java.util.stream.Collectors; - +import fj.data.Either; import org.apache.tinkerpop.gremlin.structure.Direction; import org.apache.tinkerpop.gremlin.structure.Edge; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; @@ -38,12 +28,7 @@ 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.InterfaceDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition; -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.GraphPropertyEnum; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; @@ -58,921 +43,920 @@ import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; 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 org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.beans.factory.annotation.Qualifier; -import fj.data.Either; +import java.util.*; +import java.util.regex.Pattern; +import java.util.stream.Collectors; @org.springframework.stereotype.Component("node-type-operation") public class NodeTypeOperation extends ToscaElementOperation { public final static Pattern uuidNewVersion = Pattern.compile("^\\d{1,}.1"); public final static Pattern uuidNormativeNewVersion = Pattern.compile("^\\d{1,}.0"); + private static final Logger log = Logger.getLogger(NodeTypeOperation.class); + private DerivedNodeTypeResolver derivedResourceResolver; - private static Logger log = LoggerFactory.getLogger(NodeTypeOperation.class.getName()); - - private DerivedNodeTypeResolver derivedResourceResolver; - - public NodeTypeOperation(@Qualifier("derived-resource-resolver") DerivedNodeTypeResolver derivedNodeTypeResolver) { - this.derivedResourceResolver = derivedNodeTypeResolver; - } + + public NodeTypeOperation(@Qualifier("derived-resource-resolver") DerivedNodeTypeResolver derivedNodeTypeResolver) { + this.derivedResourceResolver = derivedNodeTypeResolver; + } - public Either<NodeType, StorageOperationStatus> createNodeType(NodeType nodeType) { + public Either<NodeType, StorageOperationStatus> createNodeType(NodeType nodeType) { - Either<NodeType, StorageOperationStatus> result = null; + Either<NodeType, StorageOperationStatus> result = null; - nodeType.generateUUID(); + nodeType.generateUUID(); //Set missing props such as names, default lifecycle state, dates etc... - nodeType = getResourceMetaDataFromResource(nodeType); + nodeType = getResourceMetaDataFromResource(nodeType); //Set unique ID - String resourceUniqueId = nodeType.getUniqueId(); - if (resourceUniqueId == null) { - resourceUniqueId = UniqueIdBuilder.buildResourceUniqueId(); - nodeType.setUniqueId(resourceUniqueId); - } - - // get derived from resources - List<GraphVertex> derivedResources = null; - Either<List<GraphVertex>, StorageOperationStatus> derivedResourcesResult = findDerivedResources(nodeType); - if (derivedResourcesResult.isRight()) { - result = Either.right(derivedResourcesResult.right().value()); - return result; - } else { - derivedResources = derivedResourcesResult.left().value(); - } + String resourceUniqueId = nodeType.getUniqueId(); + if (resourceUniqueId == null) { + resourceUniqueId = UniqueIdBuilder.buildResourceUniqueId(); + nodeType.setUniqueId(resourceUniqueId); + } + + // get derived from resources + List<GraphVertex> derivedResources = null; + Either<List<GraphVertex>, StorageOperationStatus> derivedResourcesResult = findDerivedResources(nodeType); + if (derivedResourcesResult.isRight()) { + result = Either.right(derivedResourcesResult.right().value()); + return result; + } else { + derivedResources = derivedResourcesResult.left().value(); + } //Create Vertext Object and fill according to given NodeType - GraphVertex nodeTypeVertex = new GraphVertex(VertexTypeEnum.NODE_TYPE); - fillToscaElementVertexData(nodeTypeVertex, nodeType, JsonParseFlagEnum.ParseAll); + GraphVertex nodeTypeVertex = new GraphVertex(VertexTypeEnum.NODE_TYPE); + fillToscaElementVertexData(nodeTypeVertex, nodeType, JsonParseFlagEnum.ParseAll); //Create Node Type in Graph - Either<GraphVertex, TitanOperationStatus> createdVertex = titanDao.createVertex(nodeTypeVertex); - if (createdVertex.isRight()) { - TitanOperationStatus status = createdVertex.right().value(); - log.error("Error returned after creating resource data node {}. status returned is ", nodeTypeVertex, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - nodeTypeVertex = createdVertex.left().value(); - - StorageOperationStatus assosiateCommon = assosiateCommonForToscaElement(nodeTypeVertex, nodeType, derivedResources); - if (assosiateCommon != StorageOperationStatus.OK) { - result = Either.right(assosiateCommon); - return result; - } - - StorageOperationStatus associateDerived = assosiateToDerived(nodeTypeVertex, derivedResources); - if (associateDerived != StorageOperationStatus.OK) { - result = Either.right(associateDerived); - return result; - } - StorageOperationStatus associateCategory = assosiateResourceMetadataToCategory(nodeTypeVertex, nodeType); - if (associateCategory != StorageOperationStatus.OK) { - result = Either.right(associateCategory); - return result; - } - - StorageOperationStatus associateAttributes = associateAttributesToResource(nodeTypeVertex, nodeType, derivedResources); - if (associateAttributes != StorageOperationStatus.OK) { - result = Either.right(associateAttributes); - return result; - } - - StorageOperationStatus associateRequirements = associateRequirementsToResource(nodeTypeVertex, nodeType, derivedResources); - if (associateRequirements != StorageOperationStatus.OK) { - result = Either.right(associateRequirements); - return result; - } - - StorageOperationStatus associateCapabilities = associateCapabilitiesToResource(nodeTypeVertex, nodeType, derivedResources); - if (associateCapabilities != StorageOperationStatus.OK) { - result = Either.right(associateCapabilities); - return result; - } - StorageOperationStatus associateCapabilitiesProps = associateCapabilitiesPropertiesToResource(nodeTypeVertex, nodeType, derivedResources); - if (associateCapabilitiesProps != StorageOperationStatus.OK) { - result = Either.right(associateCapabilitiesProps); - return result; - } - - StorageOperationStatus associateInterfaces = associateInterfacesToResource(nodeTypeVertex, nodeType, derivedResources); - if (associateInterfaces != StorageOperationStatus.OK) { - result = Either.right(associateInterfaces); - return result; - } - - StorageOperationStatus addAdditionalInformation = addAdditionalInformationToResource(nodeTypeVertex, nodeType, derivedResources); - if (addAdditionalInformation != StorageOperationStatus.OK) { - result = Either.right(addAdditionalInformation); - return result; - } - result = Either.left(nodeType); - return result; - - } - - private StorageOperationStatus associateInterfacesToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List<GraphVertex> derivedResources) { - // Note : currently only one derived supported!!!! - Either<Map<String, InterfaceDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.INTERFACE_ARTIFACTS); - if (dataFromDerived.isRight()) { - return dataFromDerived.right().value(); - } - Map<String, InterfaceDataDefinition> interfacArtsAll = dataFromDerived.left().value(); - - Map<String, InterfaceDataDefinition> interfacArts = nodeType.getInterfaceArtifacts(); - if (interfacArts != null) { - interfacArtsAll.putAll(interfacArts); - } - if (!interfacArtsAll.isEmpty()) { - Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.INTERFACE_ARTIFACTS, EdgeLabelEnum.INTERFACE_ARTIFACTS, interfacArtsAll); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - @Override - public Either<ToscaElement, StorageOperationStatus> getToscaElement(String uniqueId, ComponentParametersView componentParametersView) { - - Either<GraphVertex, StorageOperationStatus> componentByLabelAndId = getComponentByLabelAndId(uniqueId, ToscaElementTypeEnum.NodeType, JsonParseFlagEnum.ParseMetadata); - if (componentByLabelAndId.isRight()) { - return Either.right(componentByLabelAndId.right().value()); - } - GraphVertex componentV = componentByLabelAndId.left().value(); - - return getToscaElement(componentV, componentParametersView); - - } - - // ------------------------------------------------------------- - @Override - public Either<ToscaElement, StorageOperationStatus> getToscaElement(GraphVertex componentV, ComponentParametersView componentParametersView) { - NodeType toscaElement; - toscaElement = convertToComponent(componentV); - TitanOperationStatus status = null; - if (false == componentParametersView.isIgnoreUsers()) { - status = setCreatorFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - - status = setLastModifierFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - - if (false == componentParametersView.isIgnoreProperties()) { - status = setResourcePropertiesFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK && status != TitanOperationStatus.NOT_FOUND) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - - if (false == componentParametersView.isIgnoreAttributesFrom()) { - status = setResourceAttributesFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - - if (false == componentParametersView.isIgnoreDerivedFrom()) { - status = setResourceDerivedFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - - if (false == componentParametersView.isIgnoreCategories()) { - status = setResourceCategoryFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - if (false == componentParametersView.isIgnoreRequirements()) { - status = setResourceRequirementsFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - log.error("Failed to set requirement of resource {}. status is {}", componentV.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - if (false == componentParametersView.isIgnoreCapabilities()) { - status = setResourceCapabilitiesFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - - if (false == componentParametersView.isIgnoreArtifacts()) { - status = setArtifactsFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - if (false == componentParametersView.isIgnoreAdditionalInformation()) { - status = setAdditionalInformationFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - if (false == componentParametersView.isIgnoreInterfaces()) { - status = setInterfacesFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - if (false == componentParametersView.isIgnoreAllVersions()) { - status = setAllVersions(componentV, toscaElement); - if (status != TitanOperationStatus.OK && status != TitanOperationStatus.NOT_FOUND) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - - if (false == componentParametersView.isIgnoreCapabiltyProperties()) { - status = setComponentCapPropertiesFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - - } - } - return Either.left(toscaElement); - } - - private TitanOperationStatus setComponentCapPropertiesFromGraph(GraphVertex componentV, NodeType toscaElement) { - Either<Map<String, MapPropertiesDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CAPABILITIES_PROPERTIES); - if (result.isLeft()) { - toscaElement.setCapabiltiesProperties(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - return TitanOperationStatus.OK; - } - - private TitanOperationStatus setInterfacesFromGraph(GraphVertex componentV, NodeType toscaElement) { - Either<Map<String, InterfaceDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INTERFACE_ARTIFACTS); - if (result.isLeft()) { - toscaElement.setInterfaceArtifacts(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - return TitanOperationStatus.OK; - } - - protected <T extends ToscaElement> TitanOperationStatus setCapabilitiesFromGraph(GraphVertex componentV, T toscaElement) { - return setResourceCapabilitiesFromGraph(componentV, (NodeType) toscaElement); - } - - private TitanOperationStatus setResourceCapabilitiesFromGraph(GraphVertex componentV, NodeType toscaElement) { - Either<Map<String, ListCapabilityDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CAPABILITIES); - if (result.isLeft()) { - toscaElement.setCapabilties(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - return TitanOperationStatus.OK; - } - - private TitanOperationStatus setResourceDerivedFromGraph(GraphVertex componentV, NodeType toscaElement) { - List<String> derivedFromList = new ArrayList<String>(); - - TitanOperationStatus listFromGraphStatus = findResourcesPathRecursively(componentV, derivedFromList); - if (TitanOperationStatus.OK != listFromGraphStatus) { - return listFromGraphStatus; - } - - if (false == derivedFromList.isEmpty()) { - if (derivedFromList.size() > 1) { - List<String> lastDerivedFrom = new ArrayList<String>(); - lastDerivedFrom.add(derivedFromList.get(1)); - toscaElement.setDerivedFrom(lastDerivedFrom); - toscaElement.setDerivedList(derivedFromList); - } else { - toscaElement.setDerivedFrom(null); - toscaElement.setDerivedList(derivedFromList); - } - - } - return TitanOperationStatus.OK; - } - - protected TitanOperationStatus findResourcesPathRecursively(GraphVertex nodeTypeV, List<String> resourcesPathList) { - Either<GraphVertex, TitanOperationStatus> parentResourceRes = titanDao.getChildVertex(nodeTypeV, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.NoParse); - resourcesPathList.add((String) nodeTypeV.getMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME)); - while (parentResourceRes.isLeft()) { - - GraphVertex parent = parentResourceRes.left().value(); - resourcesPathList.add((String) parent.getMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME)); - parentResourceRes = titanDao.getChildVertex(parent, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.NoParse); - } - TitanOperationStatus operationStatus = parentResourceRes.right().value(); - - if (operationStatus != TitanOperationStatus.NOT_FOUND) { - return operationStatus; - } else { - return TitanOperationStatus.OK; - } - - } - - protected <T extends ToscaElement> TitanOperationStatus setRequirementsFromGraph(GraphVertex componentV, T toscaElement) { - return setResourceRequirementsFromGraph(componentV, (NodeType) toscaElement); - } - - private TitanOperationStatus setResourceRequirementsFromGraph(GraphVertex componentV, NodeType toscaElement) { - Either<Map<String, ListRequirementDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.REQUIREMENTS); - if (result.isLeft()) { - toscaElement.setRequirements(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - return TitanOperationStatus.OK; - } - - private TitanOperationStatus setResourceAttributesFromGraph(GraphVertex componentV, NodeType toscaElement) { - Either<Map<String, PropertyDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.ATTRIBUTES); - if (result.isLeft()) { - toscaElement.setAttributes(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - return TitanOperationStatus.OK; - } - - private TitanOperationStatus setResourcePropertiesFromGraph(GraphVertex componentV, NodeType toscaElement) { - Either<Map<String, PropertyDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.PROPERTIES); - if (result.isLeft()) { - toscaElement.setProperties(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - return TitanOperationStatus.OK; - } - - private StorageOperationStatus assosiateToDerived(GraphVertex nodeTypeVertex, List<GraphVertex> derivedResources) { - for (GraphVertex derivedV : derivedResources) { - TitanOperationStatus createEdge = titanDao.createEdge(nodeTypeVertex, derivedV, EdgeLabelEnum.DERIVED_FROM, null); - if (createEdge != TitanOperationStatus.OK) { - log.trace("Failed to associate resource {} to derived with id {}", nodeTypeVertex.getUniqueId(), derivedV.getUniqueId()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge); - } - } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus addAdditionalInformationToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List<GraphVertex> derivedResources) { - // Note : currently only one derived supported!!!! - Either<Map<String, AdditionalInfoParameterDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.ADDITIONAL_INFORMATION); - if (dataFromDerived.isRight()) { - return dataFromDerived.right().value(); - } - Map<String, AdditionalInfoParameterDataDefinition> addInformationAll = dataFromDerived.left().value(); - - Map<String, AdditionalInfoParameterDataDefinition> addInformation = nodeType.getAdditionalInformation(); - if (addInformation != null) { - ToscaDataDefinition.mergeDataMaps(addInformationAll, addInformation); - } - if (!addInformationAll.isEmpty()) { - Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.ADDITIONAL_INFORMATION, EdgeLabelEnum.ADDITIONAL_INFORMATION, addInformationAll); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus associateCapabilitiesToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List<GraphVertex> derivedResources) { - // Note : currently only one derived supported!!!! - Either<Map<String, ListCapabilityDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.CAPABILITIES); - if (dataFromDerived.isRight()) { - return dataFromDerived.right().value(); - } - Map<String, ListCapabilityDataDefinition> capabiltiesAll = dataFromDerived.left().value(); - - Map<String, ListCapabilityDataDefinition> capabilties = nodeType.getCapabilties(); - if (capabilties != null) { - if (capabiltiesAll == null) { - capabiltiesAll = new HashMap<>(); - } - capabilties.values().forEach(l -> { - l.getListToscaDataDefinition().stream().filter(p -> p.getUniqueId() == null).forEach(p -> { - String uid = UniqueIdBuilder.buildCapabilityUid(nodeTypeVertex.getUniqueId(), p.getName()); - p.setUniqueId(uid); - }); - }); - - ToscaDataDefinition.mergeDataMaps(capabiltiesAll, capabilties); - capabiltiesAll.values().forEach(l -> { - l.getListToscaDataDefinition().forEach(c -> { - List<String> capabilitySources = c.getCapabilitySources(); - if (capabilitySources == null) { - capabilitySources = new ArrayList<>(); - } - capabilitySources.add((String) nodeType.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME)); - c.setCapabilitySources(capabilitySources); - }); - }); - } - capabiltiesAll.values().forEach(l -> { - l.getListToscaDataDefinition().forEach(c -> { - List<String> capabilitySources = c.getCapabilitySources(); - if (capabilitySources == null) { - capabilitySources = new ArrayList<>(); - } - capabilitySources.add((String) nodeType.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME)); - c.setCapabilitySources(capabilitySources); - }); - }); - if (!capabiltiesAll.isEmpty()) { - Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.CAPABILTIES, EdgeLabelEnum.CAPABILITIES, capabiltiesAll); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus associateRequirementsToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List<GraphVertex> derivedResources) { - // Note : currently only one derived supported!!!! - Either<Map<String, ListRequirementDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.REQUIREMENTS); - if (dataFromDerived.isRight()) { - return dataFromDerived.right().value(); - } - Map<String, ListRequirementDataDefinition> requirementsAll = dataFromDerived.left().value(); - - Map<String, ListRequirementDataDefinition> requirements = nodeType.getRequirements(); - if (requirements != null) { - if (requirementsAll == null) { - requirementsAll = new HashMap<>(); - } - requirements.values().forEach(l -> { - l.getListToscaDataDefinition().stream().filter(p -> p.getUniqueId() == null).forEach(p -> { - String uid = UniqueIdBuilder.buildRequirementUid(nodeTypeVertex.getUniqueId(), p.getName()); - p.setUniqueId(uid); - }); - }); - - ToscaDataDefinition.mergeDataMaps(requirementsAll, requirements); - - } - if (!requirementsAll.isEmpty()) { - Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.REQUIREMENTS, EdgeLabelEnum.REQUIREMENTS, requirementsAll); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus associateAttributesToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List<GraphVertex> derivedResources) { - // Note : currently only one derived supported!!!! - Either<Map<String, PropertyDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.ATTRIBUTES); - if (dataFromDerived.isRight()) { - return dataFromDerived.right().value(); - } - Map<String, PropertyDataDefinition> attributesAll = dataFromDerived.left().value(); - - Map<String, PropertyDataDefinition> attributes = nodeType.getAttributes(); - if (attributes != null) { - attributes.values().stream().filter(p -> p.getUniqueId() == null).forEach(p -> { - String uid = UniqueIdBuilder.buildAttributeUid(nodeTypeVertex.getUniqueId(), p.getName()); - p.setUniqueId(uid); - }); - ToscaDataDefinition.mergeDataMaps(attributesAll, attributes); - } - if (!attributesAll.isEmpty()) { - Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.ATTRIBUTES, EdgeLabelEnum.ATTRIBUTES, attributesAll); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - // TODO get from derived - private StorageOperationStatus associateCapabilitiesPropertiesToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List<GraphVertex> derivedResources) { - // // Note : currently only one derived supported!!!! - Either<Map<String, MapPropertiesDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.CAPABILITIES_PROPERTIES); - if (dataFromDerived.isRight()) { - return dataFromDerived.right().value(); - } - Map<String, MapPropertiesDataDefinition> propertiesAll = dataFromDerived.left().value(); - Map<String, MapPropertiesDataDefinition> capabiltiesProps = nodeType.getCapabiltiesProperties(); - if (capabiltiesProps != null) { - capabiltiesProps.values().forEach(l -> { - if (l.getMapToscaDataDefinition() != null && l.getMapToscaDataDefinition().values() != null) { - Collection<PropertyDataDefinition> mapToscaDataDefinition = l.getMapToscaDataDefinition().values(); - mapToscaDataDefinition.stream().filter(p -> p != null && p.getUniqueId() == null).forEach(p -> { - String uid = UniqueIdBuilder.buildRequirementUid(nodeTypeVertex.getUniqueId(), p.getName()); - p.setUniqueId(uid); - }); - } - }); - ToscaDataDefinition.mergeDataMaps(propertiesAll, capabiltiesProps); - } - if (!propertiesAll.isEmpty()) { - Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.CAPABILITIES_PROPERTIES, EdgeLabelEnum.CAPABILITIES_PROPERTIES, propertiesAll); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - public Either<List<GraphVertex>, StorageOperationStatus> findDerivedResources(NodeType nodeType) { - - List<GraphVertex> derivedResources = new ArrayList<GraphVertex>(); - List<String> derivedFromResources = nodeType.getDerivedFrom(); - if (derivedFromResources != null && false == derivedFromResources.isEmpty()) { - - for (String parentResource : derivedFromResources) { - Either<List<GraphVertex>, TitanOperationStatus> getParentResources = derivedResourceResolver.findDerivedResources(parentResource); - List<GraphVertex> resources = null; - if (getParentResources.isRight()) { - log.error("Cannot find parent resource by tosca resource name {} in the graph.", parentResource); - return Either.right(StorageOperationStatus.PARENT_RESOURCE_NOT_FOUND); - - } else { - resources = getParentResources.left().value(); - if (resources == null || resources.size() == 0) { - log.error("Cannot find parent resource by tosca name {} in the graph. resources size is empty", parentResource); - return Either.right(StorageOperationStatus.PARENT_RESOURCE_NOT_FOUND); - } else { - if (resources.size() > 1) { - return handleMultipleParent(parentResource, derivedResources, resources); - } else { - GraphVertex parentResourceData = resources.get(0); - derivedResources.add(parentResourceData); - } - } - - } - - } - } - return Either.left(derivedResources); - } - - Either<List<GraphVertex>, StorageOperationStatus> handleMultipleParent(String parentResource, List<GraphVertex> derivedResource, List<GraphVertex> fetchedDerivedResources) { - - Either<List<GraphVertex>, StorageOperationStatus> result = Either.left(derivedResource); - try { - fetchedDerivedResources.sort((d1, d2) -> { - return new Double(Double.parseDouble((String) d1.getMetadataProperty(GraphPropertyEnum.VERSION))).compareTo(Double.parseDouble((String) d2.getMetadataProperty(GraphPropertyEnum.VERSION))); - }); - - int actualHighestIndex = fetchedDerivedResources.size() - 1; - derivedResource.add(fetchedDerivedResources.get(actualHighestIndex)); - fetchedDerivedResources.remove(actualHighestIndex); - - StorageOperationStatus status = fixMultipleParent(fetchedDerivedResources); - if (status != StorageOperationStatus.OK) { - result = Either.right(status); - } - } catch (Exception e) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during handle multiple parent {}. Exception is {}", parentResource, e.getMessage()); - result = Either.right(StorageOperationStatus.GENERAL_ERROR); - } - return result; - } - - private StorageOperationStatus fixMultipleParent(List<GraphVertex> fetchedDerivedResources) { - StorageOperationStatus result = StorageOperationStatus.OK; - for (GraphVertex fetchedDerivedResource : fetchedDerivedResources) { - fetchedDerivedResource.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION, false); - Either<GraphVertex, TitanOperationStatus> updateVertexRes = titanDao.updateVertex(fetchedDerivedResource); - if (updateVertexRes.isRight()) { - TitanOperationStatus titatStatus = updateVertexRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to set highest version of node type {} to false. Status is {}", fetchedDerivedResource.getMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME), titatStatus); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(titatStatus); - break; - } - } - return result; - } - - private GraphVertex fillMetadata(GraphVertex nodeTypeVertex, NodeType nodeType) { - nodeTypeVertex.setLabel(VertexTypeEnum.NODE_TYPE); - - fillCommonMetadata(nodeTypeVertex, nodeType); - - return nodeTypeVertex; - } - - @Override - public Either<ToscaElement, StorageOperationStatus> deleteToscaElement(GraphVertex toscaElementVertex) { - Either<ToscaElement, StorageOperationStatus> nodeType = getToscaElement(toscaElementVertex, new ComponentParametersView()); - if (nodeType.isRight()) { - log.debug("Failed to fetch tosca element {} error {}", toscaElementVertex.getUniqueId(), nodeType.right().value()); - return nodeType; - } - TitanOperationStatus status = disassociateAndDeleteCommonElements(toscaElementVertex); - if (status != TitanOperationStatus.OK) { - Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CAPABILITIES); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate capabilties for {} error {}", toscaElementVertex.getUniqueId(), status); - Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CAPABILITIES_PROPERTIES); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate capabilties properties for {} error {}", toscaElementVertex.getUniqueId(), status); - Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.REQUIREMENTS); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate requirements for {} error {}", toscaElementVertex.getUniqueId(), status); - Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ATTRIBUTES); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate attributes for {} error {}", toscaElementVertex.getUniqueId(), status); - Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INTERFACE_ARTIFACTS); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate interface artifacts for {} error {}", toscaElementVertex.getUniqueId(), status); - Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - toscaElementVertex.getVertex().remove(); - log.trace("Tosca element vertex for {} was removed", toscaElementVertex.getUniqueId()); - - return nodeType; - } - - @SuppressWarnings("unchecked") - @Override - public Either<NodeType, StorageOperationStatus> createToscaElement(ToscaElement toscaElement) { - return createNodeType((NodeType) toscaElement); - } - - @Override - protected <T extends ToscaElement> TitanOperationStatus setCategoriesFromGraph(GraphVertex vertexComponent, T toscaElement) { - return setResourceCategoryFromGraph(vertexComponent, toscaElement); - } - - @Override - protected <T extends ToscaElement> StorageOperationStatus validateCategories(T toscaElementToUpdate, GraphVertex elementV) { - return validateResourceCategory(toscaElementToUpdate, elementV); - } - - @Override - protected <T extends ToscaElement> StorageOperationStatus updateDerived(T toscaElementToUpdate, GraphVertex nodeTypeV) { - - NodeType nodeType = (NodeType) toscaElementToUpdate; - List<GraphVertex> derivedResources = new ArrayList<>(); - - List<String> derivedFromResources = nodeType.getDerivedFrom(); - - // now supported only single derived from - if (derivedFromResources != null && !derivedFromResources.isEmpty() && derivedFromResources.get(0) != null) { - String firstDerived = derivedFromResources.get(0); - boolean derivedFromGenericType = null != nodeType.getDerivedFromGenericType(); - Either<GraphVertex, TitanOperationStatus> childVertex = titanDao.getChildVertex(nodeTypeV, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.NoParse); - if (childVertex.isRight()) { - TitanOperationStatus getchieldError = childVertex.right().value(); - log.debug("Failed to fetch derived resource for element {} error {}", nodeTypeV.getUniqueId(), getchieldError); - return DaoStatusConverter.convertTitanStatusToStorageStatus(getchieldError); - } - GraphVertex firstDerivedInChain = childVertex.left().value(); - - String firstCurrentDerived = (String) firstDerivedInChain.getMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME); - if (!firstDerived.equals(firstCurrentDerived) || derivedFromGenericType) { - - Map<GraphPropertyEnum, Object> propertiesToMatch = new HashMap<GraphPropertyEnum, Object>(); - propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - - propertiesToMatch.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, firstDerived); - propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - - Either<List<GraphVertex>, TitanOperationStatus> getParentResources = titanDao.getByCriteria(VertexTypeEnum.NODE_TYPE, propertiesToMatch, JsonParseFlagEnum.NoParse); - - if (getParentResources.isRight()) { - TitanOperationStatus error = getParentResources.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch derived by criteria {}. error {} ", propertiesToMatch, error); - return DaoStatusConverter.convertTitanStatusToStorageStatus(error); - } - // must be only one - GraphVertex newDerivedV = getParentResources.left().value().get(0); - return updateDerived(toscaElementToUpdate, nodeTypeV, firstDerivedInChain, newDerivedV, false); - } - } - return StorageOperationStatus.OK; - } - - /** - * - * @param toscaElementToUpdate - * @param nodeTypeV - * @param preDerivedV - * @param newDerivedV - * @param mergeValues - * @return - */ - protected <T extends ToscaElement> StorageOperationStatus updateDerived(T toscaElementToUpdate, GraphVertex nodeTypeV, GraphVertex preDerivedV, GraphVertex newDerivedV, boolean mergeValues) { - Set<String> preDerivedChainIdList = new HashSet(); - preDerivedChainIdList.add(preDerivedV.getUniqueId()); - Either<GraphVertex, TitanOperationStatus> childVertex = titanDao.getChildVertex(preDerivedV, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.NoParse); - while (childVertex.isLeft()) { - GraphVertex currentChield = childVertex.left().value(); - preDerivedChainIdList.add(currentChield.getUniqueId()); - childVertex = titanDao.getChildVertex(currentChield, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.NoParse); - } - - List<GraphVertex> derivedResources = new ArrayList<>(); - derivedResources.add(newDerivedV); - StorageOperationStatus updateStatus = updateDataFromNewDerived(derivedResources, nodeTypeV, (NodeType) toscaElementToUpdate, mergeValues, preDerivedChainIdList); - if (updateStatus != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update data for {} from new derived {} ", nodeTypeV.getUniqueId(), newDerivedV.getUniqueId(), updateStatus); - return updateStatus; - } - - Either<Edge, TitanOperationStatus> deleteEdge = titanDao.deleteEdge(nodeTypeV, preDerivedV, EdgeLabelEnum.DERIVED_FROM); - if (deleteEdge.isRight()) { - TitanOperationStatus deleteError = deleteEdge.right().value(); - log.debug("Failed to disassociate element {} from derived {} , error {}", nodeTypeV.getUniqueId(), preDerivedV.getUniqueId(), deleteError); - return DaoStatusConverter.convertTitanStatusToStorageStatus(deleteError); - } - - titanDao.createEdge(nodeTypeV, newDerivedV, EdgeLabelEnum.DERIVED_FROM, new HashMap<>()); - - return StorageOperationStatus.OK; - } - - private StorageOperationStatus associateDerivedDataByType(EdgeLabelEnum edgeLabel, GraphVertex nodeTypeV, NodeType nodeToUpdate, List<GraphVertex> newDerived) { - - switch (edgeLabel) { - case CAPABILITIES: - return associateCapabilitiesToResource(nodeTypeV, nodeToUpdate, newDerived); - case REQUIREMENTS: - return associateRequirementsToResource(nodeTypeV, nodeToUpdate, newDerived); - case PROPERTIES: - return associatePropertiesToResource(nodeTypeV, nodeToUpdate, newDerived); - case ATTRIBUTES: - return associateAttributesToResource(nodeTypeV, nodeToUpdate, newDerived); - case ADDITIONAL_INFORMATION: - return addAdditionalInformationToResource(nodeTypeV, nodeToUpdate, newDerived); - case CAPABILITIES_PROPERTIES: - return associateCapabilitiesPropertiesToResource(nodeTypeV, nodeToUpdate, newDerived); - default: - return StorageOperationStatus.OK; - } - - } - - private StorageOperationStatus updateDataFromNewDerived(List<GraphVertex> newDerived, GraphVertex nodeTypeV, NodeType nodeToUpdate, boolean mergeValues, Set<String> preDerivedChainIdList) { - EnumSet<EdgeLabelEnum> edgeLabels = EnumSet.of(EdgeLabelEnum.CAPABILITIES, EdgeLabelEnum.REQUIREMENTS, EdgeLabelEnum.PROPERTIES, EdgeLabelEnum.ATTRIBUTES, EdgeLabelEnum.CAPABILITIES_PROPERTIES, EdgeLabelEnum.ADDITIONAL_INFORMATION); - StorageOperationStatus status = null; - for (EdgeLabelEnum edge : edgeLabels) { - status = updateDataByType(newDerived, nodeTypeV, edge, nodeToUpdate, mergeValues, preDerivedChainIdList); - if (status != StorageOperationStatus.OK) { - break; - } - } - return status; - - } - - private <T extends ToscaDataDefinition> StorageOperationStatus updateDataByType(List<GraphVertex> newDerivedList, GraphVertex nodeTypeV, EdgeLabelEnum label, NodeType nodeElement, boolean mergeValues, Set<String> preDerivedChainIdList) { - log.debug("Update data from derived for element {} type {}", nodeTypeV.getUniqueId(), label); - Either<GraphVertex, TitanOperationStatus> dataFromGraph = getDataVertex(nodeTypeV, label); - if (dataFromGraph.isRight()) { - if (TitanOperationStatus.NOT_FOUND == dataFromGraph.right().value()) - return associateDerivedDataByType(label, nodeTypeV, nodeElement, newDerivedList); - return DaoStatusConverter.convertTitanStatusToStorageStatus(dataFromGraph.right().value()); - } - GraphVertex dataV = dataFromGraph.left().value(); - - Map<String, T> mapFromGraph = (Map<String, T>) dataV.getJson(); - Map<String, T> valuesFrmPrev = null; - if (isSimpleHierarchy(label)) { - if (mergeValues) { - valuesFrmPrev = mapFromGraph.entrySet().stream().filter(e -> e.getValue().getOwnerId() != null).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - } - mapFromGraph.entrySet().removeIf(e -> preDerivedChainIdList.contains(e.getValue().getOwnerId())); - } else { - final Map<String, T> valuesFrmPrevFinal = new HashMap<>(); - mapFromGraph.entrySet().stream().forEach(e -> { - T value = e.getValue(); - value = ToscaDataDefinition.removeAndCollectByOwnerId(value, preDerivedChainIdList); - valuesFrmPrevFinal.put(e.getKey(), value); - }); - valuesFrmPrev = valuesFrmPrevFinal; - mapFromGraph.entrySet().removeIf(e->e.getValue().isEmpty()); - } - - Either<Map<String, T>, StorageOperationStatus> dataFromDerived = getDataFromDerived(newDerivedList, label); - if (dataFromDerived.isRight()) { - return dataFromDerived.right().value(); - } - Map<String, T> dataFromDerivedAll = dataFromDerived.left().value(); - - Either<Map<String, T>, String> merged = ToscaDataDefinition.mergeDataMaps(dataFromDerivedAll, mapFromGraph); - if (merged.isRight()) { - log.debug("property {} cannot be overriden", merged.right().value()); - return StorageOperationStatus.INVALID_PROPERTY; - } - if (mergeValues && valuesFrmPrev != null) { - valuesFrmPrev.entrySet().forEach(e -> { - T newData = merged.left().value().get(e.getKey()); - if (newData != null) { - if (isSimpleHierarchy(label)) { - e.getValue().mergeFunction(newData, true); - }else{ - e.getValue().updateIfExist(newData, true); - } - } - }); - } - dataV.setJson(dataFromDerivedAll); - Either<GraphVertex, TitanOperationStatus> updateDataV = updateOrCopyOnUpdate(dataV, nodeTypeV, label); - if (updateDataV.isRight()) { - return DaoStatusConverter.convertTitanStatusToStorageStatus(updateDataV.right().value()); - } - return StorageOperationStatus.OK; - } - - private boolean isSimpleHierarchy(EdgeLabelEnum label) { - switch (label) { - case PROPERTIES: - case ATTRIBUTES: - case ADDITIONAL_INFORMATION: - case ARTIFACTS: - case GROUPS: - case INPUTS: - return true; - default: - return false; - } - } - - @Override - public <T extends ToscaElement> void fillToscaElementVertexData(GraphVertex elementV, T toscaElementToUpdate, JsonParseFlagEnum flag) { - fillMetadata(elementV, (NodeType) toscaElementToUpdate); - } - - public Either<ToscaElement, StorageOperationStatus> shouldUpdateDerivedVersion(ToscaElement toscaElementToUpdate, GraphVertex nodeTypeV) { - NodeType nodeType = (NodeType) toscaElementToUpdate; - - Either<GraphVertex, TitanOperationStatus> childVertex = titanDao.getChildVertex(nodeTypeV, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.NoParse); - if (childVertex.isRight()) { - TitanOperationStatus getchildError = childVertex.right().value(); - if (getchildError == TitanOperationStatus.NOT_FOUND) { - log.debug("derived resource for element {} not found", nodeTypeV.getUniqueId()); - return Either.right(StorageOperationStatus.OK); - } - - log.debug("Failed to fetch derived resource for element {} error {}", nodeTypeV.getUniqueId(), getchildError); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getchildError)); - } - GraphVertex firstDerivedInChain = childVertex.left().value(); - - String currentVersion = (String) firstDerivedInChain.getMetadataProperty(GraphPropertyEnum.VERSION); - - Map<GraphPropertyEnum, Object> props = new HashMap<>(); - props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, nodeType.getDerivedFrom().get(0)); - props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - - Map<GraphPropertyEnum, Object> propsHasNot = new HashMap<>(); - propsHasNot.put(GraphPropertyEnum.IS_DELETED, true); - Either<List<GraphVertex>, TitanOperationStatus> byCriteria = titanDao.getByCriteria(VertexTypeEnum.NODE_TYPE, props, propsHasNot, JsonParseFlagEnum.NoParse); - if (byCriteria.isRight()) { - log.debug("Failed to fetch derived by props {} error {}", props, byCriteria.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(byCriteria.right().value())); - } - List<GraphVertex> lastDerived = byCriteria.left().value(); - // now supported only one derived!!! Change in future!(Evg) - GraphVertex derivedFromHighest = lastDerived.get(0); - String highestVersion = (String) derivedFromHighest.getMetadataProperty(GraphPropertyEnum.VERSION); - if (!highestVersion.equals(currentVersion)) { - - // need to update to latest version of derived from - StorageOperationStatus updateDerived = updateDerived(toscaElementToUpdate, nodeTypeV, firstDerivedInChain, derivedFromHighest, true); - - if (updateDerived != StorageOperationStatus.OK) { - log.debug("Failed to update {} to highest derived {} from error {}", nodeTypeV.getUniqueId(), derivedFromHighest.getUniqueId(), updateDerived); - return Either.right(updateDerived); - } - return getToscaElement(nodeTypeV.getUniqueId(), new ComponentParametersView()); - } - // no version changes - return Either.right(StorageOperationStatus.OK); - } + Either<GraphVertex, TitanOperationStatus> createdVertex = titanDao.createVertex(nodeTypeVertex); + if (createdVertex.isRight()) { + TitanOperationStatus status = createdVertex.right().value(); + log.error("Error returned after creating resource data node {}. status returned is ", nodeTypeVertex, status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + return result; + } + nodeTypeVertex = createdVertex.left().value(); + + StorageOperationStatus assosiateCommon = assosiateCommonForToscaElement(nodeTypeVertex, nodeType, derivedResources); + if (assosiateCommon != StorageOperationStatus.OK) { + result = Either.right(assosiateCommon); + return result; + } + + StorageOperationStatus associateDerived = assosiateToDerived(nodeTypeVertex, derivedResources); + if (associateDerived != StorageOperationStatus.OK) { + result = Either.right(associateDerived); + return result; + } + StorageOperationStatus associateCategory = assosiateResourceMetadataToCategory(nodeTypeVertex, nodeType); + if (associateCategory != StorageOperationStatus.OK) { + result = Either.right(associateCategory); + return result; + } + + StorageOperationStatus associateAttributes = associateAttributesToResource(nodeTypeVertex, nodeType, derivedResources); + if (associateAttributes != StorageOperationStatus.OK) { + result = Either.right(associateAttributes); + return result; + } + + StorageOperationStatus associateRequirements = associateRequirementsToResource(nodeTypeVertex, nodeType, derivedResources); + if (associateRequirements != StorageOperationStatus.OK) { + result = Either.right(associateRequirements); + return result; + } + + StorageOperationStatus associateCapabilities = associateCapabilitiesToResource(nodeTypeVertex, nodeType, derivedResources); + if (associateCapabilities != StorageOperationStatus.OK) { + result = Either.right(associateCapabilities); + return result; + } + StorageOperationStatus associateCapabilitiesProps = associateCapabilitiesPropertiesToResource(nodeTypeVertex, nodeType, derivedResources); + if (associateCapabilitiesProps != StorageOperationStatus.OK) { + result = Either.right(associateCapabilitiesProps); + return result; + } + + StorageOperationStatus associateInterfaces = associateInterfacesToResource(nodeTypeVertex, nodeType, derivedResources); + if (associateInterfaces != StorageOperationStatus.OK) { + result = Either.right(associateInterfaces); + return result; + } + + StorageOperationStatus addAdditionalInformation = addAdditionalInformationToResource(nodeTypeVertex, nodeType, derivedResources); + if (addAdditionalInformation != StorageOperationStatus.OK) { + result = Either.right(addAdditionalInformation); + return result; + } + result = Either.left(nodeType); + return result; + + } + + private StorageOperationStatus associateInterfacesToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List<GraphVertex> derivedResources) { + // Note : currently only one derived supported!!!! + Either<Map<String, InterfaceDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.INTERFACE_ARTIFACTS); + if (dataFromDerived.isRight()) { + return dataFromDerived.right().value(); + } + Map<String, InterfaceDataDefinition> interfacArtsAll = dataFromDerived.left().value(); + + Map<String, InterfaceDataDefinition> interfacArts = nodeType.getInterfaceArtifacts(); + if (interfacArts != null) { + interfacArtsAll.putAll(interfacArts); + } + if (!interfacArtsAll.isEmpty()) { + Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INTERFACE_ARTIFACTS, EdgeLabelEnum.INTERFACE_ARTIFACTS, interfacArtsAll); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + @Override + public Either<ToscaElement, StorageOperationStatus> getToscaElement(String uniqueId, ComponentParametersView componentParametersView) { + + Either<GraphVertex, StorageOperationStatus> componentByLabelAndId = getComponentByLabelAndId(uniqueId, ToscaElementTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata); + if (componentByLabelAndId.isRight()) { + return Either.right(componentByLabelAndId.right().value()); + } + GraphVertex componentV = componentByLabelAndId.left().value(); + + return getToscaElement(componentV, componentParametersView); + + } + + // ------------------------------------------------------------- + @Override + public Either<ToscaElement, StorageOperationStatus> getToscaElement(GraphVertex componentV, ComponentParametersView componentParametersView) { + NodeType toscaElement; + toscaElement = convertToComponent(componentV); + TitanOperationStatus status = null; + if (!componentParametersView.isIgnoreUsers()) { + status = setCreatorFromGraph(componentV, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + + status = setLastModifierFromGraph(componentV, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + } + + if (!componentParametersView.isIgnoreProperties()) { + status = setResourcePropertiesFromGraph(componentV, toscaElement); + if (status != TitanOperationStatus.OK && status != TitanOperationStatus.NOT_FOUND) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + } + + if (!componentParametersView.isIgnoreAttributesFrom()) { + status = setResourceAttributesFromGraph(componentV, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + } + + if (!componentParametersView.isIgnoreDerivedFrom()) { + status = setResourceDerivedFromGraph(componentV, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + } + + if (!componentParametersView.isIgnoreCategories()) { + status = setResourceCategoryFromGraph(componentV, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + } + if (!componentParametersView.isIgnoreRequirements()) { + status = setResourceRequirementsFromGraph(componentV, toscaElement); + if (status != TitanOperationStatus.OK) { + log.error("Failed to set requirement of resource {}. status is {}", componentV.getUniqueId(), status); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + } + if (!componentParametersView.isIgnoreCapabilities()) { + status = setResourceCapabilitiesFromGraph(componentV, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + } + + if (!componentParametersView.isIgnoreArtifacts()) { + status = setArtifactsFromGraph(componentV, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + } + if (!componentParametersView.isIgnoreAdditionalInformation()) { + status = setAdditionalInformationFromGraph(componentV, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + } + if (!componentParametersView.isIgnoreInterfaces()) { + status = setInterfacesFromGraph(componentV, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + } + if (!componentParametersView.isIgnoreAllVersions()) { + status = setAllVersions(componentV, toscaElement); + if (status != TitanOperationStatus.OK && status != TitanOperationStatus.NOT_FOUND) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + } + + if (!componentParametersView.isIgnoreCapabiltyProperties()) { + status = setComponentCapPropertiesFromGraph(componentV, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + + } + } + return Either.left(toscaElement); + } + + private TitanOperationStatus setComponentCapPropertiesFromGraph(GraphVertex componentV, NodeType toscaElement) { + Either<Map<String, MapPropertiesDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CAPABILITIES_PROPERTIES); + if (result.isLeft()) { + toscaElement.setCapabiltiesProperties(result.left().value()); + } else { + if (result.right().value() != TitanOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return TitanOperationStatus.OK; + } + + private TitanOperationStatus setInterfacesFromGraph(GraphVertex componentV, NodeType toscaElement) { + Either<Map<String, InterfaceDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INTERFACE_ARTIFACTS); + if (result.isLeft()) { + toscaElement.setInterfaceArtifacts(result.left().value()); + } else { + if (result.right().value() != TitanOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return TitanOperationStatus.OK; + } + + protected <T extends ToscaElement> TitanOperationStatus setCapabilitiesFromGraph(GraphVertex componentV, T toscaElement) { + return setResourceCapabilitiesFromGraph(componentV, (NodeType) toscaElement); + } + + private TitanOperationStatus setResourceCapabilitiesFromGraph(GraphVertex componentV, NodeType toscaElement) { + Either<Map<String, ListCapabilityDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CAPABILITIES); + if (result.isLeft()) { + toscaElement.setCapabilties(result.left().value()); + } else { + if (result.right().value() != TitanOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return TitanOperationStatus.OK; + } + + private TitanOperationStatus setResourceDerivedFromGraph(GraphVertex componentV, NodeType toscaElement) { + List<String> derivedFromList = new ArrayList<>(); + + TitanOperationStatus listFromGraphStatus = findResourcesPathRecursively(componentV, derivedFromList); + if (TitanOperationStatus.OK != listFromGraphStatus) { + return listFromGraphStatus; + } + + if (!derivedFromList.isEmpty()) { + if (derivedFromList.size() > 1) { + List<String> lastDerivedFrom = new ArrayList<>(); + lastDerivedFrom.add(derivedFromList.get(1)); + toscaElement.setDerivedFrom(lastDerivedFrom); + toscaElement.setDerivedList(derivedFromList); + } else { + toscaElement.setDerivedFrom(null); + toscaElement.setDerivedList(derivedFromList); + } + + } + return TitanOperationStatus.OK; + } + + protected TitanOperationStatus findResourcesPathRecursively(GraphVertex nodeTypeV, List<String> resourcesPathList) { + Either<GraphVertex, TitanOperationStatus> parentResourceRes = titanDao.getChildVertex(nodeTypeV, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.NoParse); + resourcesPathList.add((String) nodeTypeV.getMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME)); + while (parentResourceRes.isLeft()) { + + GraphVertex parent = parentResourceRes.left().value(); + resourcesPathList.add((String) parent.getMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME)); + parentResourceRes = titanDao.getChildVertex(parent, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.NoParse); + } + TitanOperationStatus operationStatus = parentResourceRes.right().value(); + + if (operationStatus != TitanOperationStatus.NOT_FOUND) { + return operationStatus; + } else { + return TitanOperationStatus.OK; + } + + } + + protected <T extends ToscaElement> TitanOperationStatus setRequirementsFromGraph(GraphVertex componentV, T toscaElement) { + return setResourceRequirementsFromGraph(componentV, (NodeType) toscaElement); + } + + private TitanOperationStatus setResourceRequirementsFromGraph(GraphVertex componentV, NodeType toscaElement) { + Either<Map<String, ListRequirementDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.REQUIREMENTS); + if (result.isLeft()) { + toscaElement.setRequirements(result.left().value()); + } else { + if (result.right().value() != TitanOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return TitanOperationStatus.OK; + } + + private TitanOperationStatus setResourceAttributesFromGraph(GraphVertex componentV, NodeType toscaElement) { + Either<Map<String, PropertyDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.ATTRIBUTES); + if (result.isLeft()) { + toscaElement.setAttributes(result.left().value()); + } else { + if (result.right().value() != TitanOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return TitanOperationStatus.OK; + } + + private TitanOperationStatus setResourcePropertiesFromGraph(GraphVertex componentV, NodeType toscaElement) { + Either<Map<String, PropertyDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.PROPERTIES); + if (result.isLeft()) { + toscaElement.setProperties(result.left().value()); + } else { + if (result.right().value() != TitanOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return TitanOperationStatus.OK; + } + + private StorageOperationStatus assosiateToDerived(GraphVertex nodeTypeVertex, List<GraphVertex> derivedResources) { + for (GraphVertex derivedV : derivedResources) { + TitanOperationStatus createEdge = titanDao.createEdge(nodeTypeVertex, derivedV, EdgeLabelEnum.DERIVED_FROM, null); + if (createEdge != TitanOperationStatus.OK) { + log.trace("Failed to associate resource {} to derived with id {}", nodeTypeVertex.getUniqueId(), derivedV.getUniqueId()); + return DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge); + } + } + return StorageOperationStatus.OK; + } + + private StorageOperationStatus addAdditionalInformationToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List<GraphVertex> derivedResources) { + // Note : currently only one derived supported!!!! + Either<Map<String, AdditionalInfoParameterDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.ADDITIONAL_INFORMATION); + if (dataFromDerived.isRight()) { + return dataFromDerived.right().value(); + } + Map<String, AdditionalInfoParameterDataDefinition> addInformationAll = dataFromDerived.left().value(); + + Map<String, AdditionalInfoParameterDataDefinition> addInformation = nodeType.getAdditionalInformation(); + if (addInformation != null) { + ToscaDataDefinition.mergeDataMaps(addInformationAll, addInformation); + } + if (!addInformationAll.isEmpty()) { + Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.ADDITIONAL_INFORMATION, EdgeLabelEnum.ADDITIONAL_INFORMATION, addInformationAll); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + private StorageOperationStatus associateCapabilitiesToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List<GraphVertex> derivedResources) { + // Note : currently only one derived supported!!!! + Either<Map<String, ListCapabilityDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.CAPABILITIES); + if (dataFromDerived.isRight()) { + return dataFromDerived.right().value(); + } + Map<String, ListCapabilityDataDefinition> capabiltiesAll = dataFromDerived.left().value(); + + Map<String, ListCapabilityDataDefinition> capabilties = nodeType.getCapabilties(); + if (capabilties != null) { + if (capabiltiesAll == null) { + capabiltiesAll = new HashMap<>(); + } + capabilties.values().forEach(l -> { + l.getListToscaDataDefinition().stream().filter(p -> p.getUniqueId() == null).forEach(p -> { + String uid = UniqueIdBuilder.buildCapabilityUid(nodeTypeVertex.getUniqueId(), p.getName()); + p.setUniqueId(uid); + }); + }); + + ToscaDataDefinition.mergeDataMaps(capabiltiesAll, capabilties); + capabiltiesAll.values().forEach(l -> { + l.getListToscaDataDefinition().forEach(c -> { + List<String> capabilitySources = c.getCapabilitySources(); + if (capabilitySources == null) { + capabilitySources = new ArrayList<>(); + } + capabilitySources.add((String) nodeType.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME)); + c.setCapabilitySources(capabilitySources); + }); + }); + } + capabiltiesAll.values().forEach(l -> { + l.getListToscaDataDefinition().forEach(c -> { + List<String> capabilitySources = c.getCapabilitySources(); + if (capabilitySources == null) { + capabilitySources = new ArrayList<>(); + } + capabilitySources.add((String) nodeType.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME)); + c.setCapabilitySources(capabilitySources); + }); + }); + if (!capabiltiesAll.isEmpty()) { + Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.CAPABILTIES, EdgeLabelEnum.CAPABILITIES, capabiltiesAll); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + private StorageOperationStatus associateRequirementsToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List<GraphVertex> derivedResources) { + // Note : currently only one derived supported!!!! + Either<Map<String, ListRequirementDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.REQUIREMENTS); + if (dataFromDerived.isRight()) { + return dataFromDerived.right().value(); + } + Map<String, ListRequirementDataDefinition> requirementsAll = dataFromDerived.left().value(); + + Map<String, ListRequirementDataDefinition> requirements = nodeType.getRequirements(); + if (requirements != null) { + if (requirementsAll == null) { + requirementsAll = new HashMap<>(); + } + requirements.values().forEach(l -> { + l.getListToscaDataDefinition().stream().filter(p -> p.getUniqueId() == null).forEach(p -> { + String uid = UniqueIdBuilder.buildRequirementUid(nodeTypeVertex.getUniqueId(), p.getName()); + p.setUniqueId(uid); + }); + }); + + ToscaDataDefinition.mergeDataMaps(requirementsAll, requirements); + + } + if (!requirementsAll.isEmpty()) { + Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.REQUIREMENTS, EdgeLabelEnum.REQUIREMENTS, requirementsAll); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + private StorageOperationStatus associateAttributesToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List<GraphVertex> derivedResources) { + // Note : currently only one derived supported!!!! + Either<Map<String, PropertyDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.ATTRIBUTES); + if (dataFromDerived.isRight()) { + return dataFromDerived.right().value(); + } + Map<String, PropertyDataDefinition> attributesAll = dataFromDerived.left().value(); + + Map<String, PropertyDataDefinition> attributes = nodeType.getAttributes(); + if (attributes != null) { + attributes.values().stream().filter(p -> p.getUniqueId() == null).forEach(p -> { + String uid = UniqueIdBuilder.buildAttributeUid(nodeTypeVertex.getUniqueId(), p.getName()); + p.setUniqueId(uid); + }); + ToscaDataDefinition.mergeDataMaps(attributesAll, attributes); + } + if (!attributesAll.isEmpty()) { + Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.ATTRIBUTES, EdgeLabelEnum.ATTRIBUTES, attributesAll); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + // TODO get from derived + private StorageOperationStatus associateCapabilitiesPropertiesToResource(GraphVertex nodeTypeVertex, NodeType nodeType, List<GraphVertex> derivedResources) { + // // Note : currently only one derived supported!!!! + Either<Map<String, MapPropertiesDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, EdgeLabelEnum.CAPABILITIES_PROPERTIES); + if (dataFromDerived.isRight()) { + return dataFromDerived.right().value(); + } + Map<String, MapPropertiesDataDefinition> propertiesAll = dataFromDerived.left().value(); + Map<String, MapPropertiesDataDefinition> capabiltiesProps = nodeType.getCapabiltiesProperties(); + if (capabiltiesProps != null) { + capabiltiesProps.values().forEach(l -> { + if (l.getMapToscaDataDefinition() != null && l.getMapToscaDataDefinition().values() != null) { + Collection<PropertyDataDefinition> mapToscaDataDefinition = l.getMapToscaDataDefinition().values(); + mapToscaDataDefinition.stream().filter(p -> p != null && p.getUniqueId() == null).forEach(p -> { + String uid = UniqueIdBuilder.buildRequirementUid(nodeTypeVertex.getUniqueId(), p.getName()); + p.setUniqueId(uid); + }); + } + }); + ToscaDataDefinition.mergeDataMaps(propertiesAll, capabiltiesProps); + } + if (!propertiesAll.isEmpty()) { + Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.CAPABILITIES_PROPERTIES, EdgeLabelEnum.CAPABILITIES_PROPERTIES, propertiesAll); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + public Either<List<GraphVertex>, StorageOperationStatus> findDerivedResources(NodeType nodeType) { + + List<GraphVertex> derivedResources = new ArrayList<>(); + List<String> derivedFromResources = nodeType.getDerivedFrom(); + if (derivedFromResources != null && !derivedFromResources.isEmpty()) { + + for (String parentResource : derivedFromResources) { + Either<List<GraphVertex>, TitanOperationStatus> getParentResources = derivedResourceResolver.findDerivedResources(parentResource); + List<GraphVertex> resources = null; + if (getParentResources.isRight()) { + log.error("Cannot find parent resource by tosca resource name {} in the graph.", parentResource); + return Either.right(StorageOperationStatus.PARENT_RESOURCE_NOT_FOUND); + + } else { + resources = getParentResources.left().value(); + if (resources == null || resources.size() == 0) { + log.error("Cannot find parent resource by tosca name {} in the graph. resources size is empty", parentResource); + return Either.right(StorageOperationStatus.PARENT_RESOURCE_NOT_FOUND); + } else { + if (resources.size() > 1) { + return handleMultipleParent(parentResource, derivedResources, resources); + } else { + GraphVertex parentResourceData = resources.get(0); + derivedResources.add(parentResourceData); + } + } + + } + + } + } + return Either.left(derivedResources); + } + + Either<List<GraphVertex>, StorageOperationStatus> handleMultipleParent(String parentResource, List<GraphVertex> derivedResource, List<GraphVertex> fetchedDerivedResources) { + + Either<List<GraphVertex>, StorageOperationStatus> result = Either.left(derivedResource); + try { + fetchedDerivedResources.sort((d1, d2) -> { + return new Double(Double.parseDouble((String) d1.getMetadataProperty(GraphPropertyEnum.VERSION))).compareTo(Double.parseDouble((String) d2.getMetadataProperty(GraphPropertyEnum.VERSION))); + }); + + int actualHighestIndex = fetchedDerivedResources.size() - 1; + derivedResource.add(fetchedDerivedResources.get(actualHighestIndex)); + fetchedDerivedResources.remove(actualHighestIndex); + + StorageOperationStatus status = fixMultipleParent(fetchedDerivedResources); + if (status != StorageOperationStatus.OK) { + result = Either.right(status); + } + } catch (Exception e) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during handle multiple parent {}. Exception is {}", parentResource, e.getMessage()); + result = Either.right(StorageOperationStatus.GENERAL_ERROR); + } + return result; + } + + private StorageOperationStatus fixMultipleParent(List<GraphVertex> fetchedDerivedResources) { + StorageOperationStatus result = StorageOperationStatus.OK; + for (GraphVertex fetchedDerivedResource : fetchedDerivedResources) { + fetchedDerivedResource.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION, false); + Either<GraphVertex, TitanOperationStatus> updateVertexRes = titanDao.updateVertex(fetchedDerivedResource); + if (updateVertexRes.isRight()) { + TitanOperationStatus titatStatus = updateVertexRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to set highest version of node type {} to false. Status is {}", fetchedDerivedResource.getMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME), titatStatus); + result = DaoStatusConverter.convertTitanStatusToStorageStatus(titatStatus); + break; + } + } + return result; + } + + private GraphVertex fillMetadata(GraphVertex nodeTypeVertex, NodeType nodeType) { + nodeTypeVertex.setLabel(VertexTypeEnum.NODE_TYPE); + + fillCommonMetadata(nodeTypeVertex, nodeType); + + return nodeTypeVertex; + } + + @Override + public Either<ToscaElement, StorageOperationStatus> deleteToscaElement(GraphVertex toscaElementVertex) { + Either<ToscaElement, StorageOperationStatus> nodeType = getToscaElement(toscaElementVertex, new ComponentParametersView()); + if (nodeType.isRight()) { + log.debug("Failed to fetch tosca element {} error {}", toscaElementVertex.getUniqueId(), nodeType.right().value()); + return nodeType; + } + TitanOperationStatus status = disassociateAndDeleteCommonElements(toscaElementVertex); + if (status != TitanOperationStatus.OK) { + Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CAPABILITIES); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to disassociate capabilties for {} error {}", toscaElementVertex.getUniqueId(), status); + Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CAPABILITIES_PROPERTIES); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to disassociate capabilties properties for {} error {}", toscaElementVertex.getUniqueId(), status); + Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.REQUIREMENTS); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to disassociate requirements for {} error {}", toscaElementVertex.getUniqueId(), status); + Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ATTRIBUTES); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to disassociate attributes for {} error {}", toscaElementVertex.getUniqueId(), status); + Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INTERFACE_ARTIFACTS); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to disassociate interface artifacts for {} error {}", toscaElementVertex.getUniqueId(), status); + Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + toscaElementVertex.getVertex().remove(); + log.trace("Tosca element vertex for {} was removed", toscaElementVertex.getUniqueId()); + + return nodeType; + } + + @SuppressWarnings("unchecked") + @Override + public Either<NodeType, StorageOperationStatus> createToscaElement(ToscaElement toscaElement) { + return createNodeType((NodeType) toscaElement); + } + + @Override + protected <T extends ToscaElement> TitanOperationStatus setCategoriesFromGraph(GraphVertex vertexComponent, T toscaElement) { + return setResourceCategoryFromGraph(vertexComponent, toscaElement); + } + + @Override + protected <T extends ToscaElement> StorageOperationStatus validateCategories(T toscaElementToUpdate, GraphVertex elementV) { + return validateResourceCategory(toscaElementToUpdate, elementV); + } + + @Override + protected <T extends ToscaElement> StorageOperationStatus updateDerived(T toscaElementToUpdate, GraphVertex nodeTypeV) { + + NodeType nodeType = (NodeType) toscaElementToUpdate; + + List<String> derivedFromResources = nodeType.getDerivedFrom(); + + // now supported only single derived from + if (derivedFromResources != null && !derivedFromResources.isEmpty() && derivedFromResources.get(0) != null) { + String firstDerived = derivedFromResources.get(0); + boolean derivedFromGenericType = null != nodeType.getDerivedFromGenericType(); + Either<GraphVertex, TitanOperationStatus> childVertex = titanDao.getChildVertex(nodeTypeV, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.NoParse); + if (childVertex.isRight()) { + TitanOperationStatus getchieldError = childVertex.right().value(); + log.debug("Failed to fetch derived resource for element {} error {}", nodeTypeV.getUniqueId(), getchieldError); + return DaoStatusConverter.convertTitanStatusToStorageStatus(getchieldError); + } + GraphVertex firstDerivedInChain = childVertex.left().value(); + + String firstCurrentDerived = (String) firstDerivedInChain.getMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME); + if (!firstDerived.equals(firstCurrentDerived) || derivedFromGenericType) { + + Map<GraphPropertyEnum, Object> propertiesToMatch = new HashMap<>(); + propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + + propertiesToMatch.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, firstDerived); + propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + + Either<List<GraphVertex>, TitanOperationStatus> getParentResources = titanDao.getByCriteria(VertexTypeEnum.NODE_TYPE, propertiesToMatch, JsonParseFlagEnum.NoParse); + + if (getParentResources.isRight()) { + TitanOperationStatus error = getParentResources.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch derived by criteria {}. error {} ", propertiesToMatch, error); + return DaoStatusConverter.convertTitanStatusToStorageStatus(error); + } + // must be only one + GraphVertex newDerivedV = getParentResources.left().value().get(0); + return updateDerived(toscaElementToUpdate, nodeTypeV, firstDerivedInChain, newDerivedV, false); + } + } + return StorageOperationStatus.OK; + } + + /** + * + * @param toscaElementToUpdate + * @param nodeTypeV + * @param preDerivedV + * @param newDerivedV + * @param mergeValues + * @return + */ + protected <T extends ToscaElement> StorageOperationStatus updateDerived(T toscaElementToUpdate, GraphVertex nodeTypeV, GraphVertex preDerivedV, GraphVertex newDerivedV, boolean mergeValues) { + Set<String> preDerivedChainIdList = new HashSet(); + preDerivedChainIdList.add(preDerivedV.getUniqueId()); + Either<GraphVertex, TitanOperationStatus> childVertex = titanDao.getChildVertex(preDerivedV, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.NoParse); + while (childVertex.isLeft()) { + GraphVertex currentChield = childVertex.left().value(); + preDerivedChainIdList.add(currentChield.getUniqueId()); + childVertex = titanDao.getChildVertex(currentChield, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.NoParse); + } + + List<GraphVertex> derivedResources = new ArrayList<>(); + derivedResources.add(newDerivedV); + StorageOperationStatus updateStatus = updateDataFromNewDerived(derivedResources, nodeTypeV, (NodeType) toscaElementToUpdate, mergeValues, preDerivedChainIdList); + if (updateStatus != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update data for {} from new derived {} ", nodeTypeV.getUniqueId(), newDerivedV.getUniqueId(), updateStatus); + return updateStatus; + } + + Either<Edge, TitanOperationStatus> deleteEdge = titanDao.deleteEdge(nodeTypeV, preDerivedV, EdgeLabelEnum.DERIVED_FROM); + if (deleteEdge.isRight()) { + TitanOperationStatus deleteError = deleteEdge.right().value(); + log.debug("Failed to disassociate element {} from derived {} , error {}", nodeTypeV.getUniqueId(), preDerivedV.getUniqueId(), deleteError); + return DaoStatusConverter.convertTitanStatusToStorageStatus(deleteError); + } + + titanDao.createEdge(nodeTypeV, newDerivedV, EdgeLabelEnum.DERIVED_FROM, new HashMap<>()); + + return StorageOperationStatus.OK; + } + + private StorageOperationStatus associateDerivedDataByType(EdgeLabelEnum edgeLabel, GraphVertex nodeTypeV, NodeType nodeToUpdate, List<GraphVertex> newDerived) { + + switch (edgeLabel) { + case CAPABILITIES: + return associateCapabilitiesToResource(nodeTypeV, nodeToUpdate, newDerived); + case REQUIREMENTS: + return associateRequirementsToResource(nodeTypeV, nodeToUpdate, newDerived); + case PROPERTIES: + return associatePropertiesToResource(nodeTypeV, nodeToUpdate, newDerived); + case ATTRIBUTES: + return associateAttributesToResource(nodeTypeV, nodeToUpdate, newDerived); + case ADDITIONAL_INFORMATION: + return addAdditionalInformationToResource(nodeTypeV, nodeToUpdate, newDerived); + case CAPABILITIES_PROPERTIES: + return associateCapabilitiesPropertiesToResource(nodeTypeV, nodeToUpdate, newDerived); + default: + return StorageOperationStatus.OK; + } + + } + + private StorageOperationStatus updateDataFromNewDerived(List<GraphVertex> newDerived, GraphVertex nodeTypeV, NodeType nodeToUpdate, boolean mergeValues, Set<String> preDerivedChainIdList) { + EnumSet<EdgeLabelEnum> edgeLabels = EnumSet.of(EdgeLabelEnum.CAPABILITIES, EdgeLabelEnum.REQUIREMENTS, EdgeLabelEnum.PROPERTIES, EdgeLabelEnum.ATTRIBUTES, EdgeLabelEnum.CAPABILITIES_PROPERTIES, EdgeLabelEnum.ADDITIONAL_INFORMATION); + StorageOperationStatus status = null; + for (EdgeLabelEnum edge : edgeLabels) { + status = updateDataByType(newDerived, nodeTypeV, edge, nodeToUpdate, mergeValues, preDerivedChainIdList); + if (status != StorageOperationStatus.OK) { + break; + } + } + return status; + + } + + private <T extends ToscaDataDefinition> StorageOperationStatus updateDataByType(List<GraphVertex> newDerivedList, GraphVertex nodeTypeV, EdgeLabelEnum label, NodeType nodeElement, boolean mergeValues, Set<String> preDerivedChainIdList) { + log.debug("Update data from derived for element {} type {}", nodeTypeV.getUniqueId(), label); + Either<GraphVertex, TitanOperationStatus> dataFromGraph = getDataVertex(nodeTypeV, label); + if (dataFromGraph.isRight()) { + if (TitanOperationStatus.NOT_FOUND == dataFromGraph.right().value()) + return associateDerivedDataByType(label, nodeTypeV, nodeElement, newDerivedList); + return DaoStatusConverter.convertTitanStatusToStorageStatus(dataFromGraph.right().value()); + } + GraphVertex dataV = dataFromGraph.left().value(); + + Map<String, T> mapFromGraph = (Map<String, T>) dataV.getJson(); + Map<String, T> valuesFrmPrev = null; + if (isSimpleHierarchy(label)) { + if (mergeValues) { + valuesFrmPrev = mapFromGraph.entrySet().stream().filter(e -> e.getValue().getOwnerId() != null).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + } + mapFromGraph.entrySet().removeIf(e -> preDerivedChainIdList.contains(e.getValue().getOwnerId())); + } else { + final Map<String, T> valuesFrmPrevFinal = new HashMap<>(); + mapFromGraph.entrySet().stream().forEach(e -> { + T value = e.getValue(); + value = ToscaDataDefinition.removeAndCollectByOwnerId(value, preDerivedChainIdList); + valuesFrmPrevFinal.put(e.getKey(), value); + }); + valuesFrmPrev = valuesFrmPrevFinal; + mapFromGraph.entrySet().removeIf(e->e.getValue().isEmpty()); + } + + Either<Map<String, T>, StorageOperationStatus> dataFromDerived = getDataFromDerived(newDerivedList, label); + if (dataFromDerived.isRight()) { + return dataFromDerived.right().value(); + } + Map<String, T> dataFromDerivedAll = dataFromDerived.left().value(); + + Either<Map<String, T>, String> merged = ToscaDataDefinition.mergeDataMaps(dataFromDerivedAll, mapFromGraph); + if (merged.isRight()) { + log.debug("property {} cannot be overriden", merged.right().value()); + return StorageOperationStatus.INVALID_PROPERTY; + } + if (mergeValues && valuesFrmPrev != null) { + valuesFrmPrev.entrySet().forEach(e -> { + T newData = merged.left().value().get(e.getKey()); + if (newData != null) { + if (isSimpleHierarchy(label)) { + e.getValue().mergeFunction(newData, true); + }else{ + e.getValue().updateIfExist(newData, true); + } + } + }); + } + dataV.setJson(dataFromDerivedAll); + Either<GraphVertex, TitanOperationStatus> updateDataV = updateOrCopyOnUpdate(dataV, nodeTypeV, label); + if (updateDataV.isRight()) { + return DaoStatusConverter.convertTitanStatusToStorageStatus(updateDataV.right().value()); + } + return StorageOperationStatus.OK; + } + + private boolean isSimpleHierarchy(EdgeLabelEnum label) { + switch (label) { + case PROPERTIES: + case ATTRIBUTES: + case ADDITIONAL_INFORMATION: + case ARTIFACTS: + case GROUPS: + case INPUTS: + return true; + default: + return false; + } + } + + @Override + public <T extends ToscaElement> void fillToscaElementVertexData(GraphVertex elementV, T toscaElementToUpdate, JsonParseFlagEnum flag) { + fillMetadata(elementV, (NodeType) toscaElementToUpdate); + } + + public Either<ToscaElement, StorageOperationStatus> shouldUpdateDerivedVersion(ToscaElement toscaElementToUpdate, GraphVertex nodeTypeV) { + NodeType nodeType = (NodeType) toscaElementToUpdate; + + Either<GraphVertex, TitanOperationStatus> childVertex = titanDao.getChildVertex(nodeTypeV, EdgeLabelEnum.DERIVED_FROM, JsonParseFlagEnum.NoParse); + if (childVertex.isRight()) { + TitanOperationStatus getchildError = childVertex.right().value(); + if (getchildError == TitanOperationStatus.NOT_FOUND) { + log.debug("derived resource for element {} not found", nodeTypeV.getUniqueId()); + return Either.right(StorageOperationStatus.OK); + } + + log.debug("Failed to fetch derived resource for element {} error {}", nodeTypeV.getUniqueId(), getchildError); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getchildError)); + } + GraphVertex firstDerivedInChain = childVertex.left().value(); + + String currentVersion = (String) firstDerivedInChain.getMetadataProperty(GraphPropertyEnum.VERSION); + + Map<GraphPropertyEnum, Object> props = new HashMap<>(); + props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, nodeType.getDerivedFrom().get(0)); + props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + + Map<GraphPropertyEnum, Object> propsHasNot = new HashMap<>(); + propsHasNot.put(GraphPropertyEnum.IS_DELETED, true); + Either<List<GraphVertex>, TitanOperationStatus> byCriteria = titanDao.getByCriteria(VertexTypeEnum.NODE_TYPE, props, propsHasNot, JsonParseFlagEnum.NoParse); + if (byCriteria.isRight()) { + log.debug("Failed to fetch derived by props {} error {}", props, byCriteria.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(byCriteria.right().value())); + } + List<GraphVertex> lastDerived = byCriteria.left().value(); + // now supported only one derived!!! Change in future!(Evg) + GraphVertex derivedFromHighest = lastDerived.get(0); + String highestVersion = (String) derivedFromHighest.getMetadataProperty(GraphPropertyEnum.VERSION); + if (!highestVersion.equals(currentVersion)) { + + // need to update to latest version of derived from + StorageOperationStatus updateDerived = updateDerived(toscaElementToUpdate, nodeTypeV, firstDerivedInChain, derivedFromHighest, true); + + if (updateDerived != StorageOperationStatus.OK) { + log.debug("Failed to update {} to highest derived {} from error {}", nodeTypeV.getUniqueId(), derivedFromHighest.getUniqueId(), updateDerived); + return Either.right(updateDerived); + } + return getToscaElement(nodeTypeV.getUniqueId(), new ComponentParametersView()); + } + // no version changes + return Either.right(StorageOperationStatus.OK); + } } 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 index d775f44bdb..efbac3301e 100644 --- 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 @@ -1,9 +1,5 @@ package org.openecomp.sdc.be.model.jsontitan.operations; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - 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; @@ -13,13 +9,16 @@ 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 org.openecomp.sdc.common.log.wrappers.Logger; + +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 static final Logger log = Logger.getLogger(PolicyOperation.class.getName()); private TopologyTemplateOperation topologyTemplateOperation; private TitanDao titanDao; 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 d109439cc1..9fe59d95f1 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,16 +20,10 @@ 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.commons.lang3.StringUtils; import org.apache.tinkerpop.gremlin.structure.Direction; import org.apache.tinkerpop.gremlin.structure.Edge; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; @@ -37,1283 +31,1206 @@ 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.ForwardingPathDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition; -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.PolicyDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.*; +import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapCapabilityProperty; +import org.openecomp.sdc.be.datatypes.elements.MapListCapabilityDataDefinition; 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.datatypes.tosca.ToscaDataDefinition; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate; import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; import org.openecomp.sdc.be.model.jsontitan.enums.JsonConstantKeysEnum; import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; +import org.openecomp.sdc.be.model.operations.StorageException; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.be.model.utils.ComponentUtilities; 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 org.openecomp.sdc.common.log.wrappers.Logger; +import org.openecomp.sdc.common.util.ValidationUtils; +import org.springframework.beans.factory.annotation.Autowired; -import com.google.gson.reflect.TypeToken; - -import fj.data.Either; +import java.lang.reflect.Type; +import java.util.*; +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; - - topologyTemplate.generateUUID(); - - topologyTemplate = (TopologyTemplate) getResourceMetaDataFromResource(topologyTemplate); - String resourceUniqueId = topologyTemplate.getUniqueId(); - if (resourceUniqueId == null) { - resourceUniqueId = UniqueIdBuilder.buildResourceUniqueId(); - topologyTemplate.setUniqueId(resourceUniqueId); - } - - GraphVertex topologyTemplateVertex = new GraphVertex(); - topologyTemplateVertex = fillMetadata(topologyTemplateVertex, topologyTemplate, JsonParseFlagEnum.ParseAll); - - Either<GraphVertex, TitanOperationStatus> createdVertex = titanDao.createVertex(topologyTemplateVertex); - if (createdVertex.isRight()) { - TitanOperationStatus status = createdVertex.right().value(); - log.error("Error returned after creating topology template data node {}. status returned is ", topologyTemplateVertex, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - - topologyTemplateVertex = createdVertex.left().value(); - - StorageOperationStatus assosiateCommon = assosiateCommonForToscaElement(topologyTemplateVertex, topologyTemplate, null); - if (assosiateCommon != StorageOperationStatus.OK) { - result = Either.right(assosiateCommon); - return result; - } - - StorageOperationStatus associateCategory = assosiateMetadataToCategory(topologyTemplateVertex, topologyTemplate); - if (associateCategory != StorageOperationStatus.OK) { - result = Either.right(associateCategory); - return result; - } - - StorageOperationStatus associateInputs = associateInputsToComponent(topologyTemplateVertex, topologyTemplate); - if (associateInputs != StorageOperationStatus.OK) { - result = Either.right(associateInputs); - return result; - } - StorageOperationStatus associateGroups = associateGroupsToComponent(topologyTemplateVertex, topologyTemplate); - if (associateGroups != StorageOperationStatus.OK) { - 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); - return result; - } - StorageOperationStatus associateInstProperties = associateInstPropertiesToComponent(topologyTemplateVertex, topologyTemplate); - if (associateInstProperties != StorageOperationStatus.OK) { - result = Either.right(associateInstProperties); - return result; - } - StorageOperationStatus associateInstInputs = associateInstInputsToComponent(topologyTemplateVertex, topologyTemplate); - if (associateInstProperties != StorageOperationStatus.OK) { - result = Either.right(associateInstInputs); - return result; - } - StorageOperationStatus associateInstGroups = associateInstGroupsToComponent(topologyTemplateVertex, topologyTemplate); - if (associateInstGroups != StorageOperationStatus.OK) { - result = Either.right(associateInstInputs); - return result; - } - - StorageOperationStatus associateRequirements = associateRequirementsToResource(topologyTemplateVertex, topologyTemplate); - if (associateRequirements != StorageOperationStatus.OK) { - result = Either.right(associateRequirements); - return result; - } - - StorageOperationStatus associateCapabilities = associateCapabilitiesToResource(topologyTemplateVertex, topologyTemplate); - if (associateCapabilities != StorageOperationStatus.OK) { - result = Either.right(associateCapabilities); - return result; - } - - StorageOperationStatus associateArtifacts = associateTopologyTemplateArtifactsToComponent(topologyTemplateVertex, topologyTemplate); - if (associateArtifacts != StorageOperationStatus.OK) { - result = Either.right(associateArtifacts); - return result; - } - - StorageOperationStatus addAdditionalInformation = addAdditionalInformationToResource(topologyTemplateVertex, topologyTemplate); - if (addAdditionalInformation != StorageOperationStatus.OK) { - result = Either.right(addAdditionalInformation); - return result; - } - StorageOperationStatus associateCapProperties = associateCapPropertiesToResource(topologyTemplateVertex, topologyTemplate); - if (associateCapProperties != StorageOperationStatus.OK) { - result = Either.right(associateCapProperties); - return result; - } - - StorageOperationStatus associateInterfaces = associateInterfacesToResource(topologyTemplateVertex, topologyTemplate); - if (associateInterfaces != StorageOperationStatus.OK) { - result = Either.right(associateInterfaces); - 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()) { - Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(topologyTemplateVertex, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, calculatedCapProperties); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus associateCapabilitiesToResource(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { - Map<String, MapListCapabiltyDataDefinition> calculatedCapabilities = topologyTemplate.getCalculatedCapabilities(); - if (calculatedCapabilities != null && !calculatedCapabilities.isEmpty()) { - Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_CAPABILITIES, EdgeLabelEnum.CALCULATED_CAPABILITIES, calculatedCapabilities); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - Map<String, MapListCapabiltyDataDefinition> fullfilledCapabilities = topologyTemplate.getFullfilledCapabilities(); - if (fullfilledCapabilities != null && !fullfilledCapabilities.isEmpty()) { - Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.FULLFILLED_CAPABILITIES, EdgeLabelEnum.FULLFILLED_CAPABILITIES, fullfilledCapabilities); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - - } - - private StorageOperationStatus associateRequirementsToResource(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { - Map<String, MapListRequirementDataDefinition> calculatedRequirements = topologyTemplate.getCalculatedRequirements(); - if (calculatedRequirements != null && !calculatedRequirements.isEmpty()) { - Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_REQUIREMENTS, EdgeLabelEnum.CALCULATED_REQUIREMENTS, calculatedRequirements); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - Map<String, MapListRequirementDataDefinition> fullfilledRequirements = topologyTemplate.getFullfilledRequirements(); - if (fullfilledRequirements != null && !fullfilledRequirements.isEmpty()) { - Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.FULLFILLED_REQUIREMENTS, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, fullfilledRequirements); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus associateTopologyTemplateArtifactsToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { - Map<String, ArtifactDataDefinition> addInformation = topologyTemplate.getServiceApiArtifacts(); - - if (addInformation != null && !addInformation.isEmpty()) { - addInformation.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> { - String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase()); - a.setUniqueId(uniqueId); - }); - Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.SERVICE_API_ARTIFACTS, EdgeLabelEnum.SERVICE_API_ARTIFACTS, addInformation); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - Map<String, MapArtifactDataDefinition> instArtifacts = topologyTemplate.getInstDeploymentArtifacts(); - - if (instArtifacts != null && !instArtifacts.isEmpty()) { - Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, instArtifacts); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - Map<String, MapArtifactDataDefinition> instInfoArtifacts = topologyTemplate.getInstanceArtifacts(); - - if (instInfoArtifacts != null && !instInfoArtifacts.isEmpty()) { - Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.INSTANCE_ARTIFACTS, EdgeLabelEnum.INSTANCE_ARTIFACTS, instInfoArtifacts); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus addAdditionalInformationToResource(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { - - Map<String, AdditionalInfoParameterDataDefinition> addInformation = topologyTemplate.getAdditionalInformation(); - - if (addInformation != null && !addInformation.isEmpty()) { - Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.ADDITIONAL_INFORMATION, EdgeLabelEnum.ADDITIONAL_INFORMATION, addInformation); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - public StorageOperationStatus associateInstPropertiesToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { - Map<String, MapPropertiesDataDefinition> instProps = topologyTemplate.getInstProperties(); - return associateInstPropertiesToComponent(nodeTypeVertex, instProps); - } - - public StorageOperationStatus associateInstInputsToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { - Map<String, MapPropertiesDataDefinition> instProps = topologyTemplate.getInstInputs(); - return associateInstInputsToComponent(nodeTypeVertex, instProps); - } - - public StorageOperationStatus associateInstGroupsToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { - Map<String, MapGroupsDataDefinition> instGroups = topologyTemplate.getInstGroups(); - return associateInstGroupsToComponent(nodeTypeVertex, instGroups); - } - - - public StorageOperationStatus associateInstPropertiesToComponent(GraphVertex nodeTypeVertex, Map<String, MapPropertiesDataDefinition> instProps) { - if (instProps != null && !instProps.isEmpty()) { - Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.INST_PROPERTIES, EdgeLabelEnum.INST_PROPERTIES, instProps); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - public StorageOperationStatus associateInstInputsToComponent(GraphVertex nodeTypeVertex, Map<String, MapPropertiesDataDefinition> instInputs) { - if (instInputs != null && !instInputs.isEmpty()) { - Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.INST_INPUTS, EdgeLabelEnum.INST_INPUTS, instInputs); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - public StorageOperationStatus associateInstGroupsToComponent(GraphVertex nodeTypeVertex, Map<String, MapGroupsDataDefinition> instGroups) { - if (instGroups != null && !instGroups.isEmpty()) { - Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.INST_GROUPS, EdgeLabelEnum.INST_GROUPS, instGroups); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - - public StorageOperationStatus deleteInstInputsToComponent(GraphVertex nodeTypeVertex, Map<String, MapPropertiesDataDefinition> instInputs) { - - if (instInputs != null && !instInputs.isEmpty()) { - instInputs.entrySet().forEach(i -> { - List<String> uniqueKeys = new ArrayList<String>(i.getValue().getMapToscaDataDefinition().keySet()); - List<String> pathKeys = new ArrayList<String>(); - pathKeys.add(i.getKey()); - - StorageOperationStatus status = deleteToscaDataDeepElements(nodeTypeVertex, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, uniqueKeys, pathKeys, JsonPresentationFields.NAME); - if (status != StorageOperationStatus.OK) { - return; - } - }); - } - - return StorageOperationStatus.OK; - } - - public StorageOperationStatus addInstPropertiesToComponent(GraphVertex nodeTypeVertex, Map<String, MapPropertiesDataDefinition> instInputs) { - - if (instInputs != null && !instInputs.isEmpty()) { - instInputs.entrySet().forEach(i -> { - StorageOperationStatus status = addToscaDataDeepElementsBlockToToscaElement(nodeTypeVertex, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, i.getValue(), i.getKey()); - if (status != StorageOperationStatus.OK) { - return; - } - }); - } - - return StorageOperationStatus.OK; - } - - public StorageOperationStatus associateInstDeploymentArtifactsToComponent(GraphVertex nodeTypeVertex, Map<String, MapArtifactDataDefinition> instArtifacts) { - return associateInstanceArtifactsToComponent(nodeTypeVertex, instArtifacts, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS); - } - - public StorageOperationStatus associateInstArtifactsToComponent(GraphVertex nodeTypeVertex, Map<String, MapArtifactDataDefinition> instArtifacts) { - return associateInstanceArtifactsToComponent(nodeTypeVertex, instArtifacts, VertexTypeEnum.INSTANCE_ARTIFACTS, EdgeLabelEnum.INSTANCE_ARTIFACTS); - } - - private StorageOperationStatus associateInstanceArtifactsToComponent(GraphVertex nodeTypeVertex, Map<String, MapArtifactDataDefinition> instProps, VertexTypeEnum vertexType, EdgeLabelEnum edgeLabel) { - if (instProps != null && !instProps.isEmpty()) { - Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, vertexType, edgeLabel, instProps); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - public StorageOperationStatus associateCalcCapReqToComponent(GraphVertex nodeTypeVertex, Map<String, MapListRequirementDataDefinition> calcRequirements, Map<String, MapListCapabiltyDataDefinition> calcCapabilty, Map<String, MapCapabiltyProperty> calculatedCapabilitiesProperties) { - if (calcRequirements != null && !calcRequirements.isEmpty()) { - Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_REQUIREMENTS, EdgeLabelEnum.CALCULATED_REQUIREMENTS, calcRequirements); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - Map<String, MapListRequirementDataDefinition> fullFilled = new HashMap<>(); - assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.FULLFILLED_REQUIREMENTS, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, fullFilled); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - if (calcCapabilty != null && !calcCapabilty.isEmpty()) { - Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_CAPABILITIES, EdgeLabelEnum.CALCULATED_CAPABILITIES, calcCapabilty); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - Map<String, MapListCapabiltyDataDefinition> fullFilled = new HashMap<>(); - assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.FULLFILLED_CAPABILITIES, EdgeLabelEnum.FULLFILLED_CAPABILITIES, fullFilled); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - if ( calculatedCapabilitiesProperties != null && !calculatedCapabilitiesProperties.isEmpty() ){ - Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, calculatedCapabilitiesProperties); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus associateInstAttributesToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { - Map<String, MapPropertiesDataDefinition> instAttr = topologyTemplate.getInstAttributes(); - 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); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - public StorageOperationStatus associateGroupsToComponent(GraphVertex nodeTypeVertex, Map<String, GroupDataDefinition> groups) { - - if (groups != null && !groups.isEmpty()) { - groups.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.GROUPS, EdgeLabelEnum.GROUPS, groups); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus associateGroupsToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { - return associateGroupsToComponent(nodeTypeVertex, topologyTemplate.getGroups()); - } - - public StorageOperationStatus associateInputsToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { - Map<String, PropertyDataDefinition> inputs = topologyTemplate.getInputs(); - return associateInputsToComponent(nodeTypeVertex, inputs, topologyTemplate.getUniqueId()); - } - - public StorageOperationStatus associateInputsToComponent(GraphVertex nodeTypeVertex, Map<String, PropertyDataDefinition> inputs, String id) { - if (inputs != null && !inputs.isEmpty()) { - inputs.values().stream().filter(e -> e.getUniqueId() == null).forEach(e -> e.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(id, e.getName()))); - - Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.INPUTS, EdgeLabelEnum.INPUTS, inputs); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - private GraphVertex fillMetadata(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate, JsonParseFlagEnum flag) { - nodeTypeVertex.setLabel(VertexTypeEnum.TOPOLOGY_TEMPLATE); - fillCommonMetadata(nodeTypeVertex, topologyTemplate); - if (flag == JsonParseFlagEnum.ParseAll || flag == JsonParseFlagEnum.ParseJson) { - nodeTypeVertex.setJson(topologyTemplate.getCompositions()); - } - nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.CSAR_UUID, topologyTemplate.getMetadataValue(JsonPresentationFields.CSAR_UUID)); - nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, topologyTemplate.getMetadataValue(JsonPresentationFields.DISTRIBUTION_STATUS)); - - return nodeTypeVertex; - - } - - private StorageOperationStatus assosiateMetadataToCategory(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { - if (topologyTemplate.getResourceType() == null) { - // service - return associateServiceMetadataToCategory(nodeTypeVertex, topologyTemplate); - } else { - // VF - return assosiateResourceMetadataToCategory(nodeTypeVertex, topologyTemplate); - } - } - - private StorageOperationStatus associateServiceMetadataToCategory(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { - String categoryName = topologyTemplate.getCategories().get(0).getName(); - Either<GraphVertex, StorageOperationStatus> category = categoryOperation.getCategory(categoryName, VertexTypeEnum.SERVICE_CATEGORY); - if (category.isRight()) { - log.trace("NO category {} for service {}", categoryName, topologyTemplate.getUniqueId()); - return StorageOperationStatus.CATEGORY_NOT_FOUND; - } - GraphVertex categoryV = category.left().value(); - TitanOperationStatus createEdge = titanDao.createEdge(nodeTypeVertex, categoryV, EdgeLabelEnum.CATEGORY, new HashMap<>()); - if (createEdge != TitanOperationStatus.OK) { - log.trace("Failed to associate resource {} to category {} with id {}", topologyTemplate.getUniqueId(), categoryName, categoryV.getUniqueId()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge); - } - return StorageOperationStatus.OK; - } - - @Override - public Either<ToscaElement, StorageOperationStatus> getToscaElement(String uniqueId, ComponentParametersView componentParametersView) { - JsonParseFlagEnum parseFlag = componentParametersView.detectParseFlag(); - - Either<GraphVertex, StorageOperationStatus> componentByLabelAndId = getComponentByLabelAndId(uniqueId, ToscaElementTypeEnum.TopologyTemplate, parseFlag); - if (componentByLabelAndId.isRight()) { - return Either.right(componentByLabelAndId.right().value()); - } - GraphVertex componentV = componentByLabelAndId.left().value(); - - return getToscaElement(componentV, componentParametersView); - - } - // ------------------------------------------------------------- - - public Either<ToscaElement, StorageOperationStatus> getToscaElement(GraphVertex componentV, ComponentParametersView componentParametersView) { - TopologyTemplate toscaElement; - - toscaElement = convertToTopologyTemplate(componentV); - TitanOperationStatus status; - if (!componentParametersView.isIgnoreUsers()) { - status = setCreatorFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - - status = setLastModifierFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - if (!componentParametersView.isIgnoreCategories()) { - status = setTopologyTempalteCategoriesFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - - } - } - if (!componentParametersView.isIgnoreArtifacts()) { - TitanOperationStatus storageStatus = setAllArtifactsFromGraph(componentV, toscaElement); - if (storageStatus != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(storageStatus)); - } - } - if (!componentParametersView.isIgnoreComponentInstancesProperties()) { - status = setComponentInstancesPropertiesFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - if (!componentParametersView.isIgnoreCapabilities()) { - status = setCapabilitiesFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - if (!componentParametersView.isIgnoreRequirements()) { - status = setRequirementsFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - if (!componentParametersView.isIgnoreAllVersions()) { - status = setAllVersions(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - if (!componentParametersView.isIgnoreAdditionalInformation()) { - status = setAdditionalInformationFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - - if (!componentParametersView.isIgnoreGroups()) { - status = setGroupsFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - - } - 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 (!componentParametersView.isIgnoreInputs()) { - status = setInputsFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - - } - if (!componentParametersView.isIgnoreProperties()) { - status = setPropertiesFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - - } - - if (!componentParametersView.isIgnoreComponentInstancesInputs()) { - status = setComponentInstancesInputsFromGraph(componentV, toscaElement); - if (status != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - - } - } - - 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)); - - } - } - if (!componentParametersView.isIgnoreInterfaces()) { - TitanOperationStatus storageStatus = setInterfcesFromGraph(componentV, toscaElement); - if (storageStatus != TitanOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(storageStatus)); - } - } - - return Either.left(toscaElement); - } - - private TitanOperationStatus setInterfcesFromGraph(GraphVertex componentV, - TopologyTemplate topologyTemplate) { - Either<Map<String, InterfaceDataDefinition>, TitanOperationStatus> result = getDataFromGraph - (componentV, - EdgeLabelEnum.INTERFACE_ARTIFACTS); - if (result.isLeft()) { - topologyTemplate.setInterfaces(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - return TitanOperationStatus.OK; - } - - private StorageOperationStatus associateInterfacesToResource(GraphVertex topologyTemplateVertex, - TopologyTemplate topologyTemplate) { - Map<String, InterfaceDataDefinition> interfaces = topologyTemplate.getInterfaces(); - return associateInterfacesToComponent(topologyTemplateVertex,interfaces); - } - - public StorageOperationStatus associateInterfacesToComponent(GraphVertex nodeTypeVertex, - Map<String, InterfaceDataDefinition> - interfaceMap) { - if (interfaceMap != null && !interfaceMap.isEmpty()) { - Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData - (nodeTypeVertex, VertexTypeEnum.INTERFACE_ARTIFACTS, EdgeLabelEnum.INTERFACE_ARTIFACTS, interfaceMap); - if (assosiateElementToData.isRight()) { - return assosiateElementToData.right().value(); - } - } - return StorageOperationStatus.OK; - } - - - 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()) { - topologyTemplate.setCalculatedCapabilitiesProperties(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - return TitanOperationStatus.OK; - } - - private TitanOperationStatus setPropertiesFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) { - Either<Map<String, PropertyDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.PROPERTIES); - if (result.isLeft()) { - toscaElement.setProperties(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - return TitanOperationStatus.OK; - } - - private TitanOperationStatus setInstGroupsFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) { - Either<Map<String, MapGroupsDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INST_GROUPS); - if (result.isLeft()) { - topologyTemplate.setInstGroups(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - return TitanOperationStatus.OK; - } - - private TitanOperationStatus setComponentInstancesPropertiesFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) { - Either<Map<String, MapPropertiesDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INST_PROPERTIES); - if (result.isLeft()) { - topologyTemplate.setInstProperties(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - return TitanOperationStatus.OK; - } - - private TitanOperationStatus setComponentInstancesInputsFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) { - Either<Map<String, MapPropertiesDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INST_INPUTS); - if (result.isLeft()) { - topologyTemplate.setInstInputs(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - return TitanOperationStatus.OK; - } - - @Override - protected <T extends ToscaElement> TitanOperationStatus setRequirementsFromGraph(GraphVertex componentV, T toscaElement) { - Either<Map<String, MapListRequirementDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CALCULATED_REQUIREMENTS); - if (result.isLeft()) { - ((TopologyTemplate) toscaElement).setCalculatedRequirements(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - result = getDataFromGraph(componentV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS); - if (result.isLeft()) { - ((TopologyTemplate) toscaElement).setFullfilledRequirements(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - return TitanOperationStatus.OK; - - } - - protected <T extends ToscaElement> TitanOperationStatus setCapabilitiesFromGraph(GraphVertex componentV, T toscaElement) { - Either<Map<String, MapListCapabiltyDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CALCULATED_CAPABILITIES); - if (result.isLeft()) { - ((TopologyTemplate) toscaElement).setCalculatedCapabilities(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - result = getDataFromGraph(componentV, EdgeLabelEnum.FULLFILLED_CAPABILITIES); - if (result.isLeft()) { - ((TopologyTemplate) toscaElement).setFullfilledCapabilities(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - return TitanOperationStatus.OK; - } - - private TitanOperationStatus setAllArtifactsFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) { - TitanOperationStatus storageStatus = setArtifactsFromGraph(componentV, toscaElement); - if (storageStatus != TitanOperationStatus.OK) { - return storageStatus; - } - Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.SERVICE_API_ARTIFACTS); - if (result.isLeft()) { - toscaElement.setServiceApiArtifacts(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - Either<Map<String, MapArtifactDataDefinition>, TitanOperationStatus> resultInstArt = getDataFromGraph(componentV, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS); - if (resultInstArt.isLeft()) { - toscaElement.setInstDeploymentArtifacts(resultInstArt.left().value()); - } else { - if (resultInstArt.right().value() != TitanOperationStatus.NOT_FOUND) { - return resultInstArt.right().value(); - } - } - Either<Map<String, MapArtifactDataDefinition>, TitanOperationStatus> instanceArt = getDataFromGraph(componentV, EdgeLabelEnum.INSTANCE_ARTIFACTS); - if (instanceArt.isLeft()) { - toscaElement.setInstanceArtifacts(instanceArt.left().value()); - } else { - if (instanceArt.right().value() != TitanOperationStatus.NOT_FOUND) { - return instanceArt.right().value(); - } - } - return TitanOperationStatus.OK; - } - - private TitanOperationStatus setInputsFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) { - Either<Map<String, PropertyDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INPUTS); - if (result.isLeft()) { - toscaElement.setInputs(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - return TitanOperationStatus.OK; - } - - private TitanOperationStatus setGroupsFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) { - Either<Map<String, GroupDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.GROUPS); - if (result.isLeft()) { - toscaElement.setGroups(result.left().value()); - } else { - if (result.right().value() != TitanOperationStatus.NOT_FOUND) { - return result.right().value(); - } - } - return TitanOperationStatus.OK; - } - - private TitanOperationStatus setTopologyTempalteCategoriesFromGraph(GraphVertex componentV, ToscaElement toscaElement) { - List<CategoryDefinition> categories = new ArrayList<>(); - - switch (componentV.getType()) { - case RESOURCE: - return setResourceCategoryFromGraph(componentV, toscaElement); - case SERVICE: - return setServiceCategoryFromGraph(componentV, toscaElement, categories); - - default: - log.debug("Not supported component type {} ", componentV.getType()); - break; - } - return TitanOperationStatus.OK; - } - - private TitanOperationStatus setServiceCategoryFromGraph(GraphVertex componentV, ToscaElement toscaElement, List<CategoryDefinition> categories) { - 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 categoryV = childVertex.left().value(); - Map<GraphPropertyEnum, Object> 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.getProperty()), listTypeCat); - category.setIcons(iconsfromJsonCat); - categories.add(category); - toscaElement.setCategories(categories); - - return TitanOperationStatus.OK; - } - - @SuppressWarnings("unchecked") - private TopologyTemplate convertToTopologyTemplate(GraphVertex componentV) { - - TopologyTemplate topologyTemplate = super.convertToComponent(componentV); - - Map<String, CompositionDataDefinition> json = (Map<String, CompositionDataDefinition>) componentV.getJson(); - topologyTemplate.setCompositions(json); - - return topologyTemplate; - } - - @Override - public Either<ToscaElement, StorageOperationStatus> deleteToscaElement(GraphVertex toscaElementVertex) { - Either<ToscaElement, StorageOperationStatus> nodeType = getToscaElement(toscaElementVertex, new ComponentParametersView()); - if (nodeType.isRight()) { - log.debug("Failed to fetch tosca element {} error {}", toscaElementVertex.getUniqueId(), nodeType.right().value()); - return nodeType; - } - TitanOperationStatus status = disassociateAndDeleteCommonElements(toscaElementVertex); - if (status != TitanOperationStatus.OK) { - Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_ATTRIBUTES); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate instances attributes for {} error {}", toscaElementVertex.getUniqueId(), status); - Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_PROPERTIES); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate instances properties for {} error {}", toscaElementVertex.getUniqueId(), status); - Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_INPUTS); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate instances inputs for {} error {}", toscaElementVertex.getUniqueId(), status); - Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.GROUPS); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate groups for {} error {}", toscaElementVertex.getUniqueId(), status); - Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_GROUPS); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate instance groups for {} error {}", toscaElementVertex.getUniqueId(), status); - Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INPUTS); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate inputs for {} error {}", toscaElementVertex.getUniqueId(), status); - Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_INPUTS); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate instance inputs for {} error {}", toscaElementVertex.getUniqueId(), status); - Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CALCULATED_CAPABILITIES); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate calculated capabiliites for {} error {}", toscaElementVertex.getUniqueId(), status); - Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.FULLFILLED_CAPABILITIES); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate fullfilled capabilities for {} error {}", toscaElementVertex.getUniqueId(), status); - Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate calculated capabiliites properties for {} error {}", toscaElementVertex.getUniqueId(), status); - Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CALCULATED_REQUIREMENTS); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate calculated requirements for {} error {}", toscaElementVertex.getUniqueId(), status); - Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.FULLFILLED_REQUIREMENTS); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate full filled requirements for {} error {}", toscaElementVertex.getUniqueId(), status); - Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate instance artifacts for {} error {}", toscaElementVertex.getUniqueId(), status); - Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.SERVICE_API_ARTIFACTS); - 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.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()); - - return nodeType; - } - - @SuppressWarnings("unchecked") - @Override - public Either<TopologyTemplate, StorageOperationStatus> createToscaElement(ToscaElement toscaElement) { - return createTopologyTemplate((TopologyTemplate) toscaElement); - } - - @Override - protected <T extends ToscaElement> TitanOperationStatus setCategoriesFromGraph(GraphVertex vertexComponent, T toscaElement) { - return setTopologyTempalteCategoriesFromGraph(vertexComponent, toscaElement); - } - - @Override - protected <T extends ToscaElement> StorageOperationStatus validateCategories(T toscaElementToUpdate, GraphVertex elementV) { - // Product isn't supported now!! - // TODO add for Product - if (toscaElementToUpdate.getComponentType() == ComponentTypeEnum.SERVICE) { - return validateServiceCategory(toscaElementToUpdate, elementV); - } else { - // Resource - return validateResourceCategory(toscaElementToUpdate, elementV); - } - } - - @Override - protected <T extends ToscaElement> StorageOperationStatus updateDerived(T toscaElementToUpdate, GraphVertex updateElementV) { - // not relevant now for topology template - return StorageOperationStatus.OK; - } - - @Override - public <T extends ToscaElement> void fillToscaElementVertexData(GraphVertex elementV, T toscaElementToUpdate, JsonParseFlagEnum flag) { - fillMetadata(elementV, (TopologyTemplate) toscaElementToUpdate, flag); - } - - private <T extends ToscaElement> StorageOperationStatus validateServiceCategory(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 categoryV = childVertex.left().value(); - Map<GraphPropertyEnum, Object> metadataProperties = categoryV.getMetadataProperties(); - String categoryNameCurrent = (String) metadataProperties.get(GraphPropertyEnum.NAME); - - String newCategoryName = newCategory.getName(); - if (newCategoryName != null && false == newCategoryName.equals(categoryNameCurrent)) { - // the category was changed - Either<GraphVertex, StorageOperationStatus> getCategoryVertex = categoryOperation.getCategory(newCategoryName, VertexTypeEnum.SERVICE_CATEGORY); - - 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 Either<List<GraphVertex>, TitanOperationStatus> getAllNotDeletedElements() { - Map<GraphPropertyEnum, Object> propsHasNot = new HashMap<>(); - propsHasNot.put(GraphPropertyEnum.IS_DELETED, true); - - Either<List<GraphVertex>, TitanOperationStatus> byCriteria = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, null, propsHasNot, JsonParseFlagEnum.ParseJson); - if (byCriteria.isRight()) { - log.debug("Failed to fetch all non marked topology templates , propsHasNot {}, error {}", propsHasNot, byCriteria.right().value()); - return Either.right(byCriteria.right().value()); - } - 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(); - if (composition != null) { - CompositionDataDefinition instances = composition.get(JsonConstantKeysEnum.COMPOSITION.getValue()); - if (instances != null && instances.getComponentInstances() != null && !instances.getComponentInstances().isEmpty()) { - for (ComponentInstanceDataDefinition ci : instances.getComponentInstances().values()) { - if (ci.getComponentUid().equals(elementV.getUniqueId())) { - log.debug("The resource {} failed to delete cause in use as component instance UniqueID = {} in {} with UniqueID {}", elementV.getUniqueId(), ci.getUniqueId(), containerV.getType(), containerV.getUniqueId()); - return true; - } - } - - } - } - } - - 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(); - if (composition != null) { - CompositionDataDefinition instances = composition.get(JsonConstantKeysEnum.COMPOSITION.getValue()); - if (instances != null && instances.getComponentInstances() != null && !instances.getComponentInstances().isEmpty()) { - for (ComponentInstanceDataDefinition ci : instances.getComponentInstances().values()) { - if (ci.getComponentUid().equals(componentId)) { - return true; - } - } - - } - } - } - - return false; - } - - public Either<GraphVertex, StorageOperationStatus> updateDistributionStatus(String uniqueId, User user, DistributionStatusEnum distributionStatus) { - - Either<GraphVertex, StorageOperationStatus> result = null; - String userId = user.getUserId(); - Either<GraphVertex, TitanOperationStatus> getRes = findUserVertex(userId); - GraphVertex userVertex = null; - GraphVertex serviceVertex = null; - if (getRes.isRight()) { - TitanOperationStatus status = getRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Cannot find user {} in the graph. status is {}", userId, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - if (result == null) { - userVertex = getRes.left().value(); - getRes = titanDao.getVertexById(uniqueId, JsonParseFlagEnum.ParseMetadata); - if (getRes.isRight()) { - TitanOperationStatus status = getRes.right().value(); - log.error("Cannot find service {} in the graph. status is {}", uniqueId, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - if (result == null) { - serviceVertex = getRes.left().value(); - Iterator<Edge> edgeIterator = serviceVertex.getVertex().edges(Direction.IN, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER.name()); - if (edgeIterator.hasNext()) { - log.debug("Remove existing edge from user to component {}. Edge type is {}", userId, uniqueId, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER); - edgeIterator.next().remove(); - } - } - if (result == null) { - TitanOperationStatus status = titanDao.createEdge(userVertex, serviceVertex, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER, null); - if (status != TitanOperationStatus.OK) { - log.error("Failed to associate user {} to component {}. Edge type is {}", userId, uniqueId, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - if (result == null) { - serviceVertex.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, distributionStatus.name()); - long lastUpdateDate = System.currentTimeMillis(); - serviceVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate); - Either<GraphVertex, TitanOperationStatus> updateRes = titanDao.updateVertex(serviceVertex); - if (updateRes.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateRes.right().value())); - } - } - if (result == null) { - result = Either.left(serviceVertex); - } - return result; - } - /** - * 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, String ownerId) { - - Either<List<ComponentInstanceProperty>, StorageOperationStatus> result = null; - Map<String, MapCapabiltyProperty> mapPropertiesDataDefinition = null; - Either<GraphVertex, StorageOperationStatus> componentByLabelAndId = getComponentByLabelAndId(componentId, ToscaElementTypeEnum.TopologyTemplate, JsonParseFlagEnum.NoParse); - if (componentByLabelAndId.isRight()) { - result = Either.right(componentByLabelAndId.right().value()); - } - if(componentByLabelAndId.isLeft()){ - Either<Map<String, MapCapabiltyProperty>, TitanOperationStatus> getDataRes = getDataFromGraph(componentByLabelAndId.left().value(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES); - if (getDataRes.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getDataRes.right().value())); - } else { - mapPropertiesDataDefinition = getDataRes.left().value(); - } - } - if(isNotEmptyMapOfProperties(instanceId, mapPropertiesDataDefinition)){ - result = Either.left(findComponentInstanceCapabilityProperties(instanceId, capabilityName, capabilityType, ownerId, mapPropertiesDataDefinition.get(instanceId).getMapToscaDataDefinition())); - } - 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, String ownerId, Map<String, MapPropertiesDataDefinition> propertiesMap) { - List<ComponentInstanceProperty> capPropsList = null; - for(Entry<String, MapPropertiesDataDefinition> capProp : propertiesMap.entrySet()){ - 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()); - break; - } - } - } - if(capPropsList == null){ - capPropsList = new ArrayList<>(); - } - return capPropsList; - } - - 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[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 static final Logger log = Logger.getLogger(TopologyTemplateOperation.class); + + @Autowired + private ArchiveOperation archiveOperation; + + public Either<TopologyTemplate, StorageOperationStatus> createTopologyTemplate(TopologyTemplate topologyTemplate) { + Either<TopologyTemplate, StorageOperationStatus> result = null; + + topologyTemplate.generateUUID(); + + topologyTemplate = getResourceMetaDataFromResource(topologyTemplate); + String resourceUniqueId = topologyTemplate.getUniqueId(); + if (resourceUniqueId == null) { + resourceUniqueId = UniqueIdBuilder.buildResourceUniqueId(); + topologyTemplate.setUniqueId(resourceUniqueId); + } + + GraphVertex topologyTemplateVertex = new GraphVertex(); + topologyTemplateVertex = fillMetadata(topologyTemplateVertex, topologyTemplate, JsonParseFlagEnum.ParseAll); + + Either<GraphVertex, TitanOperationStatus> createdVertex = titanDao.createVertex(topologyTemplateVertex); + if (createdVertex.isRight()) { + TitanOperationStatus status = createdVertex.right().value(); + log.debug( "Error returned after creating topology template data node {}. status returned is ", topologyTemplateVertex, status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + return result; + } + + topologyTemplateVertex = createdVertex.left().value(); + + StorageOperationStatus assosiateCommon = assosiateCommonForToscaElement(topologyTemplateVertex, topologyTemplate, null); + if (assosiateCommon != StorageOperationStatus.OK) { + result = Either.right(assosiateCommon); + return result; + } + + StorageOperationStatus associateCategory = assosiateMetadataToCategory(topologyTemplateVertex, topologyTemplate); + if (associateCategory != StorageOperationStatus.OK) { + result = Either.right(associateCategory); + return result; + } + + StorageOperationStatus associateInputs = associateInputsToComponent(topologyTemplateVertex, topologyTemplate); + if (associateInputs != StorageOperationStatus.OK) { + result = Either.right(associateInputs); + return result; + } + StorageOperationStatus associateGroups = associateGroupsToComponent(topologyTemplateVertex, topologyTemplate); + if (associateGroups != StorageOperationStatus.OK) { + 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); + return result; + } + StorageOperationStatus associateInstProperties = associateInstPropertiesToComponent(topologyTemplateVertex, topologyTemplate); + if (associateInstProperties != StorageOperationStatus.OK) { + result = Either.right(associateInstProperties); + return result; + } + StorageOperationStatus associateInstInputs = associateInstInputsToComponent(topologyTemplateVertex, topologyTemplate); + if (associateInstProperties != StorageOperationStatus.OK) { + result = Either.right(associateInstInputs); + return result; + } + StorageOperationStatus associateInstGroups = associateInstGroupsToComponent(topologyTemplateVertex, topologyTemplate); + if (associateInstGroups != StorageOperationStatus.OK) { + result = Either.right(associateInstInputs); + return result; + } + + StorageOperationStatus associateRequirements = associateRequirementsToResource(topologyTemplateVertex, topologyTemplate); + if (associateRequirements != StorageOperationStatus.OK) { + result = Either.right(associateRequirements); + return result; + } + + StorageOperationStatus associateCapabilities = associateCapabilitiesToResource(topologyTemplateVertex, topologyTemplate); + if (associateCapabilities != StorageOperationStatus.OK) { + result = Either.right(associateCapabilities); + return result; + } + + StorageOperationStatus associateArtifacts = associateTopologyTemplateArtifactsToComponent(topologyTemplateVertex, topologyTemplate); + if (associateArtifacts != StorageOperationStatus.OK) { + result = Either.right(associateArtifacts); + return result; + } + + StorageOperationStatus addAdditionalInformation = addAdditionalInformationToResource(topologyTemplateVertex, topologyTemplate); + if (addAdditionalInformation != StorageOperationStatus.OK) { + result = Either.right(addAdditionalInformation); + return result; + } + StorageOperationStatus associateCapProperties = associateCapPropertiesToResource(topologyTemplateVertex, topologyTemplate); + if (associateCapProperties != StorageOperationStatus.OK) { + 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 = associateElementToData(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, MapCapabilityProperty> calculatedCapProperties = topologyTemplate.getCalculatedCapabilitiesProperties(); + if (calculatedCapProperties != null && !calculatedCapProperties.isEmpty()) { + Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(topologyTemplateVertex, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, calculatedCapProperties); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + private StorageOperationStatus associateCapabilitiesToResource(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { + Map<String, MapListCapabilityDataDefinition> calculatedCapabilities = topologyTemplate.getCalculatedCapabilities(); + if (calculatedCapabilities != null && !calculatedCapabilities.isEmpty()) { + Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_CAPABILITIES, EdgeLabelEnum.CALCULATED_CAPABILITIES, calculatedCapabilities); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + Map<String, MapListCapabilityDataDefinition> fullfilledCapabilities = topologyTemplate.getFullfilledCapabilities(); + if (fullfilledCapabilities != null && !fullfilledCapabilities.isEmpty()) { + Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.FULLFILLED_CAPABILITIES, EdgeLabelEnum.FULLFILLED_CAPABILITIES, fullfilledCapabilities); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + + } + + private StorageOperationStatus associateRequirementsToResource(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { + Map<String, MapListRequirementDataDefinition> calculatedRequirements = topologyTemplate.getCalculatedRequirements(); + if (calculatedRequirements != null && !calculatedRequirements.isEmpty()) { + Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_REQUIREMENTS, EdgeLabelEnum.CALCULATED_REQUIREMENTS, calculatedRequirements); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + Map<String, MapListRequirementDataDefinition> fullfilledRequirements = topologyTemplate.getFullfilledRequirements(); + if (fullfilledRequirements != null && !fullfilledRequirements.isEmpty()) { + Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.FULLFILLED_REQUIREMENTS, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, fullfilledRequirements); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + private StorageOperationStatus associateTopologyTemplateArtifactsToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { + Map<String, ArtifactDataDefinition> addInformation = topologyTemplate.getServiceApiArtifacts(); + + if (addInformation != null && !addInformation.isEmpty()) { + addInformation.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> { + String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase()); + a.setUniqueId(uniqueId); + }); + Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.SERVICE_API_ARTIFACTS, EdgeLabelEnum.SERVICE_API_ARTIFACTS, addInformation); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + Map<String, MapArtifactDataDefinition> instArtifacts = topologyTemplate.getInstDeploymentArtifacts(); + + if (instArtifacts != null && !instArtifacts.isEmpty()) { + Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, instArtifacts); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + Map<String, MapArtifactDataDefinition> instInfoArtifacts = topologyTemplate.getInstanceArtifacts(); + + if (instInfoArtifacts != null && !instInfoArtifacts.isEmpty()) { + Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INSTANCE_ARTIFACTS, EdgeLabelEnum.INSTANCE_ARTIFACTS, instInfoArtifacts); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + private StorageOperationStatus addAdditionalInformationToResource(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { + + Map<String, AdditionalInfoParameterDataDefinition> addInformation = topologyTemplate.getAdditionalInformation(); + + if (addInformation != null && !addInformation.isEmpty()) { + Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.ADDITIONAL_INFORMATION, EdgeLabelEnum.ADDITIONAL_INFORMATION, addInformation); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + public StorageOperationStatus associateInstPropertiesToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { + Map<String, MapPropertiesDataDefinition> instProps = topologyTemplate.getInstProperties(); + return associateInstPropertiesToComponent(nodeTypeVertex, instProps); + } + + public StorageOperationStatus associateInstInputsToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { + Map<String, MapPropertiesDataDefinition> instProps = topologyTemplate.getInstInputs(); + return associateInstInputsToComponent(nodeTypeVertex, instProps); + } + + public StorageOperationStatus associateInstGroupsToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { + Map<String, MapGroupsDataDefinition> instGroups = topologyTemplate.getInstGroups(); + return associateInstGroupsToComponent(nodeTypeVertex, instGroups); + } + + + public StorageOperationStatus associateInstPropertiesToComponent(GraphVertex nodeTypeVertex, Map<String, MapPropertiesDataDefinition> instProps) { + if (instProps != null && !instProps.isEmpty()) { + Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INST_PROPERTIES, EdgeLabelEnum.INST_PROPERTIES, instProps); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + public StorageOperationStatus associateInstInputsToComponent(GraphVertex nodeTypeVertex, Map<String, MapPropertiesDataDefinition> instInputs) { + if (instInputs != null && !instInputs.isEmpty()) { + Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INST_INPUTS, EdgeLabelEnum.INST_INPUTS, instInputs); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + public StorageOperationStatus associateInstGroupsToComponent(GraphVertex nodeTypeVertex, Map<String, MapGroupsDataDefinition> instGroups) { + if (instGroups != null && !instGroups.isEmpty()) { + Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INST_GROUPS, EdgeLabelEnum.INST_GROUPS, instGroups); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + + public StorageOperationStatus deleteInstInputsToComponent(GraphVertex nodeTypeVertex, Map<String, MapPropertiesDataDefinition> instInputs) { + + if (instInputs != null && !instInputs.isEmpty()) { + instInputs.entrySet().forEach(i -> { + List<String> uniqueKeys = new ArrayList<>(i.getValue().getMapToscaDataDefinition().keySet()); + List<String> pathKeys = new ArrayList<>(); + pathKeys.add(i.getKey()); + + StorageOperationStatus status = deleteToscaDataDeepElements(nodeTypeVertex, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, uniqueKeys, pathKeys, JsonPresentationFields.NAME); + if (status != StorageOperationStatus.OK) { + return; + } + }); + } + + return StorageOperationStatus.OK; + } + + public StorageOperationStatus addInstPropertiesToComponent(GraphVertex nodeTypeVertex, Map<String, MapPropertiesDataDefinition> instInputs) { + + if (instInputs != null && !instInputs.isEmpty()) { + instInputs.entrySet().forEach(i -> { + StorageOperationStatus status = addToscaDataDeepElementsBlockToToscaElement(nodeTypeVertex, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, i.getValue(), i.getKey()); + if (status != StorageOperationStatus.OK) { + return; + } + }); + } + + return StorageOperationStatus.OK; + } + + public StorageOperationStatus associateInstDeploymentArtifactsToComponent(GraphVertex nodeTypeVertex, Map<String, MapArtifactDataDefinition> instArtifacts) { + return associateInstanceArtifactsToComponent(nodeTypeVertex, instArtifacts, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS); + } + + public StorageOperationStatus associateInstArtifactsToComponent(GraphVertex nodeTypeVertex, Map<String, MapArtifactDataDefinition> instArtifacts) { + return associateInstanceArtifactsToComponent(nodeTypeVertex, instArtifacts, VertexTypeEnum.INSTANCE_ARTIFACTS, EdgeLabelEnum.INSTANCE_ARTIFACTS); + } + + private StorageOperationStatus associateInstanceArtifactsToComponent(GraphVertex nodeTypeVertex, Map<String, MapArtifactDataDefinition> instProps, VertexTypeEnum vertexType, EdgeLabelEnum edgeLabel) { + if (instProps != null && !instProps.isEmpty()) { + Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, vertexType, edgeLabel, instProps); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + public StorageOperationStatus associateOrAddCalcCapReqToComponent(GraphVertex nodeTypeVertex, Map<String, MapListRequirementDataDefinition> calcRequirements, Map<String, MapListCapabilityDataDefinition> calcCapabilty, Map<String, MapCapabilityProperty> calculatedCapabilitiesProperties) { + if (calcRequirements != null && !calcRequirements.isEmpty()) { + Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_REQUIREMENTS, EdgeLabelEnum.CALCULATED_REQUIREMENTS, calcRequirements); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + Map<String, MapListRequirementDataDefinition> fullFilled = new HashMap<>(); + assosiateElementToData = associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.FULLFILLED_REQUIREMENTS, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, fullFilled); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + if (calcCapabilty != null && !calcCapabilty.isEmpty()) { + Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_CAPABILITIES ,EdgeLabelEnum.CALCULATED_CAPABILITIES, calcCapabilty); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + Map<String, MapListCapabilityDataDefinition> fullFilled = new HashMap<>(); + assosiateElementToData = associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.FULLFILLED_CAPABILITIES, EdgeLabelEnum.FULLFILLED_CAPABILITIES, fullFilled); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + if ( calculatedCapabilitiesProperties != null && !calculatedCapabilitiesProperties.isEmpty() ){ + return associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, + EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, calculatedCapabilitiesProperties) + .right() + .on(v -> StorageOperationStatus.OK); + } + return StorageOperationStatus.OK; + } + + private <T extends MapDataDefinition> Either<GraphVertex, StorageOperationStatus> associateOrAddElementToData(GraphVertex nodeTypeVertex, VertexTypeEnum vertexTypeEnum, EdgeLabelEnum edgeLabelEnum, Map<String, T> dataMap){ + return titanDao.getChildVertex(nodeTypeVertex, edgeLabelEnum, JsonParseFlagEnum.ParseJson) + .either(dataVertex -> addElementsToComponent(nodeTypeVertex, dataVertex, vertexTypeEnum, edgeLabelEnum, dataMap), + status -> associateElementToDataIfNotFound(status, nodeTypeVertex, vertexTypeEnum, edgeLabelEnum, dataMap)); + } + + private Either<GraphVertex, StorageOperationStatus> associateElementToDataIfNotFound(TitanOperationStatus status, GraphVertex nodeTypeVertex, VertexTypeEnum vertexTypeEnum, EdgeLabelEnum edgeLabelEnum, Map<String, ? extends ToscaDataDefinition> dataMap) { + if(status == TitanOperationStatus.NOT_FOUND){ + return associateElementToData(nodeTypeVertex, vertexTypeEnum, edgeLabelEnum, dataMap); + } + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + + private <T extends MapDataDefinition> Either<GraphVertex, StorageOperationStatus> addElementsToComponent(GraphVertex nodeTypeVertex, GraphVertex dataVertex, VertexTypeEnum vertexTypeEnum, EdgeLabelEnum edgeLabelEnum, Map<String, T> dataMap) { + Optional<StorageOperationStatus> error = dataMap.entrySet() + .stream() + .map(e -> addElementToComponent(nodeTypeVertex.getUniqueId(), vertexTypeEnum, edgeLabelEnum, e)) + .filter(s -> s != StorageOperationStatus.OK) + .findFirst(); + if(error.isPresent()){ + return Either.right(error.get()); + } + return Either.left(dataVertex); + } + + private StorageOperationStatus associateInstAttributesToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { + Map<String, MapPropertiesDataDefinition> instAttr = topologyTemplate.getInstAttributes(); + return associateInstAttributeToComponent(nodeTypeVertex, instAttr); + } + + public StorageOperationStatus associateForwardingPathToComponent(GraphVertex nodeTypeVertex, Map<String, ForwardingPathDataDefinition> forwardingPathMap) { + if (forwardingPathMap != null && !forwardingPathMap.isEmpty()) { + Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(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 = associateElementToData(nodeTypeVertex, VertexTypeEnum.INST_ATTRIBUTES, EdgeLabelEnum.INST_ATTRIBUTES, instAttr); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + public StorageOperationStatus associateGroupsToComponent(GraphVertex nodeTypeVertex, Map<String, GroupDataDefinition> groups) { + + if (groups != null && !groups.isEmpty()) { + groups.values().stream().filter(p -> p.getUniqueId() == null).forEach(p -> { + String uid = UniqueIdBuilder.buildGroupingUid(nodeTypeVertex.getUniqueId(), p.getName()); + p.setUniqueId(uid); + }); + Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.GROUPS, EdgeLabelEnum.GROUPS, groups); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + private StorageOperationStatus associateGroupsToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { + return associateGroupsToComponent(nodeTypeVertex, topologyTemplate.getGroups()); + } + + public StorageOperationStatus associateInputsToComponent(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { + Map<String, PropertyDataDefinition> inputs = topologyTemplate.getInputs(); + return associateInputsToComponent(nodeTypeVertex, inputs, topologyTemplate.getUniqueId()); + } + + public StorageOperationStatus associateInputsToComponent(GraphVertex nodeTypeVertex, Map<String, PropertyDataDefinition> inputs, String id) { + if (inputs != null && !inputs.isEmpty()) { + inputs.values().stream().filter(e -> e.getUniqueId() == null).forEach(e -> e.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(id, e.getName()))); + + Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.INPUTS, EdgeLabelEnum.INPUTS, inputs); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + private GraphVertex fillMetadata(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate, JsonParseFlagEnum flag) { + nodeTypeVertex.setLabel(VertexTypeEnum.TOPOLOGY_TEMPLATE); + fillCommonMetadata(nodeTypeVertex, topologyTemplate); + if (flag == JsonParseFlagEnum.ParseAll || flag == JsonParseFlagEnum.ParseJson) { + nodeTypeVertex.setJson(topologyTemplate.getCompositions()); + } + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.CSAR_UUID, topologyTemplate.getMetadataValue(JsonPresentationFields.CSAR_UUID)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, topologyTemplate.getMetadataValue(JsonPresentationFields.DISTRIBUTION_STATUS)); + + return nodeTypeVertex; + + } + + private StorageOperationStatus assosiateMetadataToCategory(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { + if (topologyTemplate.getResourceType() == null) { + // service + return associateServiceMetadataToCategory(nodeTypeVertex, topologyTemplate); + } else { + // VF + return assosiateResourceMetadataToCategory(nodeTypeVertex, topologyTemplate); + } + } + + private StorageOperationStatus associateServiceMetadataToCategory(GraphVertex nodeTypeVertex, TopologyTemplate topologyTemplate) { + String categoryName = topologyTemplate.getCategories().get(0).getName(); + Either<GraphVertex, StorageOperationStatus> category = categoryOperation.getCategory(categoryName, VertexTypeEnum.SERVICE_CATEGORY); + if (category.isRight()) { + log.trace("NO category {} for service {}", categoryName, topologyTemplate.getUniqueId()); + return StorageOperationStatus.CATEGORY_NOT_FOUND; + } + GraphVertex categoryV = category.left().value(); + TitanOperationStatus createEdge = titanDao.createEdge(nodeTypeVertex, categoryV, EdgeLabelEnum.CATEGORY, new HashMap<>()); + if (createEdge != TitanOperationStatus.OK) { + log.trace("Failed to associate resource {} to category {} with id {}", topologyTemplate.getUniqueId(), categoryName, categoryV.getUniqueId()); + return DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge); + } + return StorageOperationStatus.OK; + } + + @Override + public Either<ToscaElement, StorageOperationStatus> getToscaElement(String uniqueId, ComponentParametersView componentParametersView) { + JsonParseFlagEnum parseFlag = componentParametersView.detectParseFlag(); + + Either<GraphVertex, StorageOperationStatus> componentByLabelAndId = getComponentByLabelAndId(uniqueId, ToscaElementTypeEnum.TOPOLOGY_TEMPLATE, parseFlag); + if (componentByLabelAndId.isRight()) { + return Either.right(componentByLabelAndId.right().value()); + } + GraphVertex componentV = componentByLabelAndId.left().value(); + + return getToscaElement(componentV, componentParametersView); + + } + // ------------------------------------------------------------- + + public Either<ToscaElement, StorageOperationStatus> getToscaElement(GraphVertex componentV, ComponentParametersView componentParametersView) { + TopologyTemplate toscaElement; + + toscaElement = convertToTopologyTemplate(componentV); + TitanOperationStatus status; + if (!componentParametersView.isIgnoreUsers()) { + status = setCreatorFromGraph(componentV, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + + status = setLastModifierFromGraph(componentV, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + } + if (!componentParametersView.isIgnoreCategories()) { + status = setTopologyTempalteCategoriesFromGraph(componentV, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + + } + } + if (!componentParametersView.isIgnoreArtifacts()) { + TitanOperationStatus storageStatus = setAllArtifactsFromGraph(componentV, toscaElement); + if (storageStatus != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(storageStatus)); + } + } + if (!componentParametersView.isIgnoreComponentInstancesProperties()) { + status = setComponentInstancesPropertiesFromGraph(componentV, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + } + if (!componentParametersView.isIgnoreCapabilities()) { + status = setCapabilitiesFromGraph(componentV, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + } + if (!componentParametersView.isIgnoreRequirements()) { + status = setRequirementsFromGraph(componentV, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + } + if (!componentParametersView.isIgnoreAllVersions()) { + status = setAllVersions(componentV, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + } + if (!componentParametersView.isIgnoreAdditionalInformation()) { + status = setAdditionalInformationFromGraph(componentV, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + } + + if (!componentParametersView.isIgnoreGroups()) { + status = setGroupsFromGraph(componentV, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + + } + if (!componentParametersView.isIgnorePolicies()) { + status = setPoliciesFromGraph(componentV, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + + } + if (!componentParametersView.isIgnoreComponentInstances()) { + status = setInstGroupsFromGraph(componentV, toscaElement); + + //Mark all CIs that has archived origins + archiveOperation.setArchivedOriginsFlagInComponentInstances(componentV); + + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + + } + if (!componentParametersView.isIgnoreInputs()) { + status = setInputsFromGraph(componentV, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + + } + if (!componentParametersView.isIgnoreProperties()) { + status = setPropertiesFromGraph(componentV, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + + } + + if (!componentParametersView.isIgnoreComponentInstancesInputs()) { + status = setComponentInstancesInputsFromGraph(componentV, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + + } + } + + 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, MapCapabilityProperty>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES); + if (result.isLeft()) { + topologyTemplate.setCalculatedCapabilitiesProperties(result.left().value()); + } else { + if (result.right().value() != TitanOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return TitanOperationStatus.OK; + } + + private TitanOperationStatus setPropertiesFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) { + Either<Map<String, PropertyDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.PROPERTIES); + if (result.isLeft()) { + toscaElement.setProperties(result.left().value()); + } else { + if (result.right().value() != TitanOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return TitanOperationStatus.OK; + } + + private TitanOperationStatus setInstGroupsFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) { + Either<Map<String, MapGroupsDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INST_GROUPS); + if (result.isLeft()) { + topologyTemplate.setInstGroups(result.left().value()); + } else { + if (result.right().value() != TitanOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return TitanOperationStatus.OK; + } + + private TitanOperationStatus setComponentInstancesPropertiesFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) { + Either<Map<String, MapPropertiesDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INST_PROPERTIES); + if (result.isLeft()) { + topologyTemplate.setInstProperties(result.left().value()); + } else { + if (result.right().value() != TitanOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return TitanOperationStatus.OK; + } + + private TitanOperationStatus setComponentInstancesInputsFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) { + Either<Map<String, MapPropertiesDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INST_INPUTS); + if (result.isLeft()) { + topologyTemplate.setInstInputs(result.left().value()); + } else { + if (result.right().value() != TitanOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return TitanOperationStatus.OK; + } + + @Override + protected <T extends ToscaElement> TitanOperationStatus setRequirementsFromGraph(GraphVertex componentV, T toscaElement) { + Either<Map<String, MapListRequirementDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CALCULATED_REQUIREMENTS); + if (result.isLeft()) { + ((TopologyTemplate) toscaElement).setCalculatedRequirements(result.left().value()); + } else { + if (result.right().value() != TitanOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + result = getDataFromGraph(componentV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS); + if (result.isLeft()) { + ((TopologyTemplate) toscaElement).setFullfilledRequirements(result.left().value()); + } else { + if (result.right().value() != TitanOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return TitanOperationStatus.OK; + + } + + protected <T extends ToscaElement> TitanOperationStatus setCapabilitiesFromGraph(GraphVertex componentV, T toscaElement) { + Either<Map<String, MapListCapabilityDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.CALCULATED_CAPABILITIES); + if (result.isLeft()) { + ((TopologyTemplate) toscaElement).setCalculatedCapabilities(result.left().value()); + } else { + if (result.right().value() != TitanOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + result = getDataFromGraph(componentV, EdgeLabelEnum.FULLFILLED_CAPABILITIES); + if (result.isLeft()) { + ((TopologyTemplate) toscaElement).setFullfilledCapabilities(result.left().value()); + } else { + if (result.right().value() != TitanOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return TitanOperationStatus.OK; + } + + private TitanOperationStatus setAllArtifactsFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) { + TitanOperationStatus storageStatus = setArtifactsFromGraph(componentV, toscaElement); + if (storageStatus != TitanOperationStatus.OK) { + return storageStatus; + } + Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.SERVICE_API_ARTIFACTS); + if (result.isLeft()) { + toscaElement.setServiceApiArtifacts(result.left().value()); + } else { + if (result.right().value() != TitanOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + Either<Map<String, MapArtifactDataDefinition>, TitanOperationStatus> resultInstArt = getDataFromGraph(componentV, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS); + if (resultInstArt.isLeft()) { + toscaElement.setInstDeploymentArtifacts(resultInstArt.left().value()); + } else { + if (resultInstArt.right().value() != TitanOperationStatus.NOT_FOUND) { + return resultInstArt.right().value(); + } + } + Either<Map<String, MapArtifactDataDefinition>, TitanOperationStatus> instanceArt = getDataFromGraph(componentV, EdgeLabelEnum.INSTANCE_ARTIFACTS); + if (instanceArt.isLeft()) { + toscaElement.setInstanceArtifacts(instanceArt.left().value()); + } else { + if (instanceArt.right().value() != TitanOperationStatus.NOT_FOUND) { + return instanceArt.right().value(); + } + } + return TitanOperationStatus.OK; + } + + private TitanOperationStatus setInputsFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) { + Either<Map<String, PropertyDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INPUTS); + if (result.isLeft()) { + toscaElement.setInputs(result.left().value()); + } else { + if (result.right().value() != TitanOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return TitanOperationStatus.OK; + } + + private TitanOperationStatus setGroupsFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) { + Either<Map<String, GroupDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.GROUPS); + if (result.isLeft()) { + toscaElement.setGroups(result.left().value()); + } else { + if (result.right().value() != TitanOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return TitanOperationStatus.OK; + } + + private TitanOperationStatus setTopologyTempalteCategoriesFromGraph(GraphVertex componentV, ToscaElement toscaElement) { + List<CategoryDefinition> categories = new ArrayList<>(); + + switch (componentV.getType()) { + case RESOURCE: + return setResourceCategoryFromGraph(componentV, toscaElement); + case SERVICE: + return setServiceCategoryFromGraph(componentV, toscaElement, categories); + + default: + log.debug("Not supported component type {} ", componentV.getType()); + break; + } + return TitanOperationStatus.OK; + } + + private TitanOperationStatus setServiceCategoryFromGraph(GraphVertex componentV, ToscaElement toscaElement, List<CategoryDefinition> categories) { + 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 categoryV = childVertex.left().value(); + Map<GraphPropertyEnum, Object> 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.getProperty()), listTypeCat); + category.setIcons(iconsfromJsonCat); + categories.add(category); + toscaElement.setCategories(categories); + + return TitanOperationStatus.OK; + } + + @SuppressWarnings("unchecked") + private TopologyTemplate convertToTopologyTemplate(GraphVertex componentV) { + + TopologyTemplate topologyTemplate = super.convertToComponent(componentV); + + Map<String, CompositionDataDefinition> json = (Map<String, CompositionDataDefinition>) componentV.getJson(); + topologyTemplate.setCompositions(json); + + return topologyTemplate; + } + + @Override + public Either<ToscaElement, StorageOperationStatus> deleteToscaElement(GraphVertex toscaElementVertex) { + Either<ToscaElement, StorageOperationStatus> nodeType = getToscaElement(toscaElementVertex, new ComponentParametersView()); + if (nodeType.isRight()) { + log.debug("Failed to fetch tosca element {} error {}", toscaElementVertex.getUniqueId(), nodeType.right().value()); + return nodeType; + } + TitanOperationStatus status = disassociateAndDeleteCommonElements(toscaElementVertex); + if (status != TitanOperationStatus.OK) { + Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_ATTRIBUTES); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to disassociate instances attributes for {} error {}", toscaElementVertex.getUniqueId(), status); + Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_PROPERTIES); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to disassociate instances properties for {} error {}", toscaElementVertex.getUniqueId(), status); + Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + + status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_INPUTS); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to disassociate instances inputs for {} error {}", toscaElementVertex.getUniqueId(), status); + Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + + status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.GROUPS); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to disassociate groups for {} error {}", toscaElementVertex.getUniqueId(), status); + Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_GROUPS); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to disassociate instance groups for {} error {}", toscaElementVertex.getUniqueId(), status); + Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INPUTS); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to disassociate inputs for {} error {}", toscaElementVertex.getUniqueId(), status); + Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_INPUTS); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to disassociate instance inputs for {} error {}", toscaElementVertex.getUniqueId(), status); + Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CALCULATED_CAPABILITIES); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to disassociate calculated capabiliites for {} error {}", toscaElementVertex.getUniqueId(), status); + Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.FULLFILLED_CAPABILITIES); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to disassociate fullfilled capabilities for {} error {}", toscaElementVertex.getUniqueId(), status); + Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to disassociate calculated capabiliites properties for {} error {}", toscaElementVertex.getUniqueId(), status); + Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CALCULATED_REQUIREMENTS); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to disassociate calculated requirements for {} error {}", toscaElementVertex.getUniqueId(), status); + Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.FULLFILLED_REQUIREMENTS); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to disassociate full filled requirements for {} error {}", toscaElementVertex.getUniqueId(), status); + Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to disassociate instance artifacts for {} error {}", toscaElementVertex.getUniqueId(), status); + Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.SERVICE_API_ARTIFACTS); + 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.FORWARDING_PATH); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to disassociate service api artifacts for {} error {}", toscaElementVertex.getUniqueId(), status); + Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + + titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INSTANCE_ARTIFACTS); + toscaElementVertex.getVertex().remove(); + log.trace("Tosca element vertex for {} was removed", toscaElementVertex.getUniqueId()); + + return nodeType; + } + + @SuppressWarnings("unchecked") + @Override + public Either<TopologyTemplate, StorageOperationStatus> createToscaElement(ToscaElement toscaElement) { + return createTopologyTemplate((TopologyTemplate) toscaElement); + } + + @Override + protected <T extends ToscaElement> TitanOperationStatus setCategoriesFromGraph(GraphVertex vertexComponent, T toscaElement) { + return setTopologyTempalteCategoriesFromGraph(vertexComponent, toscaElement); + } + + @Override + protected <T extends ToscaElement> StorageOperationStatus validateCategories(T toscaElementToUpdate, GraphVertex elementV) { + // Product isn't supported now!! + // TODO add for Product + if (toscaElementToUpdate.getComponentType() == ComponentTypeEnum.SERVICE) { + return validateServiceCategory(toscaElementToUpdate, elementV); + } else { + // Resource + return validateResourceCategory(toscaElementToUpdate, elementV); + } + } + + @Override + protected <T extends ToscaElement> StorageOperationStatus updateDerived(T toscaElementToUpdate, GraphVertex updateElementV) { + // not relevant now for topology template + return StorageOperationStatus.OK; + } + + @Override + public <T extends ToscaElement> void fillToscaElementVertexData(GraphVertex elementV, T toscaElementToUpdate, JsonParseFlagEnum flag) { + fillMetadata(elementV, (TopologyTemplate) toscaElementToUpdate, flag); + } + + private <T extends ToscaElement> StorageOperationStatus validateServiceCategory(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 categoryV = childVertex.left().value(); + Map<GraphPropertyEnum, Object> metadataProperties = categoryV.getMetadataProperties(); + String categoryNameCurrent = (String) metadataProperties.get(GraphPropertyEnum.NAME); + + String newCategoryName = newCategory.getName(); + if (newCategoryName != null && !newCategoryName.equals(categoryNameCurrent)) { + // the category was changed + Either<GraphVertex, StorageOperationStatus> getCategoryVertex = categoryOperation.getCategory(newCategoryName, VertexTypeEnum.SERVICE_CATEGORY); + + 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 Either<GraphVertex, StorageOperationStatus> updateDistributionStatus(String uniqueId, User user, DistributionStatusEnum distributionStatus) { + + Either<GraphVertex, StorageOperationStatus> result = null; + String userId = user.getUserId(); + Either<GraphVertex, TitanOperationStatus> getRes = findUserVertex(userId); + GraphVertex userVertex = null; + GraphVertex serviceVertex = null; + if (getRes.isRight()) { + TitanOperationStatus status = getRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Cannot find user {} in the graph. status is {}", userId, status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + if (result == null) { + userVertex = getRes.left().value(); + getRes = titanDao.getVertexById(uniqueId, JsonParseFlagEnum.ParseMetadata); + if (getRes.isRight()) { + TitanOperationStatus status = getRes.right().value(); + log.debug( "Cannot find service {} in the graph. status is {}", uniqueId, status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + } + if (result == null) { + serviceVertex = getRes.left().value(); + Iterator<Edge> edgeIterator = serviceVertex.getVertex().edges(Direction.IN, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER.name()); + if (edgeIterator.hasNext()) { + log.debug("Remove existing edge from user to component {}. Edge type is {}", userId, uniqueId, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER); + edgeIterator.next().remove(); + } + } + if (result == null) { + TitanOperationStatus status = titanDao.createEdge(userVertex, serviceVertex, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER, null); + if (status != TitanOperationStatus.OK) { + log.debug( "Failed to associate user {} to component {}. Edge type is {}", userId, uniqueId, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + } + if (result == null) { + serviceVertex.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, distributionStatus.name()); + long lastUpdateDate = System.currentTimeMillis(); + serviceVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate); + Either<GraphVertex, TitanOperationStatus> updateRes = titanDao.updateVertex(serviceVertex); + if (updateRes.isRight()) { + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateRes.right().value())); + } + } + if (result == null) { + result = Either.left(serviceVertex); + } + return result; + } + /** + * 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, String ownerId) { + + Either<List<ComponentInstanceProperty>, StorageOperationStatus> result = null; + Map<String, MapCapabilityProperty> mapPropertiesDataDefinition = null; + Either<GraphVertex, StorageOperationStatus> componentByLabelAndId = getComponentByLabelAndId(componentId, ToscaElementTypeEnum.TOPOLOGY_TEMPLATE, JsonParseFlagEnum.NoParse); + if (componentByLabelAndId.isRight()) { + result = Either.right(componentByLabelAndId.right().value()); + } + if(componentByLabelAndId.isLeft()){ + Either<Map<String, MapCapabilityProperty>, TitanOperationStatus> getDataRes = getDataFromGraph(componentByLabelAndId.left().value(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES); + if (getDataRes.isRight()) { + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getDataRes.right().value())); + } else { + mapPropertiesDataDefinition = getDataRes.left().value(); + } + } + if(isNotEmptyMapOfProperties(instanceId, mapPropertiesDataDefinition)){ + result = Either.left(findComponentInstanceCapabilityProperties(instanceId, capabilityName, capabilityType, ownerId, mapPropertiesDataDefinition.get(instanceId).getMapToscaDataDefinition())); + } + return result; + } + + public StorageOperationStatus updateComponentInstanceCapabilityProperties(Component containerComponent, String componentInstanceId, MapCapabilityProperty instanceProperties) { + return updateToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, instanceProperties, componentInstanceId); + } + + + private boolean isNotEmptyMapOfProperties(String instanceId, Map<String, MapCapabilityProperty> 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, String ownerId, Map<String, MapPropertiesDataDefinition> propertiesMap) { + List<ComponentInstanceProperty> capPropsList = null; + for(Entry<String, MapPropertiesDataDefinition> capProp : propertiesMap.entrySet()){ + if (isBelongingPropertyMap(instanceId, capabilityName, capabilityType, ownerId, capProp)) { + Map<String, PropertyDataDefinition> capMap = capProp.getValue().getMapToscaDataDefinition(); + if (capMap != null && !capMap.isEmpty()) { + capPropsList = capMap.values().stream().map(ComponentInstanceProperty::new).collect(Collectors.toList()); + break; + } + } + } + if(capPropsList == null){ + capPropsList = new ArrayList<>(); + } + return capPropsList; + } + + 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[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 addPoliciesToToscaElement(GraphVertex componentV, List<PolicyDefinition> policies) { + return addToscaDataToToscaElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policies, 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); + } + + public StorageOperationStatus updateGroupOfToscaElement(GraphVertex componentV, GroupDefinition groupDefinition) { + return updateToscaDataOfToscaElement(componentV, EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groupDefinition, JsonPresentationFields.NAME); } private void fillPolicyDefinition(GraphVertex componentV, PolicyDefinition policyDefinition, int counter) { @@ -1327,8 +1244,176 @@ public class TopologyTemplateOperation extends ToscaElementOperation { } public static String buildSubComponentName(String componentName, String subComponentTypeName, int counter) { + String normalizedComponentName = ValidationUtils.normalizeComponentInstanceName(componentName); String typeSuffix = subComponentTypeName.substring(subComponentTypeName.lastIndexOf('.') + 1, subComponentTypeName.length()); - return componentName + Constants.GROUP_POLICY_NAME_DELIMETER + typeSuffix + Constants.GROUP_POLICY_NAME_DELIMETER + counter; - } + return normalizedComponentName + Constants.GROUP_POLICY_NAME_DELIMETER + typeSuffix + Constants.GROUP_POLICY_NAME_DELIMETER + counter; + } + + void revertNamesOfCalculatedCapabilitiesRequirements(String componentId, TopologyTemplate toscaElement) { + if(MapUtils.isNotEmpty(toscaElement.getComponentInstances()) || MapUtils.isNotEmpty(toscaElement.getGroups())){ + GraphVertex toscaElementV = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse) + .left() + .on(this::throwStorageException); + if(MapUtils.isNotEmpty(toscaElement.getComponentInstances())){ + toscaElement.getComponentInstances().values().forEach(i -> revertNamesOfCalculatedCapabilitiesRequirements(toscaElement, i.getUniqueId())); + } + if(MapUtils.isNotEmpty(toscaElement.getGroups())){ + toscaElement.getGroups().values().forEach(g -> revertNamesOfCalculatedCapabilitiesRequirements(toscaElement, g.getUniqueId())); + } + topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, toscaElement.getCalculatedCapabilities()); + topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, toscaElement.getCalculatedRequirements()); + topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, toscaElement.getCalculatedCapabilitiesProperties()); + } + } + + public void updateNamesOfCalculatedCapabilitiesRequirements(String componentId, TopologyTemplate toscaElement) { + if(MapUtils.isNotEmpty(toscaElement.getComponentInstances()) || MapUtils.isNotEmpty(toscaElement.getGroups())){ + GraphVertex toscaElementV = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse) + .left() + .on(this::throwStorageException); + if(MapUtils.isNotEmpty(toscaElement.getComponentInstances())){ + toscaElement.getComponentInstances().values().forEach(i -> updateNamesOfCalculatedCapabilitiesRequirements(toscaElement, i.getUniqueId(), i.getNormalizedName())); + } + if(MapUtils.isNotEmpty(toscaElement.getGroups())){ + toscaElement.getGroups().values().forEach(g -> updateNamesOfCalculatedCapabilitiesRequirements(toscaElement, g.getUniqueId(), g.getName())); + } + topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, toscaElement.getCalculatedCapabilities()); + topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, toscaElement.getCalculatedRequirements()); + topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, toscaElement.getCalculatedCapabilitiesProperties()); + } + } + + private void updateNamesOfCalculatedCapabilitiesRequirements(TopologyTemplate toscaElement, String ownerId, String ownerName) { + updateCalculatedCapabilitiesNames(toscaElement, ownerId, ownerName); + updateCalculatedRequirementsNames(toscaElement, ownerId, ownerName); + updateCalculatedCapabilitiesPropertiesKeys(toscaElement, ownerId); + } + + private void updateCalculatedCapabilitiesPropertiesKeys(TopologyTemplate toscaElement, String ownerId) { + if(toscaElement.getCalculatedCapabilitiesProperties() != null && toscaElement.getCalculatedCapabilitiesProperties().containsKey(ownerId)){ + MapCapabilityProperty newProps = new MapCapabilityProperty(); + toscaElement.getCalculatedCapabilitiesProperties().get(ownerId) + .getMapToscaDataDefinition() + .forEach((k, v)-> updateAndAddCalculatedCapabilitiesProperties(k, v, toscaElement.getCalculatedCapabilities().get(ownerId), newProps)); + if(MapUtils.isNotEmpty(newProps.getMapToscaDataDefinition())) { + toscaElement.getCalculatedCapabilitiesProperties().put(ownerId, newProps); + } + } + } + + private void updateCalculatedRequirementsNames(TopologyTemplate toscaElement, String ownerId, String ownerName) { + if(toscaElement.getCalculatedRequirements() != null && toscaElement.getCalculatedRequirements().containsKey(ownerId)){ + String prefix = ownerName + "."; + toscaElement.getCalculatedRequirements().get(ownerId) + .getMapToscaDataDefinition().values().stream() + .flatMap(l -> l.getListToscaDataDefinition().stream()) + .forEach(r -> { + if(ComponentUtilities.isNotUpdatedCapReqName(prefix, r.getName(), r.getPreviousName())) { + if(StringUtils.isNotEmpty(r.getPreviousName())){ + r.setParentName(r.getPreviousName()); + } + r.setPreviousName(r.getName()); + } + r.setName(prefix + r.getPreviousName()); + }); + } + } + + private void updateCalculatedCapabilitiesNames(TopologyTemplate toscaElement, String ownerId, String ownerName) { + if(toscaElement.getCalculatedCapabilities() != null && toscaElement.getCalculatedCapabilities().containsKey(ownerId)){ + String prefix = ownerName + "."; + toscaElement.getCalculatedCapabilities().get(ownerId) + .getMapToscaDataDefinition().values().stream() + .flatMap(l -> l.getListToscaDataDefinition().stream()) + .forEach(c -> { + if(ComponentUtilities.isNotUpdatedCapReqName(prefix, c.getName(), c.getPreviousName())) { + if(StringUtils.isNotEmpty(c.getPreviousName())){ + c.setParentName(c.getPreviousName()); + } + c.setPreviousName(c.getName()); + } + c.setName(prefix + c.getPreviousName()); + }); + } + } + + private void updateAndAddCalculatedCapabilitiesProperties(String stringKey, MapPropertiesDataDefinition properties, MapListCapabilityDataDefinition calculatedCapabilities, MapCapabilityProperty newProps) { + String[] key = stringKey.split(ModelConverter.CAP_PROP_DELIM); + String capType = key[key.length - 2]; + String capName = key[key.length - 1]; + Optional<CapabilityDataDefinition> foundCapOpt = calculatedCapabilities.getMapToscaDataDefinition().get(capType) + .getListToscaDataDefinition().stream() + .filter(c -> c.getPreviousName().equals(capName)) + .findFirst(); + if(foundCapOpt.isPresent()){ + key[key.length - 1] = foundCapOpt.get().getName(); + newProps.put(buildCaLCapPropKey(key),properties); + } + } + + private void revertNamesOfCalculatedCapabilitiesRequirements(TopologyTemplate toscaElement, String ownerId) { + revertCalculatedCapabilitiesPropertiesKeys(toscaElement, ownerId); + revertCalculatedCapabilitiesNames(toscaElement, ownerId); + revertCalculatedRequirementsNames(toscaElement, ownerId); + } + + private void revertCalculatedCapabilitiesPropertiesKeys(TopologyTemplate toscaElement, String ownerId) { + if(toscaElement.getCalculatedCapabilitiesProperties() != null && toscaElement.getCalculatedCapabilitiesProperties().containsKey(ownerId)){ + MapCapabilityProperty newProps = new MapCapabilityProperty(); + toscaElement.getCalculatedCapabilitiesProperties().get(ownerId) + .getMapToscaDataDefinition() + .forEach((k,v) -> revertAndAddCalculatedCapabilitiesProperties(k, v, toscaElement.getCalculatedCapabilities().get(ownerId), newProps)); + if(MapUtils.isNotEmpty(newProps.getMapToscaDataDefinition())) { + toscaElement.getCalculatedCapabilitiesProperties().put(ownerId, newProps); + } + } + } + + private void revertCalculatedRequirementsNames(TopologyTemplate toscaElement, String ownerId) { + if(toscaElement.getCalculatedRequirements() != null && toscaElement.getCalculatedRequirements().containsKey(ownerId)){ + toscaElement.getCalculatedRequirements().get(ownerId) + .getMapToscaDataDefinition().values().stream() + .flatMap(l -> l.getListToscaDataDefinition().stream()) + .forEach(r -> {r.setName(r.getPreviousName());r.setPreviousName(r.getParentName());}); + } + } + + private void revertCalculatedCapabilitiesNames(TopologyTemplate toscaElement, String ownerId) { + if(toscaElement.getCalculatedCapabilities() != null && toscaElement.getCalculatedCapabilities().containsKey(ownerId)){ + toscaElement.getCalculatedCapabilities().get(ownerId) + .getMapToscaDataDefinition().values().stream() + .flatMap(l -> l.getListToscaDataDefinition().stream()) + .forEach(c -> {c.setName(c.getPreviousName());c.setPreviousName(c.getParentName());}); + } + } + + private void revertAndAddCalculatedCapabilitiesProperties(String stringKey, MapPropertiesDataDefinition properties, MapListCapabilityDataDefinition calculatedCapabilities, MapCapabilityProperty newProps) { + String[] key = stringKey.split(ModelConverter.CAP_PROP_DELIM); + String capType = key[key.length - 2]; + String capName = key[key.length - 1]; + Optional<CapabilityDataDefinition> foundCapOpt = calculatedCapabilities.getMapToscaDataDefinition().get(capType) + .getListToscaDataDefinition().stream() + .filter(c -> c.getName().equals(capName) && StringUtils.isNotEmpty(c.getPreviousName())) + .findFirst(); + if(foundCapOpt.isPresent()){ + key[key.length - 1] = foundCapOpt.get().getPreviousName(); + } + newProps.put(buildCaLCapPropKey(key), properties); + } + + private String buildCaLCapPropKey(String[] keyArray) { + StringBuilder key = new StringBuilder(); + for(int i = 0; i< keyArray.length; ++i){ + key.append(keyArray[i]); + if(i < keyArray.length - 1){ + key.append(ModelConverter.CAP_PROP_DELIM); + } + } + return key.toString(); + } + + private GraphVertex throwStorageException(TitanOperationStatus status) { + throw new StorageException(status); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaDataOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaDataOperation.java index f30a4d9159..0abc0111bf 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaDataOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaDataOperation.java @@ -20,12 +20,6 @@ package org.openecomp.sdc.be.model.jsontitan.operations; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - @org.springframework.stereotype.Component("tosca-data-operation") public class ToscaDataOperation extends BaseOperation { - - private static Logger logger = LoggerFactory.getLogger(ToscaDataOperation.class.getName()); - } 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 86415de635..d7ff072ba8 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 @@ -20,15 +20,8 @@ package org.openecomp.sdc.be.model.jsontitan.operations; -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; - +import com.thinkaurelius.titan.core.TitanVertex; +import fj.data.Either; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; @@ -46,15 +39,7 @@ import org.openecomp.sdc.be.dao.jsongraph.utils.IdBuilderUtils; import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils; import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -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.GroupInstanceDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapGroupsDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.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; @@ -73,12 +58,10 @@ import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; 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 org.openecomp.sdc.common.log.wrappers.Logger; -import com.thinkaurelius.titan.core.TitanVertex; - -import fj.data.Either; +import java.util.*; +import java.util.stream.Collectors; @org.springframework.stereotype.Component("tosca-element-lifecycle-operation") @@ -87,1516 +70,1520 @@ import fj.data.Either; */ public class ToscaElementLifecycleOperation extends BaseOperation { + private static final String FAILED_TO_DELETE_LAST_STATE_EDGE_STATUS_IS = "Failed to delete last state edge. Status is {}. "; private static final String FAILED_TO_GET_VERTICES = "Failed to get vertices by id {}. Status is {}. "; - public static final String VERSION_DELIMETER = "."; - public static final String VERSION_DELIMETER_REGEXP = "\\."; - - private static Logger logger = LoggerFactory.getLogger(ToscaElementLifecycleOperation.class.getName()); - - /** - * Performs changing a lifecycle state of tosca element from "checked out" or "ready for certification" to "checked in" - * - * @param currState - * @param toscaElementId - * @param modifierId - * @param ownerId - * @return - */ - public Either<ToscaElement, StorageOperationStatus> checkinToscaELement(LifecycleStateEnum currState, String toscaElementId, String modifierId, String ownerId) { - Either<GraphVertex, StorageOperationStatus> updateResult = null; - Either<ToscaElement, StorageOperationStatus> result = null; - Map<String, GraphVertex> vertices = null; - ToscaElementOperation operation; - try { - Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForCheckin(toscaElementId, modifierId, ownerId)); - if (getVerticesRes.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId); - updateResult = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value())); - } else { - vertices = getVerticesRes.left().value(); - updateResult = checkinToscaELement(currState, vertices.get(toscaElementId), vertices.get(ownerId), vertices.get(modifierId), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - } - if (updateResult.isLeft()) { - ComponentParametersView componentParametersView = buildComponentParametersViewAfterCheckin(); - operation = getToscaElementOperation(vertices.get(toscaElementId).getLabel()); - result = operation.getToscaElement(updateResult.left().value().getUniqueId(), componentParametersView); - if (result.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get updated tosca element {}. Status is {}", toscaElementId, result.right().value()); - } - } else { - result = Either.right(updateResult.right().value()); - } - } catch (Exception e) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during checkin of tosca element {}. {} ", toscaElementId, e.getMessage()); - } - return result; - } - - /** - * Returns vertex presenting owner of tosca element specified by uniqueId - * - * @param toscaElement - * @return - */ - public Either<User, StorageOperationStatus> getToscaElementOwner(String toscaElementId) { - Either<User, StorageOperationStatus> result = null; - GraphVertex toscaElement = null; - Either<GraphVertex, TitanOperationStatus> getToscaElementRes = titanDao.getVertexById(toscaElementId, JsonParseFlagEnum.NoParse); - if (getToscaElementRes.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getToscaElementRes.right().value())); - } - if (result == null) { - toscaElement = getToscaElementRes.left().value(); - Iterator<Vertex> vertices = toscaElement.getVertex().vertices(Direction.IN, EdgeLabelEnum.STATE.name()); - if (vertices == null || !vertices.hasNext()) { - result = Either.right(StorageOperationStatus.NOT_FOUND); - } else { - result = Either.left(convertToUser(vertices.next())); - } - } - return result; - } - - /** - * Returns vertex presenting owner of tosca element specified by uniqueId - * - * @param toscaElement - * @return - */ - public Either<User, StorageOperationStatus> getToscaElementOwner(GraphVertex toscaElement) { - Either<User, StorageOperationStatus> result = null; - Iterator<Vertex> vertices = toscaElement.getVertex().vertices(Direction.IN, EdgeLabelEnum.STATE.name()); - if (vertices == null || !vertices.hasNext()) { - result = Either.right(StorageOperationStatus.NOT_FOUND); - } else { - result = Either.left(convertToUser(vertices.next())); - } - return result; - } - - /** - * Performs checkout of a tosca element - * - * @param toscaElementId - * @param modifierId - * @param ownerId - * @param currState - * @return - */ - public Either<ToscaElement, StorageOperationStatus> checkoutToscaElement(String toscaElementId, String modifierId, String ownerId) { - Either<ToscaElement, StorageOperationStatus> result = null; - Map<String, GraphVertex> vertices = null; - try { - Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForCheckout(toscaElementId, modifierId, ownerId)); - if (getVerticesRes.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value())); - } - if (result == null) { - vertices = getVerticesRes.left().value(); - // update previous component if not certified - StorageOperationStatus status = updatePreviousVersion(vertices.get(toscaElementId), vertices.get(ownerId)); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update vertex with id {} . Status is {}. ", status); - result = Either.right(status); - } - } - if (result == null) { - result = cloneToscaElementForCheckout(vertices.get(toscaElementId), vertices.get(modifierId)); - if (result.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to checkout tosca element {}. Status is {} ", toscaElementId, result.right().value()); - } - - } - } catch (Exception e) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during checkout tosca element {}. {}", toscaElementId, e.getMessage()); - } - return result; - } - - /** - * Performs undo checkout for tosca element - * - * @param toscaElementId - * @return - */ - public Either<ToscaElement, StorageOperationStatus> undoCheckout(String toscaElementId) { - Either<ToscaElement, StorageOperationStatus> result = null; - 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())); - } - GraphVertex currVersionV = getToscaElementRes.left().value(); - if (result == null && hasPreviousVersion(currVersionV)) { - // find previous version - 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 {}. ", currVersionV.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME).toString()); - result = Either.right(StorageOperationStatus.NOT_FOUND); - } - if (result == null) { - preVersionVertex = nextVersionComponentIter.next().outVertex(); - StorageOperationStatus updateOldResourceResult = updateOldToscaElementBeforeUndoCheckout(preVersionVertex); - if (updateOldResourceResult != StorageOperationStatus.OK) { - result = Either.right(updateOldResourceResult); - } - } - } - if (result == null) { - 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()); - } - return result; - } - - private boolean hasPreviousVersion(GraphVertex toscaElementVertex) { - boolean hasPreviousVersion = true; - String version = (String) toscaElementVertex.getMetadataProperty(GraphPropertyEnum.VERSION); - if (StringUtils.isEmpty(version) || version.equals("0.1")) - hasPreviousVersion = false; - return hasPreviousVersion; - } - - /** - * Performs request certification for tosca element - * - * @param toscaElementId - * @param modifierId - * @param ownerId - * @return - */ - public Either<ToscaElement, StorageOperationStatus> requestCertificationToscaElement(String toscaElementId, String modifierId, String ownerId) { - Either<GraphVertex, StorageOperationStatus> resultUpdate = null; - Either<ToscaElement, StorageOperationStatus> result = null; - GraphVertex toscaElement = null; - GraphVertex modifier = null; - GraphVertex owner; - try { - Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId)); - if (getVerticesRes.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value())); - } - if (result == null) { - toscaElement = getVerticesRes.left().value().get(toscaElementId); - modifier = getVerticesRes.left().value().get(modifierId); - owner = getVerticesRes.left().value().get(ownerId); - - StorageOperationStatus status = handleRelationsUponRequestForCertification(toscaElement, modifier, owner); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to handle relations on certification request for tosca element {}. Status is {}. ", toscaElement.getUniqueId(), status); - } - } - if (result == null) { - LifecycleStateEnum nextState = LifecycleStateEnum.READY_FOR_CERTIFICATION; - - toscaElement.addMetadataProperty(GraphPropertyEnum.STATE, nextState.name()); - toscaElement.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); - - resultUpdate = updateToscaElementVertexMetadataPropertiesAndJson(toscaElement); - if (resultUpdate.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to set lifecycle for tosca elememt {} to state {}, error: {}", toscaElement.getUniqueId(), nextState, resultUpdate.right().value()); - result = Either.right(resultUpdate.right().value()); - } - } - if (result == null) { - ToscaElementOperation operation = getToscaElementOperation(toscaElement.getLabel()); - result = operation.getToscaElement(toscaElement.getUniqueId()); - } - return result; - - } catch (Exception e) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during request certification tosca element {}. {}", toscaElementId, e.getMessage()); - } - return result; - } - - /** - * Starts certification of tosca element - * - * @param toscaElementId - * @param modifierId - * @param ownerId - * @return - */ - public Either<ToscaElement, StorageOperationStatus> startCertificationToscaElement(String toscaElementId, String modifierId, String ownerId) { - Either<ToscaElement, StorageOperationStatus> result = null; - Either<GraphVertex, StorageOperationStatus> resultUpdate = null; - GraphVertex toscaElement = null; - GraphVertex modifier = null; - GraphVertex owner; - try { - Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId)); - if (getVerticesRes.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value())); - } - if (result == null) { - toscaElement = getVerticesRes.left().value().get(toscaElementId); - modifier = getVerticesRes.left().value().get(modifierId); - owner = getVerticesRes.left().value().get(ownerId); - - StorageOperationStatus status = handleRelationsUponCertification(toscaElement, modifier, owner); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to handle relations during certification of tosca element {}. Status is {}. ", toscaElement.getUniqueId(), status); - } - } - if (result == null) { - LifecycleStateEnum nextState = LifecycleStateEnum.CERTIFICATION_IN_PROGRESS; - - toscaElement.addMetadataProperty(GraphPropertyEnum.STATE, nextState.name()); - toscaElement.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); - - resultUpdate = updateToscaElementVertexMetadataPropertiesAndJson(toscaElement); - if (resultUpdate.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Couldn't set lifecycle for component {} to state {}, error: {}", toscaElement.getUniqueId(), nextState, resultUpdate.right().value()); - result = Either.right(resultUpdate.right().value()); - } - } - if (result == null) { - ToscaElementOperation operation = getToscaElementOperation(toscaElement.getLabel()); - result = operation.getToscaElement(toscaElement.getUniqueId()); - } - } catch (Exception e) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during start certification tosca element {}. {}", toscaElementId, e.getMessage()); - } - return result; - } - - public Either<ToscaElement, StorageOperationStatus> certifyToscaElement(String toscaElementId, String modifierId, String ownerId) { - Either<ToscaElement, StorageOperationStatus> result = null; - Either<GraphVertex, StorageOperationStatus> cloneRes = null; - GraphVertex toscaElement = null; - GraphVertex modifier = null; - GraphVertex certifiedToscaElement = null; - Integer majorVersion = null; - - StorageOperationStatus status; - try { - Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId)); - if (getVerticesRes.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value())); - } - if (result == null) { - toscaElement = getVerticesRes.left().value().get(toscaElementId); - modifier = getVerticesRes.left().value().get(modifierId); - majorVersion = getMajorVersion((String) toscaElement.getMetadataProperty(GraphPropertyEnum.VERSION)); - status = handleRelationsOfPreviousToscaElementBeforeCertifying(toscaElement, modifier, majorVersion); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to handle relations of previous tosca element before certifying {}. Status is {}. ", toscaElement.getUniqueId(), status); - } - } - if (result == null) { - cloneRes = cloneToscaElementForCertify(toscaElement, modifier, majorVersion); - if (cloneRes.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to clone tosca element during certification. "); - result = Either.right(cloneRes.right().value()); - } - } - if (result == null) { - certifiedToscaElement = cloneRes.left().value(); - status = handleRelationsOfNewestCertifiedToscaElement(toscaElement, certifiedToscaElement); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to handle relations of newest certified tosca element {}. Status is {}. ", certifiedToscaElement.getUniqueId(), status); - } - } - if (result == null) { - return getToscaElementOperation(toscaElement.getLabel()).getToscaElement(certifiedToscaElement.getUniqueId()); - } - } catch (Exception e) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during certification tosca element {}. {}", toscaElementId, e.getMessage()); - } - return result; - } - - /** - * Deletes (marks as deleted) all tosca elements according received name and uuid - * - * @param vertexType - * @param componentType - * @param componentName - * @param uuid - * @return - */ - public Either<Boolean, StorageOperationStatus> deleteOldToscaElementVersions(VertexTypeEnum vertexType, ComponentTypeEnum componentType, String componentName, String uuid) { - - Either<Boolean, StorageOperationStatus> result = null; - ToscaElementOperation operation = getToscaElementOperation(componentType); - - try { - Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class); - properties.put(GraphPropertyEnum.UUID, uuid); - properties.put(GraphPropertyEnum.NAME, componentName); - Either<List<GraphVertex>, TitanOperationStatus> getToscaElementsRes = titanDao.getByCriteria(vertexType, properties, JsonParseFlagEnum.ParseMetadata); - if (getToscaElementsRes.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getToscaElementsRes.right().value())); - } - if (result == null) { - result = markToscaElementsAsDeleted(operation, getToscaElementsRes.left().value()); - } - if (result == null) { - result = Either.left(true); - } - } catch (Exception e) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during deleteng all tosca elements by UUID {} and name {}. {} ", uuid, componentName, e.getMessage()); - } - return result; - } - - /** - * Performs cancelation or failure of certification for received tosca element - * - * @param toscaElementId - * @param modifierId - * @param ownerId - * @param nextState - * @return - */ - public Either<ToscaElement, StorageOperationStatus> cancelOrFailCertification(String toscaElementId, String modifierId, String ownerId, LifecycleStateEnum nextState) { - Either<ToscaElement, StorageOperationStatus> result = null; - StorageOperationStatus status; - ToscaElementOperation operation = null; - GraphVertex toscaElement = null; - GraphVertex modifier = null; - try { - Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId)); - if (getVerticesRes.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value())); - } - if (result == null) { - toscaElement = getVerticesRes.left().value().get(toscaElementId); - modifier = getVerticesRes.left().value().get(modifierId); - operation = getToscaElementOperation(toscaElement.getLabel()); - toscaElement.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); - toscaElement.setJsonMetadataField(JsonPresentationFields.USER_ID_LAST_UPDATER, modifier.getUniqueId()); - toscaElement.addMetadataProperty(GraphPropertyEnum.STATE, nextState.name()); - - Either<GraphVertex, TitanOperationStatus> updateVertexRes = titanDao.updateVertex(toscaElement); - if (updateVertexRes.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update vertex {} . Status is {}. ", toscaElementId, updateVertexRes.right().value()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateVertexRes.right().value())); - } - } - if (result == null) { - // cancel certification process - status = handleRelationsUponCancelCertification(toscaElement, nextState); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to handle relations upon cancel certification {}. Status is {}. ", toscaElement.getUniqueId(), status); - } - } - if (result == null) { - // fail certification - status = handleRelationsUponFailCertification(toscaElement, nextState); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to handle relations upon fail certification {}. Status is {}. ", toscaElement.getUniqueId(), status); - } - } - if (result == null) { - result = operation.getToscaElement(toscaElementId); - } - } catch (Exception e) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during cancel or fail certification of tosca element {}. {}. ", toscaElementId, e.getMessage()); - } - return result; - } - - public Either<GraphVertex, TitanOperationStatus> findUser(String userId) { - return findUserVertex(userId); - } - - private Either<Boolean, StorageOperationStatus> markToscaElementsAsDeleted(ToscaElementOperation operation, List<GraphVertex> toscaElements) { - Either<Boolean, StorageOperationStatus> result = Either.left(true); - for (GraphVertex resourceToDelete : toscaElements) { - if (!((String) resourceToDelete.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals(LifecycleStateEnum.CERTIFIED.name())) { - Either<GraphVertex, StorageOperationStatus> deleteElementRes = operation.markComponentToDelete(resourceToDelete); - if (deleteElementRes.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete tosca element {}. Status is {}. ", resourceToDelete.getUniqueId(), deleteElementRes.right().value()); - result = Either.right(deleteElementRes.right().value()); - break; - } - } - } - return result; - } - - private StorageOperationStatus handleRelationsOfNewestCertifiedToscaElement(GraphVertex toscaElement, GraphVertex certifiedToscaElement) { - StorageOperationStatus result = null; - Edge foundEdge = null; - Iterator<Edge> certReqUserEdgeIter = null; - // add rfc relation to preserve follower information - // get user of certification request - certReqUserEdgeIter = toscaElement.getVertex().edges(Direction.IN, GraphEdgeLabels.LAST_STATE.name()); - if (certReqUserEdgeIter == null || !certReqUserEdgeIter.hasNext()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to find rfc relation during certification clone. "); - result = StorageOperationStatus.NOT_FOUND; - } - 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); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(createVersionEdgeStatus); - } - } - if (result == null) { - - while (certReqUserEdgeIter.hasNext()) { - Edge edge = certReqUserEdgeIter.next(); - if (((String) titanDao.getProperty(edge, EdgePropertyEnum.STATE)).equals(LifecycleStateEnum.READY_FOR_CERTIFICATION.name())) { - foundEdge = edge; - break; - } - - } - if (foundEdge == null) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to find rfc relation during certification clone. "); - result = StorageOperationStatus.NOT_FOUND; - } - } - if (result == null) { - TitanOperationStatus createEdgeRes = titanDao.createEdge(foundEdge.outVertex(), certifiedToscaElement.getVertex(), EdgeLabelEnum.LAST_STATE, foundEdge); - if (createEdgeRes != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create rfc relation for component {}. status=", certifiedToscaElement.getUniqueId(), createEdgeRes); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(createEdgeRes); - } - } - if (result == null) { - result = StorageOperationStatus.OK; - } - return result; - } - - private StorageOperationStatus handleRelationsUponFailCertification(GraphVertex toscaElement, LifecycleStateEnum nextState) { - StorageOperationStatus result = null; - TitanOperationStatus status = null; - Edge originEdge; - Vertex user = null; - if (nextState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN) { - // fail certification - // delete relation CERTIFICATION_IN_PROGRESS - Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class); - properties.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - - Either<Edge, TitanOperationStatus> deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.STATE, properties); - if (deleteResult.isRight()) { - status = deleteResult.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete state edge. Status is {}. ", status); - result = StorageOperationStatus.INCONSISTENCY; - } - if (result == null) { - // delete relation READY_FOR_CERTIFICATION - properties.put(GraphPropertyEnum.STATE, LifecycleStateEnum.READY_FOR_CERTIFICATION); - deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.LAST_STATE, properties); - if (deleteResult.isRight()) { - status = deleteResult.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete last state edge. Status is {}. ", status); - result = StorageOperationStatus.INCONSISTENCY; - } - } - if (result == null) { - // delete relation NOT_CERTIFIED_CHECKIN (in order to change to STATE) - properties.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.LAST_STATE, properties); - if (deleteResult.isRight()) { - status = deleteResult.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete last state edge. Status is {}. ", status); - result = StorageOperationStatus.INCONSISTENCY; - } - } - if (result == null) { - // create new STATE relation NOT_CERTIFIED_CHECKIN - originEdge = deleteResult.left().value(); - user = originEdge.outVertex(); - status = titanDao.createEdge(user, toscaElement.getVertex(), EdgeLabelEnum.STATE, originEdge); - if (status != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create state edge. Status is {}. ", status); - result = StorageOperationStatus.INCONSISTENCY; - } - } - if (result == null) { - // delete relation LAST_MODIFIER (in order to change tester to designer) - deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.LAST_MODIFIER, new HashMap<>()); - if (status != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create last modifier edge. Status is {}. ", status); - result = StorageOperationStatus.INCONSISTENCY; - } - } - if (result == null) { - // create new LAST_MODIFIER relation - originEdge = deleteResult.left().value(); - status = titanDao.createEdge(user, toscaElement.getVertex(), EdgeLabelEnum.LAST_MODIFIER, originEdge); - if (status != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create last modifier edge. Status is {}. ", status); - result = StorageOperationStatus.INCONSISTENCY; - } - } - } - if (result == null) { - result = StorageOperationStatus.OK; - } - return result; - } - - private StorageOperationStatus handleRelationsUponCancelCertification(GraphVertex toscaElement, LifecycleStateEnum nextState) { - StorageOperationStatus result = null; - Edge originEdge; - if (nextState == LifecycleStateEnum.READY_FOR_CERTIFICATION) { - // delete relation CERTIFICATION_IN_PROGRESS - Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class); - properties.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - Either<Edge, TitanOperationStatus> deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.STATE, properties); - - if (deleteResult.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete state edge. Status is {}. ", deleteResult.right().value()); - result = StorageOperationStatus.INCONSISTENCY; - } - if (result == null) { - // delete relation READY_FOR_CERTIFICATION (LAST_STATE) - properties.put(GraphPropertyEnum.STATE, nextState); - deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.LAST_STATE, properties); - - if (deleteResult.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete last state edge. Status is {}. ", deleteResult.right().value()); - result = StorageOperationStatus.INCONSISTENCY; - } - } - if (result == null) { - // create relation READY_FOR_CERTIFICATION (STATE) - originEdge = deleteResult.left().value(); - TitanOperationStatus status = titanDao.createEdge(originEdge.outVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, originEdge); - if (status != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create state edge. Status is {}. ", status); - result = StorageOperationStatus.INCONSISTENCY; - } - } - if (result == null) { - result = StorageOperationStatus.OK; - } - } - return result; - } - - private StorageOperationStatus handleRelationsOfPreviousToscaElementBeforeCertifying(GraphVertex toscaElement, GraphVertex modifier, Integer majorVersion) { - StorageOperationStatus result = null; - if (majorVersion > 0) { - Either<Vertex, StorageOperationStatus> findRes = findLastCertifiedToscaElementVertex(toscaElement); - if (findRes.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch last certified tosca element {} . Status is {}. ", toscaElement.getMetadataProperty(GraphPropertyEnum.NAME), findRes.right().value()); - result = findRes.right().value(); - } - if (result == null) { - Vertex lastCertifiedVertex = findRes.left().value(); - Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class); - properties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, false); - TitanOperationStatus status = titanDao.updateVertexMetadataPropertiesWithJson(lastCertifiedVertex, properties); - if (status != TitanOperationStatus.OK) { - 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) { - result = StorageOperationStatus.OK; - } - return result; - } - - private StorageOperationStatus handleRelationsUponRequestForCertification(GraphVertex toscaElement, GraphVertex modifier, GraphVertex owner) { - TitanOperationStatus status; - StorageOperationStatus result = null; - - if (((String) toscaElement.getMetadataProperty(GraphPropertyEnum.STATE)).equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { - // remove CHECKOUT relation - Either<Edge, TitanOperationStatus> deleteRes = titanDao.deleteEdge(owner, toscaElement, EdgeLabelEnum.STATE); - if (deleteRes.isRight()) { - status = deleteRes.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete edge. Status is {}. ", status); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - if (result == null) { - // create CHECKIN relation - Map<EdgePropertyEnum, Object> properties = new EnumMap<>(EdgePropertyEnum.class); - properties.put(EdgePropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - status = titanDao.createEdge(modifier.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.LAST_STATE, properties); - if (status != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create edge. Status is {}", status); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - } - } else { - status = titanDao.replaceEdgeLabel(owner.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE); - if (status != TitanOperationStatus.OK) { - result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - } - if (result == null) { - // create RFC relation - Map<EdgePropertyEnum, Object> properties = new EnumMap<>(EdgePropertyEnum.class); - properties.put(EdgePropertyEnum.STATE, LifecycleStateEnum.READY_FOR_CERTIFICATION); - status = titanDao.createEdge(modifier.getVertex(), toscaElement.getVertex(), 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 handleRelationsUponCertification(GraphVertex toscaElement, GraphVertex modifier, GraphVertex owner) { - - StorageOperationStatus result = null; - TitanOperationStatus status = titanDao.replaceEdgeLabel(owner.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE); - if (status != TitanOperationStatus.OK) { - result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - if (result == null) { - Map<EdgePropertyEnum, Object> properties = new EnumMap<>(EdgePropertyEnum.class); - properties.put(EdgePropertyEnum.STATE, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - 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) { - Either<GraphVertex, StorageOperationStatus> updateRelationsRes = updateLastModifierEdge(toscaElement, owner, modifier); - if (updateRelationsRes.isRight()) { - result = updateRelationsRes.right().value(); - } - } - if (result == null) { - result = StorageOperationStatus.OK; - } - return result; - } - - private Either<Vertex, StorageOperationStatus> findLastCertifiedToscaElementVertex(GraphVertex toscaElement) { - return findLastCertifiedToscaElementVertexRecursively(toscaElement.getVertex()); - } - - private Either<Vertex, StorageOperationStatus> findLastCertifiedToscaElementVertexRecursively(Vertex vertex) { - if (isCertifiedVersion((String) vertex.property(GraphPropertyEnum.VERSION.getProperty()).value())) { - return Either.left(vertex); - } - Iterator<Edge> edgeIter = vertex.edges(Direction.IN, EdgeLabelEnum.VERSION.name()); - if (!edgeIter.hasNext()) { - return Either.right(StorageOperationStatus.NOT_FOUND); - } - return findLastCertifiedToscaElementVertexRecursively(edgeIter.next().outVertex()); - } - - private boolean isCertifiedVersion(String version) { - String[] versionParts = version.split(VERSION_DELIMETER_REGEXP); - if (Integer.parseInt(versionParts[0]) > 0 && Integer.parseInt(versionParts[1]) == 0) { - return true; - } - return false; - } - - private StorageOperationStatus updateOldToscaElementBeforeUndoCheckout(Vertex previousVersionToscaElement) { - - StorageOperationStatus result = StorageOperationStatus.OK; - String previousVersion = (String) previousVersionToscaElement.property(GraphPropertyEnum.VERSION.getProperty()).value(); - if (!previousVersion.endsWith(".0")) { - try { - CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to update vertex of previous version of tosca element", previousVersionToscaElement.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty())); - - Map<String, Object> propertiesToUpdate = new HashMap<>(); - propertiesToUpdate.put(GraphPropertyEnum.IS_HIGHEST_VERSION.getProperty(), true); - 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.toJson(jsonMetadataMap)); - - titanDao.setVertexProperties(previousVersionToscaElement, propertiesToUpdate); - - Iterator<Edge> edgesIter = previousVersionToscaElement.edges(Direction.IN, EdgeLabelEnum.LAST_STATE.name()); - if (!edgesIter.hasNext()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch last modifier vertex for tosca element {}. ", previousVersionToscaElement.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty())); - result = StorageOperationStatus.NOT_FOUND; - } else { - Edge lastStateEdge = edgesIter.next(); - Vertex lastModifier = lastStateEdge.outVertex(); - TitanOperationStatus replaceRes = titanDao.replaceEdgeLabel(lastModifier, previousVersionToscaElement, lastStateEdge, EdgeLabelEnum.LAST_STATE, EdgeLabelEnum.STATE); - if (replaceRes != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to replace label from {} to {}. status = {}", EdgeLabelEnum.LAST_STATE, EdgeLabelEnum.STATE, replaceRes); - result = StorageOperationStatus.INCONSISTENCY; - if (replaceRes != TitanOperationStatus.INVALID_ID) { - result = DaoStatusConverter.convertTitanStatusToStorageStatus(replaceRes); - } - } - - } - } catch (Exception e) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during update previous tosca element {} before undo checkout. {} ", e.getMessage()); - } - } - return result; - } - - private StorageOperationStatus updatePreviousVersion(GraphVertex toscaElementVertex, GraphVertex ownerVertex) { - StorageOperationStatus result = null; - String ownerId = (String) ownerVertex.getMetadataProperty(GraphPropertyEnum.USERID); - String toscaElementId = toscaElementVertex.getUniqueId(); - if (!toscaElementVertex.getMetadataProperty(GraphPropertyEnum.STATE).equals(LifecycleStateEnum.CERTIFIED.name())) { - toscaElementVertex.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION, false); - Either<GraphVertex, TitanOperationStatus> updateVertexRes = titanDao.updateVertex(toscaElementVertex); - if (updateVertexRes.isRight()) { - TitanOperationStatus titatStatus = updateVertexRes.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update tosca element vertex {}. Status is {}", toscaElementVertex.getUniqueId(), titatStatus); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(titatStatus); - } - Either<Edge, TitanOperationStatus> deleteEdgeRes = null; - if (result == null) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to replace edge with label {} to label {} from {} to {}. ", EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE, ownerId, toscaElementId); - - deleteEdgeRes = titanDao.deleteEdge(ownerVertex, toscaElementVertex, EdgeLabelEnum.STATE); - if (deleteEdgeRes.isRight()) { - TitanOperationStatus titanStatus = deleteEdgeRes.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete edge with label {} from {} to {}. Status is {} ", EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE, ownerId, toscaElementId, titanStatus); - if (!titanStatus.equals(TitanOperationStatus.INVALID_ID)) { - result = DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus); - } else { - result = StorageOperationStatus.INCONSISTENCY; - } - } - } - if (result == null) { - TitanOperationStatus createEdgeRes = titanDao.createEdge(ownerVertex.getVertex(), toscaElementVertex.getVertex(), EdgeLabelEnum.LAST_STATE, deleteEdgeRes.left().value()); - if (createEdgeRes != TitanOperationStatus.OK) { - result = DaoStatusConverter.convertTitanStatusToStorageStatus(createEdgeRes); - } - } - } - if (result == null) { - result = StorageOperationStatus.OK; - } - return result; - } - - private Either<ToscaElement, StorageOperationStatus> cloneToscaElementForCheckout(GraphVertex toscaElementVertex, GraphVertex modifierVertex) { - - Either<ToscaElement, StorageOperationStatus> result = null; - Either<GraphVertex, StorageOperationStatus> cloneResult = null; - ToscaElementOperation operation = getToscaElementOperation(toscaElementVertex.getLabel()); - // 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(); - String fetchedVersion = (String) nextVersionVertex.property(GraphPropertyEnum.VERSION.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); - } - if (result == null) { - cloneResult = operation.cloneToscaElement(toscaElementVertex, cloneGraphVertexForCheckout(toscaElementVertex, modifierVertex), modifierVertex); - if (cloneResult.isRight()) { - result = Either.right(cloneResult.right().value()); - } - } - GraphVertex clonedVertex = null; - if (result == null) { - clonedVertex = cloneResult.left().value(); - TitanOperationStatus status = titanDao.createEdge(toscaElementVertex.getVertex(), cloneResult.left().value().getVertex(), EdgeLabelEnum.VERSION, new HashMap<>()); - if (status != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create edge with label {} from vertex {} to tosca element vertex {} on graph. Status is {}. ", EdgeLabelEnum.VERSION, - toscaElementVertex.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), cloneResult.left().value().getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - 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; - } - - private Either<ToscaElement, StorageOperationStatus> handleFixTopologyTemplate(GraphVertex toscaElementVertex, Either<ToscaElement, StorageOperationStatus> result, ToscaElementOperation operation, GraphVertex clonedVertex, - ToscaElement toscaElement) { - TopologyTemplate topologyTemplate = (TopologyTemplate) toscaElement; - Map<String, MapPropertiesDataDefinition> instInputs = topologyTemplate.getInstInputs(); - Map<String, MapGroupsDataDefinition> instGroups = topologyTemplate.getInstGroups(); - Map<String, MapArtifactDataDefinition> instArtifactsMap = topologyTemplate.getInstanceArtifacts(); - Map<String, ToscaElement> origCompMap = new HashMap<>(); - if (instInputs == null) { - instInputs = new HashMap<>(); - } - if (instGroups == null) { - instGroups = new HashMap<>(); - } - if (instArtifactsMap == null) { - instArtifactsMap = new HashMap<>(); - } - Map<String, ComponentInstanceDataDefinition> instancesMap = topologyTemplate.getComponentInstances(); - boolean isAddInstGroup = instGroups == null || instGroups.isEmpty(); - boolean needUpdateComposition = false; - - if (instancesMap != null && !instancesMap.isEmpty()) { - for (ComponentInstanceDataDefinition vfInst : instancesMap.values()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "vfInst name is {} . OriginType {}. ", vfInst.getName(), vfInst.getOriginType()); - if (vfInst.getOriginType().name().equals(OriginTypeEnum.VF.name())) { - collectInstanceInputAndGroups(instInputs, instGroups, instArtifactsMap, origCompMap, isAddInstGroup, vfInst, clonedVertex); - } - needUpdateComposition = needUpdateComposition || fixToscaComponentName(vfInst, origCompMap); - if (needUpdateComposition) { - instancesMap.put(vfInst.getUniqueId(), vfInst); - } - } - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "before add to graph instInputs {} instGroups {} needUpdateComposition {}", instInputs, instGroups, needUpdateComposition); - if (!instInputs.isEmpty()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "before add inst inputs {} ", instInputs == null ? 0 : instInputs.size()); - GraphVertex toscaDataVertex = null; - Either<GraphVertex, TitanOperationStatus> instInpVertexEither = titanDao.getChildVertex(toscaElementVertex, EdgeLabelEnum.INST_INPUTS, JsonParseFlagEnum.ParseJson); - if (instInpVertexEither.isLeft()) { - toscaDataVertex = instInpVertexEither.left().value(); - } - - StorageOperationStatus status = handleToscaData(clonedVertex, VertexTypeEnum.INST_INPUTS, EdgeLabelEnum.INST_INPUTS, toscaDataVertex, instInputs); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update instance inputs . Status is {}. ", status); - result = Either.right(status); - return result; - } - - } - if (!instGroups.isEmpty()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "before add inst groups {} ", instGroups == null ? 0 : instGroups.size()); - GraphVertex toscaDataVertex = null; - Either<GraphVertex, TitanOperationStatus> instGrVertexEither = titanDao.getChildVertex(toscaElementVertex, EdgeLabelEnum.INST_GROUPS, JsonParseFlagEnum.ParseJson); - if (instGrVertexEither.isLeft()) { - toscaDataVertex = instGrVertexEither.left().value(); - } - - StorageOperationStatus status = handleToscaData(clonedVertex, VertexTypeEnum.INST_GROUPS, EdgeLabelEnum.INST_GROUPS, toscaDataVertex, instGroups); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update instance group . Status is {}. ", status); - result = Either.right(status); - return result; - } - - } - if (needUpdateComposition) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "before update Instances "); - Map<String, CompositionDataDefinition> jsonComposition = (Map<String, CompositionDataDefinition>) clonedVertex.getJson(); - CompositionDataDefinition compositionDataDefinition = jsonComposition.get(JsonConstantKeysEnum.COMPOSITION.getValue()); - compositionDataDefinition.setComponentInstances(instancesMap); - Either<GraphVertex, TitanOperationStatus> updateElement = titanDao.updateVertex(clonedVertex); - if (updateElement.isRight()) { - TitanOperationStatus status = updateElement.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update instances on metadata vertex . Status is {}. ", status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - } - - result = operation.getToscaElement(clonedVertex.getUniqueId()); - - } else { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "RI map empty on component {}", toscaElement.getUniqueId()); - } - return result; - } - - // TODO remove after jsonModelMigration - public boolean resolveToscaComponentName(ComponentInstanceDataDefinition vfInst, Map<String, ToscaElement> origCompMap) { - return fixToscaComponentName(vfInst, origCompMap); - } - - private boolean fixToscaComponentName(ComponentInstanceDataDefinition vfInst, Map<String, ToscaElement> origCompMap) { - if (vfInst.getToscaComponentName() == null || vfInst.getToscaComponentName().isEmpty()) { - String ciUid = vfInst.getUniqueId(); - String origCompUid = vfInst.getComponentUid(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "fixToscaComponentName:: Ri id {} . origin component id is {}. type is{} ", ciUid, origCompUid, vfInst.getOriginType()); - ToscaElement origComp = null; - if (!origCompMap.containsKey(origCompUid)) { - Either<ToscaElement, StorageOperationStatus> origCompEither; - if (vfInst.getOriginType() == null || vfInst.getOriginType().name().equals(OriginTypeEnum.VF.name())) { - origCompEither = topologyTemplateOperation.getToscaElement(origCompUid); - } else { - origCompEither = nodeTypeOperation.getToscaElement(origCompUid); - } - if (origCompEither.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to find orig component {} . Status is {}. ", origCompEither.right().value()); - return false; - } - origComp = origCompEither.left().value(); - origCompMap.put(origCompUid, origComp); - } else { - origComp = origCompMap.get(origCompUid); - } - String toscaName = (String) origComp.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Origin component id is {}. toscaName {}", origCompUid, toscaName); - vfInst.setToscaComponentName(toscaName); - return true; - } - return false; - } - - private void collectInstanceInputAndGroups(Map<String, MapPropertiesDataDefinition> instInputs, Map<String, MapGroupsDataDefinition> instGroups, Map<String, MapArtifactDataDefinition> instArtifactsMap, Map<String, ToscaElement> origCompMap, - boolean isAddInstGroup, ComponentInstanceDataDefinition vfInst, GraphVertex clonedVertex) { - String ciUid = vfInst.getUniqueId(); - String origCompUid = vfInst.getComponentUid(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "collectInstanceInputAndGroups:: Ri id {} . origin component id is {}. ", ciUid, origCompUid); - TopologyTemplate origComp = null; - if (!origCompMap.containsKey(origCompUid)) { - Either<ToscaElement, StorageOperationStatus> origCompEither = topologyTemplateOperation.getToscaElement(origCompUid); - if (origCompEither.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to find orig component {} . Status is {}. ", origCompEither.right().value()); - return; - } - origComp = (TopologyTemplate) origCompEither.left().value(); - origCompMap.put(origCompUid, origComp); - } else { - origComp = (TopologyTemplate) origCompMap.get(origCompUid); - } - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Orig component {}. ", origComp.getUniqueId()); - - Map<String, PropertyDataDefinition> origInputs = origComp.getInputs(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Orig component inputs size {}. ", origInputs == null ? 0 : origInputs.size()); - if (origInputs != null) { - if (!instInputs.containsKey(ciUid)) { - MapPropertiesDataDefinition instProperties = new MapPropertiesDataDefinition(origInputs); - instInputs.put(ciUid, instProperties); - } else { - - MapPropertiesDataDefinition instInputMap = instInputs.get(ciUid); - Map<String, PropertyDataDefinition> instProp = instInputMap.getMapToscaDataDefinition(); - origInputs.forEach((propName, propMap) -> { - if (!instProp.containsKey(propName)) { - instProp.put(propName, propMap); - } - }); - } - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "ComponentInstanseInputs {}. ", instInputs.get(ciUid)); - } - - if (isAddInstGroup) { - 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()); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "check vf groups . Size is {} ", filteredGroups == null ? 0 : filteredGroups.size()); - } - 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 { - instArifacts = instArtifactsMap.get(ciUid); - } - - 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) { - 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); - 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); - groupInstance.setGroupInstanceArtifactsUuid(artifactsUid); - groupInstanceToCreate.put(groupInstance.getName(), groupInstance); - } - if (MapUtils.isNotEmpty(groupInstanceToCreate)) { - instGroups.put(vfInst.getUniqueId(), new MapGroupsDataDefinition(groupInstanceToCreate)); - - } - } - } - } - } - - private GraphVertex cloneGraphVertexForCheckout(GraphVertex toscaElementVertex, GraphVertex modifierVertex) { - GraphVertex nextVersionToscaElementVertex = new GraphVertex(); - String uniqueId = UniqueIdBuilder.buildComponentUniqueId(); - Map<GraphPropertyEnum, Object> metadataProperties = new HashMap<>(toscaElementVertex.getMetadataProperties()); - nextVersionToscaElementVertex.setMetadataProperties(metadataProperties); - nextVersionToscaElementVertex.setUniqueId(uniqueId); - nextVersionToscaElementVertex.setLabel(toscaElementVertex.getLabel()); - nextVersionToscaElementVertex.setType(toscaElementVertex.getType()); - - nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, uniqueId); - nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE, nextVersionToscaElementVertex.getType().name()); - String nextVersion = getNextVersion((String) toscaElementVertex.getMetadataProperty(GraphPropertyEnum.VERSION)); - if (isFirstCheckoutAfterCertification(nextVersion)) { - nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.UUID, IdBuilderUtils.generateUUID()); - } - nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.VERSION, nextVersion); - nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()); - nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - - if (toscaElementVertex.getType() == ComponentTypeEnum.SERVICE && toscaElementVertex.getMetadataProperty(GraphPropertyEnum.STATE).equals(LifecycleStateEnum.CERTIFIED.name())) { - nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.getValue()); - } - if (!MapUtils.isEmpty(toscaElementVertex.getMetadataJson())) { - nextVersionToscaElementVertex.setMetadataJson(new HashMap<String, Object>(toscaElementVertex.getMetadataJson())); - nextVersionToscaElementVertex.updateMetadataJsonWithCurrentMetadataProperties(); - } - long currTime = System.currentTimeMillis(); - nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.CREATION_DATE, currTime); - nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, currTime); - nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.USER_ID_CREATOR, modifierVertex.getUniqueId()); - nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.USER_ID_LAST_UPDATER, modifierVertex.getUniqueId()); - if (toscaElementVertex.getType() == ComponentTypeEnum.SERVICE) { - nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.CONFORMANCE_LEVEL, ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel()); - } - - if (!MapUtils.isEmpty(toscaElementVertex.getJson())) { - nextVersionToscaElementVertex.setJson(new HashMap<String, ToscaDataDefinition>(toscaElementVertex.getJson())); - } - return nextVersionToscaElementVertex; - } - - private Either<GraphVertex, StorageOperationStatus> cloneToscaElementForCertify(GraphVertex toscaElementVertex, GraphVertex modifierVertex, Integer majorVersion) { - Either<GraphVertex, StorageOperationStatus> result; - Either<List<GraphVertex>, StorageOperationStatus> deleteResult = null; - GraphVertex clonedToscaElement = null; - result = getToscaElementOperation(toscaElementVertex.getLabel()).cloneToscaElement(toscaElementVertex, cloneGraphVertexForCertify(toscaElementVertex, modifierVertex, majorVersion), modifierVertex); - if (result.isRight()) { - 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()); - result = Either.right(deleteResult.right().value()); - } - } - if (result.isLeft()) { - result = handlePreviousVersionRelation(clonedToscaElement, deleteResult.left().value(), majorVersion); - } - return result; - } - - private Either<GraphVertex, StorageOperationStatus> handlePreviousVersionRelation(GraphVertex clonedToscaElement, List<GraphVertex> deletedVersions, Integer majorVersion) { - Either<GraphVertex, StorageOperationStatus> result = null; - Vertex previousCertifiedToscaElement = null; - if (majorVersion > 0) { - List<GraphVertex> firstMinorVersionVertex = deletedVersions.stream().filter(gv -> getMinorVersion((String) gv.getMetadataProperty(GraphPropertyEnum.VERSION)) == 1).collect(Collectors.toList()); - - if (CollectionUtils.isEmpty(firstMinorVersionVertex)) { - result = Either.right(StorageOperationStatus.NOT_FOUND); - } else { - previousCertifiedToscaElement = getPreviousCertifiedToscaElement(firstMinorVersionVertex.get(0)); - if (previousCertifiedToscaElement == null) { - result = Either.right(StorageOperationStatus.NOT_FOUND); - } - } - if (result == null) { - TitanOperationStatus status = titanDao.createEdge(previousCertifiedToscaElement, clonedToscaElement.getVertex(), EdgeLabelEnum.VERSION, new HashMap<>()); - if (status != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create edge with label {} from vertex {} to tosca element vertex {} on graph. Status is {}. ", EdgeLabelEnum.VERSION, - previousCertifiedToscaElement.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), clonedToscaElement.getUniqueId(), status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - - } - if (result == null) { - result = Either.left(clonedToscaElement); - } - return result; - } - - private Vertex getPreviousCertifiedToscaElement(GraphVertex graphVertex) { - - Iterator<Edge> edges = graphVertex.getVertex().edges(Direction.IN, EdgeLabelEnum.VERSION.name()); - if (edges.hasNext()) { - return edges.next().outVertex(); - } - return null; - } - - private Either<List<GraphVertex>, StorageOperationStatus> deleteAllPreviousNotCertifiedVersions(GraphVertex toscaElementVertex) { - Either<List<GraphVertex>, StorageOperationStatus> result = null; - - ToscaElementOperation operation = getToscaElementOperation(toscaElementVertex.getLabel()); - List<GraphVertex> previosVersions = null; - Object uuid = toscaElementVertex.getMetadataProperty(GraphPropertyEnum.UUID); - Object componentName = toscaElementVertex.getMetadataProperty(GraphPropertyEnum.NAME); - try { - Map<GraphPropertyEnum, Object> properties = new HashMap<>(); - properties.put(GraphPropertyEnum.UUID, uuid); - properties.put(GraphPropertyEnum.NAME, componentName); - Either<List<GraphVertex>, TitanOperationStatus> getToscaElementsRes = titanDao.getByCriteria(toscaElementVertex.getLabel(), properties, JsonParseFlagEnum.ParseMetadata); - if (getToscaElementsRes.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getToscaElementsRes.right().value())); - } - if (result == null) { - previosVersions = getToscaElementsRes.left().value(); - Either<Boolean, StorageOperationStatus> deleteResult = markToscaElementsAsDeleted(operation, getToscaElementsRes.left().value()); - if (deleteResult.isRight()) { - result = Either.right(deleteResult.right().value()); - } - } - if (result == null) { - result = Either.left(previosVersions); - } - } catch (Exception e) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during deleteng all tosca elements by UUID {} and name {}. {} ", uuid, componentName, e.getMessage()); - } - return result; - } - - private GraphVertex cloneGraphVertexForCertify(GraphVertex toscaElementVertex, GraphVertex modifierVertex, Integer majorVersion) { - - GraphVertex nextVersionToscaElementVertex = new GraphVertex(); - String uniqueId = IdBuilderUtils.generateUniqueId(); - Map<GraphPropertyEnum, Object> metadataProperties = new HashMap<>(toscaElementVertex.getMetadataProperties()); - nextVersionToscaElementVertex.setMetadataProperties(metadataProperties); - nextVersionToscaElementVertex.setUniqueId(uniqueId); - nextVersionToscaElementVertex.setLabel(toscaElementVertex.getLabel()); - nextVersionToscaElementVertex.setType(toscaElementVertex.getType()); - - nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, uniqueId); - nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE, nextVersionToscaElementVertex.getType().name()); - nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.VERSION, (majorVersion + 1) + VERSION_DELIMETER + "0"); - nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.CREATION_DATE, System.currentTimeMillis()); - nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, null); - nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.USER_ID_CREATOR, modifierVertex.getUniqueId()); - nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.USER_ID_LAST_UPDATER, modifierVertex.getUniqueId()); - - if (toscaElementVertex.getType() == ComponentTypeEnum.SERVICE && toscaElementVertex.getMetadataProperty(GraphPropertyEnum.STATE).equals(LifecycleStateEnum.CERTIFIED)) { - nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.getValue()); - } - if (!MapUtils.isEmpty(toscaElementVertex.getMetadataJson())) { - nextVersionToscaElementVertex.setMetadataJson(new HashMap<String, Object>(toscaElementVertex.getMetadataJson())); - nextVersionToscaElementVertex.updateMetadataJsonWithCurrentMetadataProperties(); - } - if (!MapUtils.isEmpty(toscaElementVertex.getJson())) { - nextVersionToscaElementVertex.setJson(new HashMap<String, ToscaDataDefinition>(toscaElementVertex.getJson())); - } - return nextVersionToscaElementVertex; - } - - private ComponentParametersView buildComponentParametersViewAfterCheckin() { - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnoreUsers(false); - return componentParametersView; - } - - private Either<GraphVertex, StorageOperationStatus> checkinToscaELement(LifecycleStateEnum currState, GraphVertex toscaElementVertex, GraphVertex ownerVertex, GraphVertex modifierVertex, LifecycleStateEnum nextState) { - Either<GraphVertex, StorageOperationStatus> updateRelationsRes; - Either<GraphVertex, StorageOperationStatus> result = changeStateToCheckedIn(currState, toscaElementVertex, ownerVertex, modifierVertex); - if (result.isLeft()) { - toscaElementVertex.addMetadataProperty(GraphPropertyEnum.STATE, nextState.name()); - toscaElementVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); - result = updateToscaElementVertexMetadataPropertiesAndJson(toscaElementVertex); - } - if (result.isLeft()) { - updateRelationsRes = updateLastModifierEdge(toscaElementVertex, ownerVertex, modifierVertex); - if (updateRelationsRes.isRight()) { - result = Either.right(updateRelationsRes.right().value()); - } - } - return result; - } - - private Either<GraphVertex, StorageOperationStatus> updateToscaElementVertexMetadataPropertiesAndJson(GraphVertex toscaElementVertex) { - - Either<GraphVertex, StorageOperationStatus> result; - - Either<GraphVertex, TitanOperationStatus> updateVertexRes = titanDao.updateVertex(toscaElementVertex); - if (updateVertexRes.isRight()) { - TitanOperationStatus titatStatus = updateVertexRes.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update state of tosca element vertex {} metadata. Status is {}", toscaElementVertex.getUniqueId(), titatStatus); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(titatStatus)); - } else { - result = Either.left(updateVertexRes.left().value()); - } - return result; - } - - private Either<GraphVertex, StorageOperationStatus> changeStateToCheckedIn(LifecycleStateEnum currState, GraphVertex toscaElementVertex, GraphVertex ownerVertex, GraphVertex modifierVertex) { - Either<GraphVertex, StorageOperationStatus> result = null; - LifecycleStateEnum nextState = LifecycleStateEnum.NOT_CERTIFIED_CHECKIN; - String faileToUpdateStateMsg = "Failed to update state of tosca element {}. Status is {}"; - - if (currState == LifecycleStateEnum.READY_FOR_CERTIFICATION) { - // In case of cancel "ready for certification" remove last state edge with "STATE" property equals to "NOT_CERTIFIED_CHECKIN" - Map<GraphPropertyEnum, Object> vertexProperties = new HashMap<>(); - vertexProperties.put(GraphPropertyEnum.STATE, nextState); - Either<Edge, TitanOperationStatus> deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElementVertex, EdgeLabelEnum.LAST_STATE, vertexProperties); - if (deleteResult.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, faileToUpdateStateMsg, toscaElementVertex.getUniqueId(), deleteResult.right().value()); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "failed to update last state relation"); - result = Either.right(StorageOperationStatus.INCONSISTENCY); - } - } - if (result == null) { - // Remove CHECKOUT relation - Either<Edge, TitanOperationStatus> deleteEdgeResult = titanDao.deleteEdge(ownerVertex, toscaElementVertex, EdgeLabelEnum.STATE); - if (deleteEdgeResult.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, faileToUpdateStateMsg, toscaElementVertex.getUniqueId()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(deleteEdgeResult.right().value())); - } - } - if (result == null) { - // Create CHECKIN relation - Map<EdgePropertyEnum, Object> edgeProperties = new HashMap<>(); - edgeProperties.put(EdgePropertyEnum.STATE, nextState); - TitanOperationStatus createEdgeRes = titanDao.createEdge(modifierVertex.getVertex(), toscaElementVertex.getVertex(), EdgeLabelEnum.STATE, edgeProperties); - if (createEdgeRes != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, faileToUpdateStateMsg, toscaElementVertex.getUniqueId()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createEdgeRes)); - } - } - if (result == null) { - result = Either.left(toscaElementVertex); - } - return result; - } - - private Either<GraphVertex, StorageOperationStatus> updateLastModifierEdge(GraphVertex toscaElementVertex, GraphVertex ownerVertex, GraphVertex modifierVertex) { - Either<GraphVertex, StorageOperationStatus> result = null; - if (!modifierVertex.getMetadataProperties().get(GraphPropertyEnum.USERID).equals(ownerVertex.getMetadataProperties().get(GraphPropertyEnum.USERID))) { - Either<Edge, TitanOperationStatus> deleteEdgeRes = titanDao.deleteEdge(ownerVertex, toscaElementVertex, EdgeLabelEnum.LAST_MODIFIER); - if (deleteEdgeRes.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete last modifier {} to tosca element {}. Edge type is {}", ownerVertex.getUniqueId(), ownerVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(deleteEdgeRes.right().value())); - } - if (result == null) { - TitanOperationStatus createEdgeRes = titanDao.createEdge(modifierVertex.getVertex(), toscaElementVertex.getVertex(), EdgeLabelEnum.LAST_MODIFIER, new HashMap<>()); - - if (createEdgeRes != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to associate user {} to component {}. Edge type is {}", modifierVertex.getUniqueId(), ownerVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createEdgeRes)); - } else { - result = Either.left(modifierVertex); - } - } - } else { - result = Either.left(ownerVertex); - } - return result; - } - - private Map<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> prepareParametersToGetVerticesForCheckin(String toscaElementId, String modifierId, String ownerId) { - Map<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> verticesToGetParameters = new HashMap<>(); - verticesToGetParameters.put(toscaElementId, new ImmutablePair<>(GraphPropertyEnum.UNIQUE_ID, JsonParseFlagEnum.ParseMetadata)); - verticesToGetParameters.put(modifierId, new ImmutablePair<>(GraphPropertyEnum.USERID, JsonParseFlagEnum.NoParse)); - verticesToGetParameters.put(ownerId, new ImmutablePair<>(GraphPropertyEnum.USERID, JsonParseFlagEnum.NoParse)); - return verticesToGetParameters; - } - - private Map<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> prepareParametersToGetVerticesForRequestCertification(String toscaElementId, String modifierId, String ownerId) { - Map<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> verticesToGetParameters = new HashMap<>(); - verticesToGetParameters.put(toscaElementId, new ImmutablePair<>(GraphPropertyEnum.UNIQUE_ID, JsonParseFlagEnum.ParseAll)); - verticesToGetParameters.put(modifierId, new ImmutablePair<>(GraphPropertyEnum.USERID, JsonParseFlagEnum.NoParse)); - verticesToGetParameters.put(ownerId, new ImmutablePair<>(GraphPropertyEnum.USERID, JsonParseFlagEnum.NoParse)); - return verticesToGetParameters; - } - - private Map<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> prepareParametersToGetVerticesForCheckout(String toscaElementId, String modifierId, String ownerId) { - Map<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> verticesToGetParameters = new HashMap<>(); - verticesToGetParameters.put(toscaElementId, new ImmutablePair<>(GraphPropertyEnum.UNIQUE_ID, JsonParseFlagEnum.ParseAll)); - verticesToGetParameters.put(modifierId, new ImmutablePair<>(GraphPropertyEnum.USERID, JsonParseFlagEnum.NoParse)); - verticesToGetParameters.put(ownerId, new ImmutablePair<>(GraphPropertyEnum.USERID, JsonParseFlagEnum.NoParse)); - 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; - return versionParts[0] + VERSION_DELIMETER + minorVersion; - } - - private Integer getMinorVersion(String version) { - String[] versionParts = version.split(VERSION_DELIMETER_REGEXP); - return Integer.parseInt(versionParts[1]); - } - - private Integer getMajorVersion(String version) { - String[] versionParts = version.split(VERSION_DELIMETER_REGEXP); - return Integer.parseInt(versionParts[0]); - } - - private boolean isFirstCheckoutAfterCertification(String version) { - if (Integer.parseInt(version.split(VERSION_DELIMETER_REGEXP)[0]) != 0 && Integer.parseInt(version.split(VERSION_DELIMETER_REGEXP)[1]) == 1) { - return true; - } - return false; - } - - 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; - GraphVertex modifier = null; - GraphVertex owner; - try { - Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId)); - if (getVerticesRes.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value())); - } - if (result == null) { - toscaElement = getVerticesRes.left().value().get(toscaElementId); - modifier = getVerticesRes.left().value().get(modifierId); - owner = getVerticesRes.left().value().get(ownerId); - - StorageOperationStatus status = handleRelationsUponForceCertification(toscaElement, modifier, owner); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to handle relations on certification request for tosca element {}. Status is {}. ", toscaElement.getUniqueId(), status); - } - } - if (result == null) { - LifecycleStateEnum nextState = LifecycleStateEnum.CERTIFIED; - - toscaElement.addMetadataProperty(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - toscaElement.addMetadataProperty(GraphPropertyEnum.VERSION, getNextCertifiedVersion(currVersion)); - - resultUpdate = updateToscaElementVertexMetadataPropertiesAndJson(toscaElement); - if (resultUpdate.isRight()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to set lifecycle for tosca elememt {} to state {}, error: {}", toscaElement.getUniqueId(), nextState, resultUpdate.right().value()); - result = Either.right(resultUpdate.right().value()); - } - } - if (result == null) { - ToscaElementOperation operation = getToscaElementOperation(toscaElement.getLabel()); - result = operation.getToscaElement(toscaElement.getUniqueId()); - } - return result; - - } catch (Exception e) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during request certification tosca element {}. {}", toscaElementId, e.getMessage()); - } - return result; - } - - private StorageOperationStatus handleRelationsUponForceCertification(GraphVertex toscaElement, GraphVertex modifier, GraphVertex owner) { - - StorageOperationStatus result = null; - TitanOperationStatus status = titanDao.replaceEdgeLabel(owner.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE); - if (status != TitanOperationStatus.OK) { - result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - if (result == null) { - Map<EdgePropertyEnum, Object> properties = new EnumMap<>(EdgePropertyEnum.class); - properties.put(EdgePropertyEnum.STATE, LifecycleStateEnum.CERTIFIED); - status = titanDao.createEdge(modifier, toscaElement, EdgeLabelEnum.STATE, properties); - if (status != TitanOperationStatus.OK) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "failed to create edge. Status is {}", status); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - } - if (result == null) { - result = StorageOperationStatus.OK; - } - return result; - } - - 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 (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 StorageOperationStatus.OK; - } + public static final String VERSION_DELIMITER = "."; + public static final String VERSION_DELIMITER_REGEXP = "\\."; + + private static final Logger log = Logger.getLogger(ToscaElementLifecycleOperation.class); + + /** + * Performs changing a lifecycle state of tosca element from "checked out" or "ready for certification" to "checked in" + * + * @param currState + * @param toscaElementId + * @param modifierId + * @param ownerId + * @return + */ + public Either<ToscaElement, StorageOperationStatus> checkinToscaELement(LifecycleStateEnum currState, String toscaElementId, String modifierId, String ownerId) { + Either<GraphVertex, StorageOperationStatus> updateResult = null; + Either<ToscaElement, StorageOperationStatus> result = null; + Map<String, GraphVertex> vertices = null; + ToscaElementOperation operation; + try { + Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForCheckin(toscaElementId, modifierId, ownerId)); + if (getVerticesRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId); + updateResult = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value())); + } else { + vertices = getVerticesRes.left().value(); + updateResult = checkinToscaELement(currState, vertices.get(toscaElementId), vertices.get(ownerId), vertices.get(modifierId), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + } + if (updateResult.isLeft()) { + operation = getToscaElementOperation(vertices.get(toscaElementId).getLabel()); + result = operation.getToscaElement(updateResult.left().value().getUniqueId()); + if (result.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated tosca element {}. Status is {}", toscaElementId, result.right().value()); + } + } else { + result = Either.right(updateResult.right().value()); + } + } catch (Exception e) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during checkin of tosca element {}. {} ", toscaElementId, e.getMessage()); + } + return result; + } + + /** + * Returns vertex presenting owner of tosca element specified by uniqueId + * + * @param toscaElementId + * @return + */ + public Either<User, StorageOperationStatus> getToscaElementOwner(String toscaElementId) { + Either<User, StorageOperationStatus> result = null; + GraphVertex toscaElement = null; + Either<GraphVertex, TitanOperationStatus> getToscaElementRes = titanDao.getVertexById(toscaElementId, JsonParseFlagEnum.NoParse); + if (getToscaElementRes.isRight()) { + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getToscaElementRes.right().value())); + } + if (result == null) { + toscaElement = getToscaElementRes.left().value(); + Iterator<Vertex> vertices = toscaElement.getVertex().vertices(Direction.IN, EdgeLabelEnum.STATE.name()); + if (vertices == null || !vertices.hasNext()) { + result = Either.right(StorageOperationStatus.NOT_FOUND); + } else { + result = Either.left(convertToUser(vertices.next())); + } + } + return result; + } + + /** + * Returns vertex presenting owner of tosca element specified by uniqueId + * + * @param toscaElement + * @return + */ + public Either<User, StorageOperationStatus> getToscaElementOwner(GraphVertex toscaElement) { + Either<User, StorageOperationStatus> result = null; + Iterator<Vertex> vertices = toscaElement.getVertex().vertices(Direction.IN, EdgeLabelEnum.STATE.name()); + if (vertices == null || !vertices.hasNext()) { + result = Either.right(StorageOperationStatus.NOT_FOUND); + } else { + result = Either.left(convertToUser(vertices.next())); + } + return result; + } + + /** + * Performs checkout of a tosca element + * + * @param toscaElementId + * @param modifierId + * @param ownerId + * @return + */ + public Either<ToscaElement, StorageOperationStatus> checkoutToscaElement(String toscaElementId, String modifierId, String ownerId) { + Either<ToscaElement, StorageOperationStatus> result = null; + Map<String, GraphVertex> vertices = null; + try { + Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForCheckout(toscaElementId, modifierId, ownerId)); + if (getVerticesRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value())); + } + if (result == null) { + vertices = getVerticesRes.left().value(); + // update previous component if not certified + StorageOperationStatus status = updatePreviousVersion(vertices.get(toscaElementId), vertices.get(ownerId)); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update vertex with id {} . Status is {}. ", status); + result = Either.right(status); + } + } + if (result == null) { + result = cloneToscaElementForCheckout(vertices.get(toscaElementId), vertices.get(modifierId)); + if (result.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to checkout tosca element {}. Status is {} ", toscaElementId, result.right().value()); + } + + } + } catch (Exception e) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during checkout tosca element {}. {}", toscaElementId, e.getMessage()); + } + return result; + } + + /** + * Performs undo checkout for tosca element + * + * @param toscaElementId + * @return + */ + public Either<ToscaElement, StorageOperationStatus> undoCheckout(String toscaElementId) { + Either<ToscaElement, StorageOperationStatus> result = null; + 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(log, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getToscaElementRes.right().value())); + } + GraphVertex currVersionV = getToscaElementRes.left().value(); + if (result == null && hasPreviousVersion(currVersionV)) { + // find previous version + nextVersionComponentIter = currVersionV.getVertex().edges(Direction.IN, EdgeLabelEnum.VERSION.name()); + if (nextVersionComponentIter == null || !nextVersionComponentIter.hasNext()) { + CommonUtility.addRecordToLog(log, 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) { + preVersionVertex = nextVersionComponentIter.next().outVertex(); + StorageOperationStatus updateOldResourceResult = updateOldToscaElementBeforeUndoCheckout(preVersionVertex); + if (updateOldResourceResult != StorageOperationStatus.OK) { + result = Either.right(updateOldResourceResult); + } + } + } + if (result == null) { + StorageOperationStatus updateCatalogRes = updateEdgeToCatalogRootByUndoCheckout((TitanVertex) preVersionVertex, currVersionV); + if (updateCatalogRes != StorageOperationStatus.OK) { + return Either.right(updateCatalogRes); + } + operation = getToscaElementOperation(currVersionV.getLabel()); + result = operation.deleteToscaElement(currVersionV); + } + } catch (Exception e) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during undo checkout tosca element {}. {}", toscaElementId, e.getMessage()); + } + return result; + } + + private boolean hasPreviousVersion(GraphVertex toscaElementVertex) { + boolean hasPreviousVersion = true; + String version = (String) toscaElementVertex.getMetadataProperty(GraphPropertyEnum.VERSION); + if (StringUtils.isEmpty(version) || version.equals("0.1")) + hasPreviousVersion = false; + return hasPreviousVersion; + } + + /** + * Performs request certification for tosca element + * + * @param toscaElementId + * @param modifierId + * @param ownerId + * @return + */ + public Either<ToscaElement, StorageOperationStatus> requestCertificationToscaElement(String toscaElementId, String modifierId, String ownerId) { + Either<GraphVertex, StorageOperationStatus> resultUpdate = null; + Either<ToscaElement, StorageOperationStatus> result = null; + GraphVertex toscaElement = null; + GraphVertex modifier = null; + GraphVertex owner; + try { + Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId)); + if (getVerticesRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value())); + } + if (result == null) { + toscaElement = getVerticesRes.left().value().get(toscaElementId); + modifier = getVerticesRes.left().value().get(modifierId); + owner = getVerticesRes.left().value().get(ownerId); + + StorageOperationStatus status = handleRelationsUponRequestForCertification(toscaElement, modifier, owner); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to handle relations on certification request for tosca element {}. Status is {}. ", toscaElement.getUniqueId(), status); + } + } + if (result == null) { + LifecycleStateEnum nextState = LifecycleStateEnum.READY_FOR_CERTIFICATION; + + toscaElement.addMetadataProperty(GraphPropertyEnum.STATE, nextState.name()); + toscaElement.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); + + resultUpdate = updateToscaElementVertexMetadataPropertiesAndJson(toscaElement); + if (resultUpdate.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to set lifecycle for tosca elememt {} to state {}, error: {}", toscaElement.getUniqueId(), nextState, resultUpdate.right().value()); + result = Either.right(resultUpdate.right().value()); + } + } + if (result == null) { + ToscaElementOperation operation = getToscaElementOperation(toscaElement.getLabel()); + result = operation.getToscaElement(toscaElement.getUniqueId()); + } + return result; + + } catch (Exception e) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during request certification tosca element {}. {}", toscaElementId, e.getMessage()); + } + return result; + } + + /** + * Starts certification of tosca element + * + * @param toscaElementId + * @param modifierId + * @param ownerId + * @return + */ + public Either<ToscaElement, StorageOperationStatus> startCertificationToscaElement(String toscaElementId, String modifierId, String ownerId) { + Either<ToscaElement, StorageOperationStatus> result = null; + Either<GraphVertex, StorageOperationStatus> resultUpdate = null; + GraphVertex toscaElement = null; + GraphVertex modifier = null; + GraphVertex owner; + try { + Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId)); + if (getVerticesRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value())); + } + if (result == null) { + toscaElement = getVerticesRes.left().value().get(toscaElementId); + modifier = getVerticesRes.left().value().get(modifierId); + owner = getVerticesRes.left().value().get(ownerId); + + StorageOperationStatus status = handleRelationsUponCertification(toscaElement, modifier, owner); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to handle relations during certification of tosca element {}. Status is {}. ", toscaElement.getUniqueId(), status); + } + } + if (result == null) { + LifecycleStateEnum nextState = LifecycleStateEnum.CERTIFICATION_IN_PROGRESS; + + toscaElement.addMetadataProperty(GraphPropertyEnum.STATE, nextState.name()); + toscaElement.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); + + resultUpdate = updateToscaElementVertexMetadataPropertiesAndJson(toscaElement); + if (resultUpdate.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Couldn't set lifecycle for component {} to state {}, error: {}", toscaElement.getUniqueId(), nextState, resultUpdate.right().value()); + result = Either.right(resultUpdate.right().value()); + } + } + if (result == null) { + ToscaElementOperation operation = getToscaElementOperation(toscaElement.getLabel()); + result = operation.getToscaElement(toscaElement.getUniqueId()); + } + } catch (Exception e) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during start certification tosca element {}. {}", toscaElementId, e.getMessage()); + } + return result; + } + + public Either<ToscaElement, StorageOperationStatus> certifyToscaElement(String toscaElementId, String modifierId, String ownerId) { + Either<ToscaElement, StorageOperationStatus> result = null; + Either<GraphVertex, StorageOperationStatus> cloneRes = null; + GraphVertex toscaElement = null; + GraphVertex modifier = null; + GraphVertex certifiedToscaElement = null; + Integer majorVersion = null; + + StorageOperationStatus status; + try { + Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId)); + if (getVerticesRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value())); + } + if (result == null) { + toscaElement = getVerticesRes.left().value().get(toscaElementId); + modifier = getVerticesRes.left().value().get(modifierId); + majorVersion = getMajorVersion((String) toscaElement.getMetadataProperty(GraphPropertyEnum.VERSION)); + status = handleRelationsOfPreviousToscaElementBeforeCertifying(toscaElement, modifier, majorVersion); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to handle relations of previous tosca element before certifying {}. Status is {}. ", toscaElement.getUniqueId(), status); + } + } + if (result == null) { + cloneRes = cloneToscaElementForCertify(toscaElement, modifier, majorVersion); + if (cloneRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to clone tosca element during certification. "); + result = Either.right(cloneRes.right().value()); + } + } + if (result == null) { + certifiedToscaElement = cloneRes.left().value(); + status = handleRelationsOfNewestCertifiedToscaElement(toscaElement, certifiedToscaElement); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to handle relations of newest certified tosca element {}. Status is {}. ", certifiedToscaElement.getUniqueId(), status); + } + } + if (result == null) { + return getToscaElementOperation(toscaElement.getLabel()).getToscaElement(certifiedToscaElement.getUniqueId()); + } + } catch (Exception e) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during certification tosca element {}. {}", toscaElementId, e.getMessage()); + } + return result; + } + + /** + * Deletes (marks as deleted) all tosca elements according received name and uuid + * + * @param vertexType + * @param componentType + * @param componentName + * @param uuid + * @return + */ + public Either<Boolean, StorageOperationStatus> deleteOldToscaElementVersions(VertexTypeEnum vertexType, ComponentTypeEnum componentType, String componentName, String uuid) { + + Either<Boolean, StorageOperationStatus> result = null; + ToscaElementOperation operation = getToscaElementOperation(componentType); + + try { + Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class); + properties.put(GraphPropertyEnum.UUID, uuid); + properties.put(GraphPropertyEnum.NAME, componentName); + Either<List<GraphVertex>, TitanOperationStatus> getToscaElementsRes = titanDao.getByCriteria(vertexType, properties, JsonParseFlagEnum.ParseMetadata); + if (getToscaElementsRes.isRight()) { + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getToscaElementsRes.right().value())); + } + if (result == null) { + result = markToscaElementsAsDeleted(operation, getToscaElementsRes.left().value()); + } + if (result == null) { + result = Either.left(true); + } + } catch (Exception e) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during deleteng all tosca elements by UUID {} and name {}. {} ", uuid, componentName, e.getMessage()); + } + return result; + } + + /** + * Performs cancelation or failure of certification for received tosca element + * + * @param toscaElementId + * @param modifierId + * @param ownerId + * @param nextState + * @return + */ + public Either<ToscaElement, StorageOperationStatus> cancelOrFailCertification(String toscaElementId, String modifierId, String ownerId, LifecycleStateEnum nextState) { + Either<ToscaElement, StorageOperationStatus> result = null; + StorageOperationStatus status; + ToscaElementOperation operation = null; + GraphVertex toscaElement = null; + GraphVertex modifier = null; + try { + Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId)); + if (getVerticesRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value())); + } + if (result == null) { + toscaElement = getVerticesRes.left().value().get(toscaElementId); + modifier = getVerticesRes.left().value().get(modifierId); + operation = getToscaElementOperation(toscaElement.getLabel()); + toscaElement.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); + toscaElement.setJsonMetadataField(JsonPresentationFields.USER_ID_LAST_UPDATER, modifier.getUniqueId()); + toscaElement.addMetadataProperty(GraphPropertyEnum.STATE, nextState.name()); + + Either<GraphVertex, TitanOperationStatus> updateVertexRes = titanDao.updateVertex(toscaElement); + if (updateVertexRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update vertex {} . Status is {}. ", toscaElementId, updateVertexRes.right().value()); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateVertexRes.right().value())); + } + } + if (result == null) { + // cancel certification process + status = handleRelationsUponCancelCertification(toscaElement, nextState); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to handle relations upon cancel certification {}. Status is {}. ", toscaElement.getUniqueId(), status); + } + } + if (result == null) { + // fail certification + status = handleRelationsUponFailCertification(toscaElement, nextState); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to handle relations upon fail certification {}. Status is {}. ", toscaElement.getUniqueId(), status); + } + } + if (result == null) { + result = operation.getToscaElement(toscaElementId); + } + } catch (Exception e) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during cancel or fail certification of tosca element {}. {}. ", toscaElementId, e.getMessage()); + } + return result; + } + + public Either<GraphVertex, TitanOperationStatus> findUser(String userId) { + return findUserVertex(userId); + } + + private Either<Boolean, StorageOperationStatus> markToscaElementsAsDeleted(ToscaElementOperation operation, List<GraphVertex> toscaElements) { + Either<Boolean, StorageOperationStatus> result = Either.left(true); + for (GraphVertex resourceToDelete : toscaElements) { + if (!((String) resourceToDelete.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals(LifecycleStateEnum.CERTIFIED.name())) { + Either<GraphVertex, StorageOperationStatus> deleteElementRes = operation.markComponentToDelete(resourceToDelete); + if (deleteElementRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete tosca element {}. Status is {}. ", resourceToDelete.getUniqueId(), deleteElementRes.right().value()); + result = Either.right(deleteElementRes.right().value()); + break; + } + } + } + return result; + } + + private StorageOperationStatus handleRelationsOfNewestCertifiedToscaElement(GraphVertex toscaElement, GraphVertex certifiedToscaElement) { + StorageOperationStatus result = null; + Edge foundEdge = null; + Iterator<Edge> certReqUserEdgeIter = null; + // add rfc relation to preserve follower information + // get user of certification request + certReqUserEdgeIter = toscaElement.getVertex().edges(Direction.IN, GraphEdgeLabels.LAST_STATE.name()); + if (certReqUserEdgeIter == null || !certReqUserEdgeIter.hasNext()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find rfc relation during certification clone. "); + result = StorageOperationStatus.NOT_FOUND; + } + if (result == null) { + TitanOperationStatus createVersionEdgeStatus = titanDao.createEdge(toscaElement, certifiedToscaElement, EdgeLabelEnum.VERSION, new HashMap<>()); + if (createVersionEdgeStatus != TitanOperationStatus.OK) { + CommonUtility.addRecordToLog(log, 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 (certReqUserEdgeIter!=null) { + while (certReqUserEdgeIter.hasNext()) { + Edge edge = certReqUserEdgeIter.next(); + if (((String) titanDao.getProperty(edge, EdgePropertyEnum.STATE)).equals(LifecycleStateEnum.READY_FOR_CERTIFICATION.name())) { + foundEdge = edge; + break; + } + + } + } + if (foundEdge == null) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find rfc relation during certification clone. "); + result = StorageOperationStatus.NOT_FOUND; + } + } + if (result == null) { + TitanOperationStatus createEdgeRes = titanDao.createEdge(foundEdge.outVertex(), certifiedToscaElement.getVertex(), EdgeLabelEnum.LAST_STATE, foundEdge); + if (createEdgeRes != TitanOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create rfc relation for component {}. status=", certifiedToscaElement.getUniqueId(), createEdgeRes); + result = DaoStatusConverter.convertTitanStatusToStorageStatus(createEdgeRes); + } + } + if (result == null) { + result = StorageOperationStatus.OK; + } + return result; + } + + private StorageOperationStatus handleRelationsUponFailCertification(GraphVertex toscaElement, LifecycleStateEnum nextState) { + StorageOperationStatus result = null; + TitanOperationStatus status = null; + Edge originEdge; + Vertex user = null; + if (nextState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN) { + // fail certification + // delete relation CERTIFICATION_IN_PROGRESS + Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class); + properties.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + + Either<Edge, TitanOperationStatus> deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.STATE, properties); + if (deleteResult.isRight()) { + status = deleteResult.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete state edge. Status is {}. ", status); + result = StorageOperationStatus.INCONSISTENCY; + } + if (result == null) { + // delete relation READY_FOR_CERTIFICATION + properties.put(GraphPropertyEnum.STATE, LifecycleStateEnum.READY_FOR_CERTIFICATION); + deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.LAST_STATE, properties); + if (deleteResult.isRight()) { + status = deleteResult.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_DELETE_LAST_STATE_EDGE_STATUS_IS, status); + result = StorageOperationStatus.INCONSISTENCY; + } + } + if (result == null) { + // delete relation NOT_CERTIFIED_CHECKIN (in order to change to STATE) + properties.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.LAST_STATE, properties); + if (deleteResult.isRight()) { + status = deleteResult.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_DELETE_LAST_STATE_EDGE_STATUS_IS, status); + result = StorageOperationStatus.INCONSISTENCY; + } + } + if (result == null) { + // create new STATE relation NOT_CERTIFIED_CHECKIN + originEdge = deleteResult.left().value(); + user = originEdge.outVertex(); + status = titanDao.createEdge(user, toscaElement.getVertex(), EdgeLabelEnum.STATE, originEdge); + if (status != TitanOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create state edge. Status is {}. ", status); + result = StorageOperationStatus.INCONSISTENCY; + } + } + if (result == null) { + // delete relation LAST_MODIFIER (in order to change tester to designer) + deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.LAST_MODIFIER, new HashMap<>()); + if (status != TitanOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create last modifier edge. Status is {}. ", status); + result = StorageOperationStatus.INCONSISTENCY; + } + } + if (result == null) { + // create new LAST_MODIFIER relation + originEdge = deleteResult.left().value(); + status = titanDao.createEdge(user, toscaElement.getVertex(), EdgeLabelEnum.LAST_MODIFIER, originEdge); + if (status != TitanOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create last modifier edge. Status is {}. ", status); + result = StorageOperationStatus.INCONSISTENCY; + } + } + } + if (result == null) { + result = StorageOperationStatus.OK; + } + return result; + } + + private StorageOperationStatus handleRelationsUponCancelCertification(GraphVertex toscaElement, LifecycleStateEnum nextState) { + StorageOperationStatus result = null; + Edge originEdge; + if (nextState == LifecycleStateEnum.READY_FOR_CERTIFICATION) { + // delete relation CERTIFICATION_IN_PROGRESS + Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class); + properties.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + Either<Edge, TitanOperationStatus> deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.STATE, properties); + + if (deleteResult.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete state edge. Status is {}. ", deleteResult.right().value()); + result = StorageOperationStatus.INCONSISTENCY; + } + if (result == null) { + // delete relation READY_FOR_CERTIFICATION (LAST_STATE) + properties.put(GraphPropertyEnum.STATE, nextState); + deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.LAST_STATE, properties); + + if (deleteResult.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_DELETE_LAST_STATE_EDGE_STATUS_IS, deleteResult.right().value()); + result = StorageOperationStatus.INCONSISTENCY; + } + } + if (result == null) { + // create relation READY_FOR_CERTIFICATION (STATE) + originEdge = deleteResult.left().value(); + TitanOperationStatus status = titanDao.createEdge(originEdge.outVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, originEdge); + if (status != TitanOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create state edge. Status is {}. ", status); + result = StorageOperationStatus.INCONSISTENCY; + } + } + if (result == null) { + result = StorageOperationStatus.OK; + } + } + return result; + } + + private StorageOperationStatus handleRelationsOfPreviousToscaElementBeforeCertifying(GraphVertex toscaElement, GraphVertex modifier, Integer majorVersion) { + StorageOperationStatus result = null; + if (majorVersion > 0) { + Either<Vertex, StorageOperationStatus> findRes = findLastCertifiedToscaElementVertex(toscaElement); + if (findRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch last certified tosca element {} . Status is {}. ", toscaElement.getMetadataProperty(GraphPropertyEnum.NAME), findRes.right().value()); + result = findRes.right().value(); + } + if (result == null) { + Vertex lastCertifiedVertex = findRes.left().value(); + Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class); + properties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, false); + TitanOperationStatus status = titanDao.updateVertexMetadataPropertiesWithJson(lastCertifiedVertex, properties); + if (status != TitanOperationStatus.OK) { + CommonUtility.addRecordToLog(log, 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) { + result = StorageOperationStatus.OK; + } + return result; + } + + private StorageOperationStatus handleRelationsUponRequestForCertification(GraphVertex toscaElement, GraphVertex modifier, GraphVertex owner) { + TitanOperationStatus status; + StorageOperationStatus result = null; + + if (((String) toscaElement.getMetadataProperty(GraphPropertyEnum.STATE)).equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { + // remove CHECKOUT relation + Either<Edge, TitanOperationStatus> deleteRes = titanDao.deleteEdge(owner, toscaElement, EdgeLabelEnum.STATE); + if (deleteRes.isRight()) { + status = deleteRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete edge. Status is {}. ", status); + result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); + } + if (result == null) { + // create CHECKIN relation + Map<EdgePropertyEnum, Object> properties = new EnumMap<>(EdgePropertyEnum.class); + properties.put(EdgePropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); + status = titanDao.createEdge(modifier.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.LAST_STATE, properties); + if (status != TitanOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge. Status is {}", status); + result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); + } + } + } else { + status = titanDao.replaceEdgeLabel(owner.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE); + if (status != TitanOperationStatus.OK) { + result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); + } + } + if (result == null) { + // create RFC relation + Map<EdgePropertyEnum, Object> properties = new EnumMap<>(EdgePropertyEnum.class); + properties.put(EdgePropertyEnum.STATE, LifecycleStateEnum.READY_FOR_CERTIFICATION); + status = titanDao.createEdge(modifier.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, properties); + if (status != TitanOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge. Status is {}", status); + result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); + } + } + if (result == null) { + result = StorageOperationStatus.OK; + } + return result; + } + + private StorageOperationStatus handleRelationsUponCertification(GraphVertex toscaElement, GraphVertex modifier, GraphVertex owner) { + + StorageOperationStatus result = null; + TitanOperationStatus status = titanDao.replaceEdgeLabel(owner.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE); + if (status != TitanOperationStatus.OK) { + result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); + } + if (result == null) { + Map<EdgePropertyEnum, Object> properties = new EnumMap<>(EdgePropertyEnum.class); + properties.put(EdgePropertyEnum.STATE, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); + status = titanDao.createEdge(modifier, toscaElement, EdgeLabelEnum.STATE, properties); + if (status != TitanOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "failed to create edge. Status is {}", status); + result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); + } + } + if (result == null) { + Either<GraphVertex, StorageOperationStatus> updateRelationsRes = updateLastModifierEdge(toscaElement, owner, modifier); + if (updateRelationsRes.isRight()) { + result = updateRelationsRes.right().value(); + } + } + if (result == null) { + result = StorageOperationStatus.OK; + } + return result; + } + + private Either<Vertex, StorageOperationStatus> findLastCertifiedToscaElementVertex(GraphVertex toscaElement) { + return findLastCertifiedToscaElementVertexRecursively(toscaElement.getVertex()); + } + + private Either<Vertex, StorageOperationStatus> findLastCertifiedToscaElementVertexRecursively(Vertex vertex) { + if (isCertifiedVersion((String) vertex.property(GraphPropertyEnum.VERSION.getProperty()).value())) { + return Either.left(vertex); + } + Iterator<Edge> edgeIter = vertex.edges(Direction.IN, EdgeLabelEnum.VERSION.name()); + if (!edgeIter.hasNext()) { + return Either.right(StorageOperationStatus.NOT_FOUND); + } + return findLastCertifiedToscaElementVertexRecursively(edgeIter.next().outVertex()); + } + + private boolean isCertifiedVersion(String version) { + String[] versionParts = version.split(VERSION_DELIMITER_REGEXP); + if (Integer.parseInt(versionParts[0]) > 0 && Integer.parseInt(versionParts[1]) == 0) { + return true; + } + return false; + } + + private StorageOperationStatus updateOldToscaElementBeforeUndoCheckout(Vertex previousVersionToscaElement) { + + StorageOperationStatus result = StorageOperationStatus.OK; + String previousVersion = (String) previousVersionToscaElement.property(GraphPropertyEnum.VERSION.getProperty()).value(); + if (!previousVersion.endsWith(".0")) { + try { + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update vertex of previous version of tosca element", previousVersionToscaElement.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty())); + + Map<String, Object> propertiesToUpdate = new HashMap<>(); + propertiesToUpdate.put(GraphPropertyEnum.IS_HIGHEST_VERSION.getProperty(), true); + 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.toJson(jsonMetadataMap)); + + titanDao.setVertexProperties(previousVersionToscaElement, propertiesToUpdate); + + Iterator<Edge> edgesIter = previousVersionToscaElement.edges(Direction.IN, EdgeLabelEnum.LAST_STATE.name()); + if (!edgesIter.hasNext()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch last modifier vertex for tosca element {}. ", previousVersionToscaElement.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty())); + result = StorageOperationStatus.NOT_FOUND; + } else { + Edge lastStateEdge = edgesIter.next(); + Vertex lastModifier = lastStateEdge.outVertex(); + TitanOperationStatus replaceRes = titanDao.replaceEdgeLabel(lastModifier, previousVersionToscaElement, lastStateEdge, EdgeLabelEnum.LAST_STATE, EdgeLabelEnum.STATE); + if (replaceRes != TitanOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to replace label from {} to {}. status = {}", EdgeLabelEnum.LAST_STATE, EdgeLabelEnum.STATE, replaceRes); + result = StorageOperationStatus.INCONSISTENCY; + if (replaceRes != TitanOperationStatus.INVALID_ID) { + result = DaoStatusConverter.convertTitanStatusToStorageStatus(replaceRes); + } + } + + } + } catch (Exception e) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during update previous tosca element {} before undo checkout. {} ", e.getMessage()); + } + } + return result; + } + + private StorageOperationStatus updatePreviousVersion(GraphVertex toscaElementVertex, GraphVertex ownerVertex) { + StorageOperationStatus result = null; + String ownerId = (String) ownerVertex.getMetadataProperty(GraphPropertyEnum.USERID); + String toscaElementId = toscaElementVertex.getUniqueId(); + if (!toscaElementVertex.getMetadataProperty(GraphPropertyEnum.STATE).equals(LifecycleStateEnum.CERTIFIED.name())) { + toscaElementVertex.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION, false); + Either<GraphVertex, TitanOperationStatus> updateVertexRes = titanDao.updateVertex(toscaElementVertex); + if (updateVertexRes.isRight()) { + TitanOperationStatus titatStatus = updateVertexRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update tosca element vertex {}. Status is {}", toscaElementVertex.getUniqueId(), titatStatus); + result = DaoStatusConverter.convertTitanStatusToStorageStatus(titatStatus); + } + Either<Edge, TitanOperationStatus> deleteEdgeRes = null; + if (result == null) { + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to replace edge with label {} to label {} from {} to {}. ", EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE, ownerId, toscaElementId); + + deleteEdgeRes = titanDao.deleteEdge(ownerVertex, toscaElementVertex, EdgeLabelEnum.STATE); + if (deleteEdgeRes.isRight()) { + TitanOperationStatus titanStatus = deleteEdgeRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete edge with label {} from {} to {}. Status is {} ", EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE, ownerId, toscaElementId, titanStatus); + if (!titanStatus.equals(TitanOperationStatus.INVALID_ID)) { + result = DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus); + } else { + result = StorageOperationStatus.INCONSISTENCY; + } + } + } + if (result == null) { + TitanOperationStatus createEdgeRes = titanDao.createEdge(ownerVertex.getVertex(), toscaElementVertex.getVertex(), EdgeLabelEnum.LAST_STATE, deleteEdgeRes.left().value()); + if (createEdgeRes != TitanOperationStatus.OK) { + result = DaoStatusConverter.convertTitanStatusToStorageStatus(createEdgeRes); + } + } + } + if (result == null) { + result = StorageOperationStatus.OK; + } + return result; + } + + private Either<ToscaElement, StorageOperationStatus> cloneToscaElementForCheckout(GraphVertex toscaElementVertex, GraphVertex modifierVertex) { + + Either<ToscaElement, StorageOperationStatus> result = null; + Either<GraphVertex, StorageOperationStatus> cloneResult = null; + ToscaElementOperation operation = getToscaElementOperation(toscaElementVertex.getLabel()); + // 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(); + String fetchedVersion = (String) nextVersionVertex.property(GraphPropertyEnum.VERSION.getProperty()).value(); + String fetchedName = (String) nextVersionVertex.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty()).value(); + CommonUtility.addRecordToLog(log, 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); + } + if (result == null) { + toscaElementVertex.getOrSetDefaultInstantiationTypeForToscaElementJson(); + cloneResult = operation.cloneToscaElement(toscaElementVertex, cloneGraphVertexForCheckout(toscaElementVertex, modifierVertex), modifierVertex); + if (cloneResult.isRight()) { + result = Either.right(cloneResult.right().value()); + } + } + GraphVertex clonedVertex = null; + if (result == null) { + clonedVertex = cloneResult.left().value(); + TitanOperationStatus status = titanDao.createEdge(toscaElementVertex.getVertex(), cloneResult.left().value().getVertex(), EdgeLabelEnum.VERSION, new HashMap<>()); + if (status != TitanOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge with label {} from vertex {} to tosca element vertex {} on graph. Status is {}. ", EdgeLabelEnum.VERSION, + toscaElementVertex.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), cloneResult.left().value().getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + } + 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.TOPOLOGY_TEMPLATE) { + result = handleFixTopologyTemplate(toscaElementVertex, result, operation, clonedVertex, toscaElement); + } + } + + return result; + } + + private Either<ToscaElement, StorageOperationStatus> handleFixTopologyTemplate(GraphVertex toscaElementVertex, Either<ToscaElement, StorageOperationStatus> result, ToscaElementOperation operation, GraphVertex clonedVertex, + ToscaElement toscaElement) { + TopologyTemplate topologyTemplate = (TopologyTemplate) toscaElement; + Map<String, MapPropertiesDataDefinition> instInputs = topologyTemplate.getInstInputs(); + Map<String, MapGroupsDataDefinition> instGroups = topologyTemplate.getInstGroups(); + Map<String, MapArtifactDataDefinition> instArtifactsMap = topologyTemplate.getInstanceArtifacts(); + Map<String, ToscaElement> origCompMap = new HashMap<>(); + if (instInputs == null) { + instInputs = new HashMap<>(); + } + if (instGroups == null) { + instGroups = new HashMap<>(); + } + if (instArtifactsMap == null) { + instArtifactsMap = new HashMap<>(); + } + Map<String, ComponentInstanceDataDefinition> instancesMap = topologyTemplate.getComponentInstances(); + boolean isAddInstGroup = instGroups == null || instGroups.isEmpty(); + boolean needUpdateComposition = false; + + if (instancesMap != null && !instancesMap.isEmpty()) { + for (ComponentInstanceDataDefinition vfInst : instancesMap.values()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "vfInst name is {} . OriginType {}. ", vfInst.getName(), vfInst.getOriginType()); + if (vfInst.getOriginType().name().equals(OriginTypeEnum.VF.name())) { + collectInstanceInputAndGroups(instInputs, instGroups, instArtifactsMap, origCompMap, isAddInstGroup, vfInst, clonedVertex); + } + needUpdateComposition = needUpdateComposition || fixToscaComponentName(vfInst, origCompMap); + if (needUpdateComposition) { + instancesMap.put(vfInst.getUniqueId(), vfInst); + } + } + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "before add to graph instInputs {} instGroups {} needUpdateComposition {}", instInputs, instGroups, needUpdateComposition); + if (!instInputs.isEmpty()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "before add inst inputs {} ", instInputs == null ? 0 : instInputs.size()); + GraphVertex toscaDataVertex = null; + Either<GraphVertex, TitanOperationStatus> instInpVertexEither = titanDao.getChildVertex(toscaElementVertex, EdgeLabelEnum.INST_INPUTS, JsonParseFlagEnum.ParseJson); + if (instInpVertexEither.isLeft()) { + toscaDataVertex = instInpVertexEither.left().value(); + } + + StorageOperationStatus status = handleToscaData(clonedVertex, VertexTypeEnum.INST_INPUTS, EdgeLabelEnum.INST_INPUTS, toscaDataVertex, instInputs); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update instance inputs . Status is {}. ", status); + result = Either.right(status); + return result; + } + + } + if (!instGroups.isEmpty()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "before add inst groups {} ", instGroups == null ? 0 : instGroups.size()); + GraphVertex toscaDataVertex = null; + Either<GraphVertex, TitanOperationStatus> instGrVertexEither = titanDao.getChildVertex(toscaElementVertex, EdgeLabelEnum.INST_GROUPS, JsonParseFlagEnum.ParseJson); + if (instGrVertexEither.isLeft()) { + toscaDataVertex = instGrVertexEither.left().value(); + } + + StorageOperationStatus status = handleToscaData(clonedVertex, VertexTypeEnum.INST_GROUPS, EdgeLabelEnum.INST_GROUPS, toscaDataVertex, instGroups); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update instance group . Status is {}. ", status); + result = Either.right(status); + return result; + } + + } + if (needUpdateComposition) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "before update Instances "); + Map<String, CompositionDataDefinition> jsonComposition = (Map<String, CompositionDataDefinition>) clonedVertex.getJson(); + CompositionDataDefinition compositionDataDefinition = jsonComposition.get(JsonConstantKeysEnum.COMPOSITION.getValue()); + compositionDataDefinition.setComponentInstances(instancesMap); + Either<GraphVertex, TitanOperationStatus> updateElement = titanDao.updateVertex(clonedVertex); + if (updateElement.isRight()) { + TitanOperationStatus status = updateElement.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update instances on metadata vertex . Status is {}. ", status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + return result; + } + } + + result = operation.getToscaElement(clonedVertex.getUniqueId()); + + } else { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "RI map empty on component {}", toscaElement.getUniqueId()); + } + return result; + } + + // TODO remove after jsonModelMigration + public boolean resolveToscaComponentName(ComponentInstanceDataDefinition vfInst, Map<String, ToscaElement> origCompMap) { + return fixToscaComponentName(vfInst, origCompMap); + } + + private boolean fixToscaComponentName(ComponentInstanceDataDefinition vfInst, Map<String, ToscaElement> origCompMap) { + if (vfInst.getToscaComponentName() == null || vfInst.getToscaComponentName().isEmpty()) { + String ciUid = vfInst.getUniqueId(); + String origCompUid = vfInst.getComponentUid(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "fixToscaComponentName:: Ri id {} . origin component id is {}. type is{} ", ciUid, origCompUid, vfInst.getOriginType()); + ToscaElement origComp = null; + if (!origCompMap.containsKey(origCompUid)) { + Either<ToscaElement, StorageOperationStatus> origCompEither; + if (vfInst.getOriginType() == null || vfInst.getOriginType().name().equals(OriginTypeEnum.VF.name())) { + origCompEither = topologyTemplateOperation.getToscaElement(origCompUid); + } else { + origCompEither = nodeTypeOperation.getToscaElement(origCompUid); + } + if (origCompEither.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find orig component {} . Status is {}. ", origCompEither.right().value()); + return false; + } + origComp = origCompEither.left().value(); + origCompMap.put(origCompUid, origComp); + } else { + origComp = origCompMap.get(origCompUid); + } + String toscaName = (String) origComp.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Origin component id is {}. toscaName {}", origCompUid, toscaName); + vfInst.setToscaComponentName(toscaName); + return true; + } + return false; + } + + private void collectInstanceInputAndGroups(Map<String, MapPropertiesDataDefinition> instInputs, Map<String, MapGroupsDataDefinition> instGroups, Map<String, MapArtifactDataDefinition> instArtifactsMap, Map<String, ToscaElement> origCompMap, + boolean isAddInstGroup, ComponentInstanceDataDefinition vfInst, GraphVertex clonedVertex) { + String ciUid = vfInst.getUniqueId(); + String origCompUid = vfInst.getComponentUid(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "collectInstanceInputAndGroups:: Ri id {} . origin component id is {}. ", ciUid, origCompUid); + TopologyTemplate origComp = null; + if (!origCompMap.containsKey(origCompUid)) { + Either<ToscaElement, StorageOperationStatus> origCompEither = topologyTemplateOperation.getToscaElement(origCompUid); + if (origCompEither.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find orig component {} . Status is {}. ", origCompEither.right().value()); + return; + } + origComp = (TopologyTemplate) origCompEither.left().value(); + origCompMap.put(origCompUid, origComp); + } else { + origComp = (TopologyTemplate) origCompMap.get(origCompUid); + } + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Orig component {}. ", origComp.getUniqueId()); + + Map<String, PropertyDataDefinition> origInputs = origComp.getInputs(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Orig component inputs size {}. ", origInputs == null ? 0 : origInputs.size()); + if (origInputs != null) { + if (!instInputs.containsKey(ciUid)) { + MapPropertiesDataDefinition instProperties = new MapPropertiesDataDefinition(origInputs); + instInputs.put(ciUid, instProperties); + } else { + + MapPropertiesDataDefinition instInputMap = instInputs.get(ciUid); + Map<String, PropertyDataDefinition> instProp = instInputMap.getMapToscaDataDefinition(); + origInputs.forEach((propName, propMap) -> { + if (!instProp.containsKey(propName)) { + instProp.put(propName, propMap); + } + }); + } + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "ComponentInstanseInputs {}. ", instInputs.get(ciUid)); + } + + if (isAddInstGroup) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "before create group instance. "); + List<GroupDataDefinition> filteredGroups = null; + + CommonUtility.addRecordToLog(log, 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()); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "check vf groups . Size is {} ", filteredGroups == null ? 0 : filteredGroups.size()); + } + CommonUtility.addRecordToLog(log, 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(log, 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) { + Map<String, ArtifactDataDefinition> instDeplArtifMap = instArifacts.getMapToscaDataDefinition(); + + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "check group dep artifacts. Size is {} ", instDeplArtifMap == null ? 0 : instDeplArtifMap.values().size()); + Map<String, GroupInstanceDataDefinition> groupInstanceToCreate = new HashMap<>(); + for (GroupDataDefinition group : filteredGroups) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "create new groupInstance {} ", group.getName()); + GroupInstanceDataDefinition groupInstance = buildGroupInstanceDataDefinition(group, vfInst, instDeplArtifMap); + List<String> artifactsUid = new ArrayList<>(); + List<String> artifactsId = new ArrayList<>(); + if (instDeplArtifMap!=null) { + for (ArtifactDataDefinition artifact : instDeplArtifMap.values()) { + 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); + groupInstance.setGroupInstanceArtifactsUuid(artifactsUid); + groupInstanceToCreate.put(groupInstance.getName(), groupInstance); + } + if (MapUtils.isNotEmpty(groupInstanceToCreate)) { + instGroups.put(vfInst.getUniqueId(), new MapGroupsDataDefinition(groupInstanceToCreate)); + + } + } + } + } + } + + private GraphVertex cloneGraphVertexForCheckout(GraphVertex toscaElementVertex, GraphVertex modifierVertex) { + GraphVertex nextVersionToscaElementVertex = new GraphVertex(); + String uniqueId = UniqueIdBuilder.buildComponentUniqueId(); + Map<GraphPropertyEnum, Object> metadataProperties = new HashMap<>(toscaElementVertex.getMetadataProperties()); + nextVersionToscaElementVertex.setMetadataProperties(metadataProperties); + nextVersionToscaElementVertex.setUniqueId(uniqueId); + nextVersionToscaElementVertex.setLabel(toscaElementVertex.getLabel()); + nextVersionToscaElementVertex.setType(toscaElementVertex.getType()); + + nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, uniqueId); + nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE, nextVersionToscaElementVertex.getType().name()); + String nextVersion = getNextVersion((String) toscaElementVertex.getMetadataProperty(GraphPropertyEnum.VERSION)); + if (isFirstCheckoutAfterCertification(nextVersion)) { + nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.UUID, IdBuilderUtils.generateUUID()); + } + nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.VERSION, nextVersion); + nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()); + nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + + if (toscaElementVertex.getType() == ComponentTypeEnum.SERVICE && toscaElementVertex.getMetadataProperty(GraphPropertyEnum.STATE).equals(LifecycleStateEnum.CERTIFIED.name())) { + nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); + } + if (!MapUtils.isEmpty(toscaElementVertex.getMetadataJson())) { + nextVersionToscaElementVertex.setMetadataJson(new HashMap<>(toscaElementVertex.getMetadataJson())); + nextVersionToscaElementVertex.updateMetadataJsonWithCurrentMetadataProperties(); + } + long currTime = System.currentTimeMillis(); + nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.CREATION_DATE, currTime); + nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, currTime); + nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.USER_ID_CREATOR, modifierVertex.getUniqueId()); + nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.USER_ID_LAST_UPDATER, modifierVertex.getUniqueId()); + if (toscaElementVertex.getType() == ComponentTypeEnum.SERVICE) { + nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.CONFORMANCE_LEVEL, ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel()); + } + + if (!MapUtils.isEmpty(toscaElementVertex.getJson())) { + nextVersionToscaElementVertex.setJson(new HashMap<String, ToscaDataDefinition>(toscaElementVertex.getJson())); + } + return nextVersionToscaElementVertex; + } + + private Either<GraphVertex, StorageOperationStatus> cloneToscaElementForCertify(GraphVertex toscaElementVertex, GraphVertex modifierVertex, Integer majorVersion) { + Either<GraphVertex, StorageOperationStatus> result; + Either<List<GraphVertex>, StorageOperationStatus> deleteResult = null; + GraphVertex clonedToscaElement = null; + result = getToscaElementOperation(toscaElementVertex.getLabel()).cloneToscaElement(toscaElementVertex, cloneGraphVertexForCertify(toscaElementVertex, modifierVertex, majorVersion), modifierVertex); + if (result.isRight()) { + CommonUtility.addRecordToLog(log, 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(log, LogLevelEnum.DEBUG, "Failed to delete all previous npt certified versions of tosca element {}. Status is {}. ", toscaElementVertex.getUniqueId(), deleteResult.right().value()); + result = Either.right(deleteResult.right().value()); + } + } + if (result.isLeft()) { + result = handlePreviousVersionRelation(clonedToscaElement, deleteResult.left().value(), majorVersion); + } + return result; + } + + private Either<GraphVertex, StorageOperationStatus> handlePreviousVersionRelation(GraphVertex clonedToscaElement, List<GraphVertex> deletedVersions, Integer majorVersion) { + Either<GraphVertex, StorageOperationStatus> result = null; + Vertex previousCertifiedToscaElement = null; + if (majorVersion > 0) { + List<GraphVertex> firstMinorVersionVertex = deletedVersions.stream().filter(gv -> getMinorVersion((String) gv.getMetadataProperty(GraphPropertyEnum.VERSION)) == 1).collect(Collectors.toList()); + + if (CollectionUtils.isEmpty(firstMinorVersionVertex)) { + result = Either.right(StorageOperationStatus.NOT_FOUND); + } else { + previousCertifiedToscaElement = getPreviousCertifiedToscaElement(firstMinorVersionVertex.get(0)); + if (previousCertifiedToscaElement == null) { + result = Either.right(StorageOperationStatus.NOT_FOUND); + } + } + if (result == null) { + TitanOperationStatus status = titanDao.createEdge(previousCertifiedToscaElement, clonedToscaElement.getVertex(), EdgeLabelEnum.VERSION, new HashMap<>()); + if (status != TitanOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge with label {} from vertex {} to tosca element vertex {} on graph. Status is {}. ", EdgeLabelEnum.VERSION, + previousCertifiedToscaElement.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), clonedToscaElement.getUniqueId(), status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + } + + } + if (result == null) { + result = Either.left(clonedToscaElement); + } + return result; + } + + private Vertex getPreviousCertifiedToscaElement(GraphVertex graphVertex) { + + Iterator<Edge> edges = graphVertex.getVertex().edges(Direction.IN, EdgeLabelEnum.VERSION.name()); + if (edges.hasNext()) { + return edges.next().outVertex(); + } + return null; + } + + private Either<List<GraphVertex>, StorageOperationStatus> deleteAllPreviousNotCertifiedVersions(GraphVertex toscaElementVertex) { + Either<List<GraphVertex>, StorageOperationStatus> result = null; + + ToscaElementOperation operation = getToscaElementOperation(toscaElementVertex.getLabel()); + List<GraphVertex> previosVersions = null; + Object uuid = toscaElementVertex.getMetadataProperty(GraphPropertyEnum.UUID); + Object componentName = toscaElementVertex.getMetadataProperty(GraphPropertyEnum.NAME); + try { + Map<GraphPropertyEnum, Object> properties = new HashMap<>(); + properties.put(GraphPropertyEnum.UUID, uuid); + properties.put(GraphPropertyEnum.NAME, componentName); + Either<List<GraphVertex>, TitanOperationStatus> getToscaElementsRes = titanDao.getByCriteria(toscaElementVertex.getLabel(), properties, JsonParseFlagEnum.ParseMetadata); + if (getToscaElementsRes.isRight()) { + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getToscaElementsRes.right().value())); + } + if (result == null) { + previosVersions = getToscaElementsRes.left().value(); + Either<Boolean, StorageOperationStatus> deleteResult = markToscaElementsAsDeleted(operation, getToscaElementsRes.left().value()); + if (deleteResult.isRight()) { + result = Either.right(deleteResult.right().value()); + } + } + if (result == null) { + result = Either.left(previosVersions); + } + } catch (Exception e) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during deleteng all tosca elements by UUID {} and name {}. {} ", uuid, componentName, e.getMessage()); + } + return result; + } + + private GraphVertex cloneGraphVertexForCertify(GraphVertex toscaElementVertex, GraphVertex modifierVertex, Integer majorVersion) { + + GraphVertex nextVersionToscaElementVertex = new GraphVertex(); + String uniqueId = IdBuilderUtils.generateUniqueId(); + Map<GraphPropertyEnum, Object> metadataProperties = new HashMap<>(toscaElementVertex.getMetadataProperties()); + nextVersionToscaElementVertex.setMetadataProperties(metadataProperties); + nextVersionToscaElementVertex.setUniqueId(uniqueId); + nextVersionToscaElementVertex.setLabel(toscaElementVertex.getLabel()); + nextVersionToscaElementVertex.setType(toscaElementVertex.getType()); + + nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, uniqueId); + nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE, nextVersionToscaElementVertex.getType().name()); + nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.VERSION, (majorVersion + 1) + VERSION_DELIMITER + "0"); + nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.CREATION_DATE, System.currentTimeMillis()); + nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, null); + nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.USER_ID_CREATOR, modifierVertex.getUniqueId()); + nextVersionToscaElementVertex.setJsonMetadataField(JsonPresentationFields.USER_ID_LAST_UPDATER, modifierVertex.getUniqueId()); + + if (toscaElementVertex.getType() == ComponentTypeEnum.SERVICE && toscaElementVertex.getMetadataProperty(GraphPropertyEnum.STATE).equals(LifecycleStateEnum.CERTIFIED)) { + nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); + } + if (!MapUtils.isEmpty(toscaElementVertex.getMetadataJson())) { + nextVersionToscaElementVertex.setMetadataJson(new HashMap<>(toscaElementVertex.getMetadataJson())); + nextVersionToscaElementVertex.updateMetadataJsonWithCurrentMetadataProperties(); + } + if (!MapUtils.isEmpty(toscaElementVertex.getJson())) { + nextVersionToscaElementVertex.setJson(new HashMap<String, ToscaDataDefinition>(toscaElementVertex.getJson())); + } + return nextVersionToscaElementVertex; + } + + private ComponentParametersView buildComponentParametersViewAfterCheckin() { + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.disableAll(); + componentParametersView.setIgnoreUsers(false); + return componentParametersView; + } + + private Either<GraphVertex, StorageOperationStatus> checkinToscaELement(LifecycleStateEnum currState, GraphVertex toscaElementVertex, GraphVertex ownerVertex, GraphVertex modifierVertex, LifecycleStateEnum nextState) { + Either<GraphVertex, StorageOperationStatus> updateRelationsRes; + Either<GraphVertex, StorageOperationStatus> result = changeStateToCheckedIn(currState, toscaElementVertex, ownerVertex, modifierVertex); + if (result.isLeft()) { + toscaElementVertex.addMetadataProperty(GraphPropertyEnum.STATE, nextState.name()); + toscaElementVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); + result = updateToscaElementVertexMetadataPropertiesAndJson(toscaElementVertex); + } + if (result.isLeft()) { + updateRelationsRes = updateLastModifierEdge(toscaElementVertex, ownerVertex, modifierVertex); + if (updateRelationsRes.isRight()) { + result = Either.right(updateRelationsRes.right().value()); + } + } + return result; + } + + private Either<GraphVertex, StorageOperationStatus> updateToscaElementVertexMetadataPropertiesAndJson(GraphVertex toscaElementVertex) { + + Either<GraphVertex, StorageOperationStatus> result; + + Either<GraphVertex, TitanOperationStatus> updateVertexRes = titanDao.updateVertex(toscaElementVertex); + if (updateVertexRes.isRight()) { + TitanOperationStatus titatStatus = updateVertexRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update state of tosca element vertex {} metadata. Status is {}", toscaElementVertex.getUniqueId(), titatStatus); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(titatStatus)); + } else { + result = Either.left(updateVertexRes.left().value()); + } + return result; + } + + private Either<GraphVertex, StorageOperationStatus> changeStateToCheckedIn(LifecycleStateEnum currState, GraphVertex toscaElementVertex, GraphVertex ownerVertex, GraphVertex modifierVertex) { + Either<GraphVertex, StorageOperationStatus> result = null; + LifecycleStateEnum nextState = LifecycleStateEnum.NOT_CERTIFIED_CHECKIN; + String faileToUpdateStateMsg = "Failed to update state of tosca element {}. Status is {}"; + + if (currState == LifecycleStateEnum.READY_FOR_CERTIFICATION) { + // In case of cancel "ready for certification" remove last state edge with "STATE" property equals to "NOT_CERTIFIED_CHECKIN" + Map<GraphPropertyEnum, Object> vertexProperties = new HashMap<>(); + vertexProperties.put(GraphPropertyEnum.STATE, nextState); + Either<Edge, TitanOperationStatus> deleteResult = titanDao.deleteBelongingEdgeByCriteria(toscaElementVertex, EdgeLabelEnum.LAST_STATE, vertexProperties); + if (deleteResult.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, faileToUpdateStateMsg, toscaElementVertex.getUniqueId(), deleteResult.right().value()); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "failed to update last state relation"); + result = Either.right(StorageOperationStatus.INCONSISTENCY); + } + } + if (result == null) { + // Remove CHECKOUT relation + Either<Edge, TitanOperationStatus> deleteEdgeResult = titanDao.deleteEdge(ownerVertex, toscaElementVertex, EdgeLabelEnum.STATE); + if (deleteEdgeResult.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, faileToUpdateStateMsg, toscaElementVertex.getUniqueId()); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(deleteEdgeResult.right().value())); + } + } + if (result == null) { + // Create CHECKIN relation + Map<EdgePropertyEnum, Object> edgeProperties = new HashMap<>(); + edgeProperties.put(EdgePropertyEnum.STATE, nextState); + TitanOperationStatus createEdgeRes = titanDao.createEdge(modifierVertex.getVertex(), toscaElementVertex.getVertex(), EdgeLabelEnum.STATE, edgeProperties); + if (createEdgeRes != TitanOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, faileToUpdateStateMsg, toscaElementVertex.getUniqueId()); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createEdgeRes)); + } + } + if (result == null) { + result = Either.left(toscaElementVertex); + } + return result; + } + + private Either<GraphVertex, StorageOperationStatus> updateLastModifierEdge(GraphVertex toscaElementVertex, GraphVertex ownerVertex, GraphVertex modifierVertex) { + Either<GraphVertex, StorageOperationStatus> result = null; + if (!modifierVertex.getMetadataProperties().get(GraphPropertyEnum.USERID).equals(ownerVertex.getMetadataProperties().get(GraphPropertyEnum.USERID))) { + Either<Edge, TitanOperationStatus> deleteEdgeRes = titanDao.deleteEdge(ownerVertex, toscaElementVertex, EdgeLabelEnum.LAST_MODIFIER); + if (deleteEdgeRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete last modifier {} to tosca element {}. Edge type is {}", ownerVertex.getUniqueId(), ownerVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(deleteEdgeRes.right().value())); + } + if (result == null) { + TitanOperationStatus createEdgeRes = titanDao.createEdge(modifierVertex.getVertex(), toscaElementVertex.getVertex(), EdgeLabelEnum.LAST_MODIFIER, new HashMap<>()); + + if (createEdgeRes != TitanOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to associate user {} to component {}. Edge type is {}", modifierVertex.getUniqueId(), ownerVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createEdgeRes)); + } else { + result = Either.left(modifierVertex); + } + } + } else { + result = Either.left(ownerVertex); + } + return result; + } + + private Map<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> prepareParametersToGetVerticesForCheckin(String toscaElementId, String modifierId, String ownerId) { + Map<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> verticesToGetParameters = new HashMap<>(); + verticesToGetParameters.put(toscaElementId, new ImmutablePair<>(GraphPropertyEnum.UNIQUE_ID, JsonParseFlagEnum.ParseMetadata)); + verticesToGetParameters.put(modifierId, new ImmutablePair<>(GraphPropertyEnum.USERID, JsonParseFlagEnum.NoParse)); + verticesToGetParameters.put(ownerId, new ImmutablePair<>(GraphPropertyEnum.USERID, JsonParseFlagEnum.NoParse)); + return verticesToGetParameters; + } + + private Map<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> prepareParametersToGetVerticesForRequestCertification(String toscaElementId, String modifierId, String ownerId) { + Map<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> verticesToGetParameters = new HashMap<>(); + verticesToGetParameters.put(toscaElementId, new ImmutablePair<>(GraphPropertyEnum.UNIQUE_ID, JsonParseFlagEnum.ParseAll)); + verticesToGetParameters.put(modifierId, new ImmutablePair<>(GraphPropertyEnum.USERID, JsonParseFlagEnum.NoParse)); + verticesToGetParameters.put(ownerId, new ImmutablePair<>(GraphPropertyEnum.USERID, JsonParseFlagEnum.NoParse)); + return verticesToGetParameters; + } + + private Map<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> prepareParametersToGetVerticesForCheckout(String toscaElementId, String modifierId, String ownerId) { + //Implementation is currently identical + return prepareParametersToGetVerticesForRequestCertification(toscaElementId,modifierId, ownerId); + } + + private String getNextCertifiedVersion(String version) { + String[] versionParts = version.split(VERSION_DELIMITER_REGEXP); + Integer nextMajorVersion = Integer.parseInt(versionParts[0]) + 1; + return nextMajorVersion + VERSION_DELIMITER + "0"; + } + + private String getNextVersion(String currVersion) { + String[] versionParts = currVersion.split(VERSION_DELIMITER_REGEXP); + Integer minorVersion = Integer.parseInt(versionParts[1]) + 1; + return versionParts[0] + VERSION_DELIMITER + minorVersion; + } + + private Integer getMinorVersion(String version) { + String[] versionParts = version.split(VERSION_DELIMITER_REGEXP); + return Integer.parseInt(versionParts[1]); + } + + private Integer getMajorVersion(String version) { + String[] versionParts = version.split(VERSION_DELIMITER_REGEXP); + return Integer.parseInt(versionParts[0]); + } + + private boolean isFirstCheckoutAfterCertification(String version) { + return (Integer.parseInt(version.split(VERSION_DELIMITER_REGEXP)[0]) != 0 && Integer.parseInt(version.split(VERSION_DELIMITER_REGEXP)[1]) == 1); + } + + 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; + GraphVertex modifier = null; + GraphVertex owner; + try { + Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesRes = titanDao.getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId)); + if (getVerticesRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVerticesRes.right().value())); + } + if (result == null) { + toscaElement = getVerticesRes.left().value().get(toscaElementId); + modifier = getVerticesRes.left().value().get(modifierId); + owner = getVerticesRes.left().value().get(ownerId); + + StorageOperationStatus status = handleRelationsUponForceCertification(toscaElement, modifier, owner); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to handle relations on certification request for tosca element {}. Status is {}. ", toscaElement.getUniqueId(), status); + } + } + if (result == null) { + LifecycleStateEnum nextState = LifecycleStateEnum.CERTIFIED; + + toscaElement.addMetadataProperty(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + toscaElement.addMetadataProperty(GraphPropertyEnum.VERSION, getNextCertifiedVersion(currVersion)); + + resultUpdate = updateToscaElementVertexMetadataPropertiesAndJson(toscaElement); + if (resultUpdate.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to set lifecycle for tosca elememt {} to state {}, error: {}", toscaElement.getUniqueId(), nextState, resultUpdate.right().value()); + result = Either.right(resultUpdate.right().value()); + } + } + if (result == null) { + ToscaElementOperation operation = getToscaElementOperation(toscaElement.getLabel()); + result = operation.getToscaElement(toscaElement.getUniqueId()); + } + return result; + + } catch (Exception e) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during request certification tosca element {}. {}", toscaElementId, e.getMessage()); + } + return result; + } + + private StorageOperationStatus handleRelationsUponForceCertification(GraphVertex toscaElement, GraphVertex modifier, GraphVertex owner) { + + StorageOperationStatus result = null; + TitanOperationStatus status = titanDao.replaceEdgeLabel(owner.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE); + if (status != TitanOperationStatus.OK) { + result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); + } + if (result == null) { + Map<EdgePropertyEnum, Object> properties = new EnumMap<>(EdgePropertyEnum.class); + properties.put(EdgePropertyEnum.STATE, LifecycleStateEnum.CERTIFIED); + status = titanDao.createEdge(modifier, toscaElement, EdgeLabelEnum.STATE, properties); + if (status != TitanOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "failed to create edge. Status is {}", status); + result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); + } + } + if (result == null) { + result = StorageOperationStatus.OK; + } + return result; + } + + private StorageOperationStatus updateEdgeToCatalogRootByUndoCheckout(TitanVertex preV, GraphVertex curV) { + if (preV == null) { + return updateEdgeToCatalogRoot(null, curV); + } + String uniqueIdPreVer = (String) titanDao.getProperty((TitanVertex) preV, GraphPropertyEnum.UNIQUE_ID.getProperty()); + LifecycleStateEnum state = LifecycleStateEnum.findState((String) titanDao.getProperty(preV, GraphPropertyEnum.STATE.getProperty())); + if (state == LifecycleStateEnum.CERTIFIED) { + return updateEdgeToCatalogRoot(null, curV); + } + return titanDao.getVertexById(uniqueIdPreVer) + .either(l -> updateEdgeToCatalogRoot(l, curV), + DaoStatusConverter::convertTitanStatusToStorageStatus); + } + + private StorageOperationStatus updateEdgeToCatalogRoot(GraphVertex newVersionV, GraphVertex prevVersionV) { + Either<GraphVertex, TitanOperationStatus> catalog = titanDao.getVertexByLabel(VertexTypeEnum.CATALOG_ROOT); + if (catalog.isRight()) { + CommonUtility.addRecordToLog(log, 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(log, LogLevelEnum.DEBUG, "Failed to create edge from {} to catalog vertex. error {}", newVersionV.getUniqueId(), result); + return DaoStatusConverter.convertTitanStatusToStorageStatus(result); + } + } + } + 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(log, LogLevelEnum.DEBUG, "Failed to delete edge from {} to catalog vertex. error {}", prevVersionV.getUniqueId(), deleteResult.right().value()); + return DaoStatusConverter.convertTitanStatusToStorageStatus(deleteResult.right().value()); + } + } + } + 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 df7b382503..a97f033e1c 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 @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -23,6 +23,7 @@ package org.openecomp.sdc.be.model.jsontitan.operations; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import fj.data.Either; +import org.apache.commons.collections.CollectionUtils; import org.apache.tinkerpop.gremlin.structure.Direction; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Vertex; @@ -58,16 +59,15 @@ import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.common.jsongraph.util.CommonUtility; import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; +import org.openecomp.sdc.common.log.wrappers.Logger; 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 java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; +import java.util.*; +import java.util.Map.Entry; +import java.util.stream.Collectors; import java.util.Iterator; import java.util.List; import java.util.Map; @@ -75,7 +75,13 @@ import java.util.Map.Entry; import java.util.Set; public abstract class ToscaElementOperation extends BaseOperation { - private static Logger log = LoggerFactory.getLogger(ToscaElementOperation.class.getName()); + private static final String FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR = "failed to fetch {} for tosca element with id {}, error {}"; + + private static final String CANNOT_FIND_USER_IN_THE_GRAPH_STATUS_IS = "Cannot find user {} in the graph. status is {}"; + + private static final String FAILED_TO_CREATE_EDGE_WITH_LABEL_FROM_USER_VERTEX_TO_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS = "Failed to create edge with label {} from user vertex {} to tosca element vertex {} on graph. Status is {}. "; + + private static Logger log = Logger.getLogger(ToscaElementOperation.class.getName()); private static final Gson gson = new Gson(); @@ -88,7 +94,7 @@ public abstract class ToscaElementOperation extends BaseOperation { protected Either<GraphVertex, StorageOperationStatus> getComponentByLabelAndId(String uniqueId, ToscaElementTypeEnum nodeType, JsonParseFlagEnum parseFlag) { - Map<GraphPropertyEnum, Object> propertiesToMatch = new HashMap<GraphPropertyEnum, Object>(); + Map<GraphPropertyEnum, Object> propertiesToMatch = new HashMap<>(); propertiesToMatch.put(GraphPropertyEnum.UNIQUE_ID, uniqueId); VertexTypeEnum vertexType = ToscaElementTypeEnum.getVertexTypeByToscaType(nodeType); @@ -141,7 +147,7 @@ public abstract class ToscaElementOperation extends BaseOperation { /** * Performs a shadow clone of previousToscaElement - * + * * @param previousToscaElement * @param nextToscaElement * @param user @@ -162,11 +168,11 @@ public abstract class ToscaElementOperation extends BaseOperation { } if (result == null) { createdToscaElementVertex = createNextVersionRes.left().value(); - Map<EdgePropertyEnum, Object> properties = new HashMap<EdgePropertyEnum, Object>(); + Map<EdgePropertyEnum, Object> properties = new HashMap<>(); 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(), + 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)); } @@ -174,7 +180,7 @@ public abstract class ToscaElementOperation extends BaseOperation { 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(), + 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)); } @@ -182,7 +188,7 @@ public abstract class ToscaElementOperation extends BaseOperation { 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(), + 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)); } @@ -290,6 +296,9 @@ public abstract class ToscaElementOperation extends BaseOperation { 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)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_ARCHIVED, toscaElement.getMetadataValue(JsonPresentationFields.IS_ARCHIVED)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.ARCHIVE_TIME, toscaElement.getMetadataValue(JsonPresentationFields.ARCHIVE_TIME)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_VSP_ARCHIVED, toscaElement.getMetadataValue(JsonPresentationFields.IS_VSP_ARCHIVED)); toscaElement.getMetadata().entrySet().stream().filter(e -> e.getValue() != null).forEach(e -> nodeTypeVertex.setJsonMetadataField(JsonPresentationFields.getByPresentation(e.getKey()), e.getValue())); nodeTypeVertex.setUniqueId(toscaElement.getUniqueId()); @@ -305,7 +314,7 @@ public abstract class ToscaElementOperation extends BaseOperation { if (findUser.isRight()) { TitanOperationStatus status = findUser.right().value(); - log.error("Cannot find user {} in the graph. status is {}", userId, status); + log.error(CANNOT_FIND_USER_IN_THE_GRAPH_STATUS_IS, userId, status); return DaoStatusConverter.convertTitanStatusToStorageStatus(status); } @@ -316,13 +325,13 @@ public abstract class ToscaElementOperation extends BaseOperation { findUser = findUserVertex(updaterId); if (findUser.isRight()) { TitanOperationStatus status = findUser.right().value(); - log.error("Cannot find user {} in the graph. status is {}", userId, status); + 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>(); + Map<EdgePropertyEnum, Object> props = new HashMap<>(); props.put(EdgePropertyEnum.STATE, (String) toscaElement.getMetadataValue(JsonPresentationFields.LIFECYCLE_STATE)); TitanOperationStatus result = titanDao.createEdge(updaterVertex, nodeTypeVertex, EdgeLabelEnum.STATE, props); @@ -397,7 +406,7 @@ public abstract class ToscaElementOperation extends BaseOperation { String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase()); a.setUniqueId(uniqueId); }); - status = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.ARTIFACTS, EdgeLabelEnum.ARTIFACTS, artifacts); + status = associateElementToData(nodeTypeVertex, VertexTypeEnum.ARTIFACTS, EdgeLabelEnum.ARTIFACTS, artifacts); if (status.isRight()) { return status.right().value(); } @@ -408,7 +417,7 @@ public abstract class ToscaElementOperation extends BaseOperation { String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase()); a.setUniqueId(uniqueId); }); - status = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.TOSCA_ARTIFACTS, EdgeLabelEnum.TOSCA_ARTIFACTS, toscaArtifacts); + status = associateElementToData(nodeTypeVertex, VertexTypeEnum.TOSCA_ARTIFACTS, EdgeLabelEnum.TOSCA_ARTIFACTS, toscaArtifacts); if (status.isRight()) { return status.right().value(); } @@ -419,7 +428,7 @@ public abstract class ToscaElementOperation extends BaseOperation { String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase()); a.setUniqueId(uniqueId); }); - status = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.DEPLOYMENT_ARTIFACTS, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS, deploymentArtifacts); + status = associateElementToData(nodeTypeVertex, VertexTypeEnum.DEPLOYMENT_ARTIFACTS, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS, deploymentArtifacts); if (status.isRight()) { return status.right().value(); } @@ -546,7 +555,7 @@ public abstract class ToscaElementOperation extends BaseOperation { } } if (!propertiesAll.isEmpty()) { - Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.PROPERTIES, EdgeLabelEnum.PROPERTIES, propertiesAll); + Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.PROPERTIES, EdgeLabelEnum.PROPERTIES, propertiesAll); if (assosiateElementToData.isRight()) { return assosiateElementToData.right().value(); } @@ -557,7 +566,7 @@ public abstract class ToscaElementOperation extends BaseOperation { 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); + Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData(nodeTypeVertex, VertexTypeEnum.ADDITIONAL_INFORMATION, EdgeLabelEnum.ADDITIONAL_INFORMATION, additionalInformation); if (assosiateElementToData.isRight()) { return assosiateElementToData.right().value(); } @@ -624,7 +633,7 @@ public abstract class ToscaElementOperation extends BaseOperation { Map<String, String> allVersion = new HashMap<>(); allVersion.put((String) componentV.getMetadataProperty(GraphPropertyEnum.VERSION), componentV.getUniqueId()); - ArrayList<GraphVertex> allChildrenAndParants = new ArrayList<GraphVertex>(); + ArrayList<GraphVertex> allChildrenAndParants = new ArrayList<>(); Either<GraphVertex, TitanOperationStatus> childResourceRes = titanDao.getChildVertex(componentV, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); while (childResourceRes.isLeft()) { GraphVertex child = childResourceRes.left().value(); @@ -648,7 +657,7 @@ public abstract class ToscaElementOperation extends BaseOperation { } else { allChildrenAndParants.stream().filter(vertex -> { Boolean isDeleted = (Boolean) vertex.getMetadataProperty(GraphPropertyEnum.IS_DELETED); - return (isDeleted == null || isDeleted == false); + return (isDeleted == null || !isDeleted); }).forEach(vertex -> allVersion.put((String) vertex.getMetadataProperty(GraphPropertyEnum.VERSION), vertex.getUniqueId())); toscaElement.setAllVersions(allVersion); @@ -681,7 +690,7 @@ public abstract class ToscaElementOperation extends BaseOperation { List<T> componentsPerUser; for (GraphVertex userV : users) { - HashSet<String> ids = new HashSet<String>(); + HashSet<String> ids = new HashSet<>(); 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()); @@ -716,7 +725,7 @@ public abstract class ToscaElementOperation extends BaseOperation { if (ids.contains(comp.getUniqueId())) { isFirst = false; } - if (isFirst == true) { + if (isFirst) { components.add(comp); } @@ -749,8 +758,9 @@ public abstract class ToscaElementOperation extends BaseOperation { 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()); + Boolean isArchived = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_ARCHIVED); + if (isDeleted != null && isDeleted || isArchived != null && isArchived) { + log.trace("Deleted/Archived element {}, discard", node.getUniqueId()); continue; } @@ -766,19 +776,19 @@ public abstract class ToscaElementOperation extends BaseOperation { } 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) { + case SERVICE: + case PRODUCT: handleNode(components, node, componentType); - } // if not abstract - break; - default: - log.debug("not supported node type {}", componentType); - break; + break; + case RESOURCE: + Boolean isAbtract = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_ABSTRACT); + if (isAbtract == null || !isAbtract) { + handleNode(components, node, componentType); + } // if not abstract + break; + default: + log.debug("not supported node type {}", componentType); + break; }// case } // needed type } @@ -854,15 +864,15 @@ public abstract class ToscaElementOperation extends BaseOperation { 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; + 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(); @@ -872,29 +882,29 @@ public abstract class ToscaElementOperation extends BaseOperation { return (T) toscaElement; } - protected TitanOperationStatus setServiceCategoryFromGraphV(Vertex vertex, CatalogComponent catalogComponent) { + 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()); + 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(); + 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 setResourceCategoryFromGraphV(Vertex vertex, CatalogComponent catalogComponent) { - + 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()); + 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(); + Vertex categoryV = childVertex.left().value(); catalogComponent.setCategoryNormalizedName((String) categoryV.property(JsonPresentationFields.NORMALIZED_NAME.getPresentation()).value()); return TitanOperationStatus.OK; @@ -906,7 +916,7 @@ public abstract class ToscaElementOperation extends BaseOperation { 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()); + 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(); @@ -966,12 +976,11 @@ public abstract class ToscaElementOperation extends BaseOperation { if (findUser.isRight()) { TitanOperationStatus status = findUser.right().value(); - log.error("Cannot find user {} in the graph. status is {}", modifierUserId, status); + 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); @@ -1036,12 +1045,6 @@ public abstract class ToscaElementOperation extends BaseOperation { // 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) { @@ -1086,7 +1089,7 @@ public abstract class ToscaElementOperation extends BaseOperation { 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()); + 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(); @@ -1107,12 +1110,12 @@ public abstract class ToscaElementOperation extends BaseOperation { String newCategoryName = newCategory.getName(); SubCategoryDefinition newSubcategory = newCategory.getSubcategories().get(0); String newSubCategoryName = newSubcategory.getName(); - if (newCategoryName != null && false == newCategoryName.equals(categoryNameCurrent)) { + if (newCategoryName != null && !newCategoryName.equals(categoryNameCurrent)) { // the category was changed categoryWasChanged = true; } else { // the sub-category was changed - if (newSubCategoryName != null && false == newSubCategoryName.equals(subCategoryNameCurrent)) { + if (newSubCategoryName != null && !newSubCategoryName.equals(subCategoryNameCurrent)) { log.debug("Going to update the category of the resource from {} to {}", categoryNameCurrent, newCategory); categoryWasChanged = true; } @@ -1144,7 +1147,7 @@ public abstract class ToscaElementOperation extends BaseOperation { List<T> result = new ArrayList<>(); if (listOfComponents.isLeft()) { List<GraphVertex> highestAndAllCertified = listOfComponents.left().value(); - if (highestAndAllCertified != null && false == highestAndAllCertified.isEmpty()) { + if (highestAndAllCertified != null && !highestAndAllCertified.isEmpty()) { for (GraphVertex vertexComponent : highestAndAllCertified) { Either<T, StorageOperationStatus> component = getLightComponent(vertexComponent, componentType, new ComponentParametersView(true)); if (component.isRight()) { @@ -1159,29 +1162,42 @@ public abstract class ToscaElementOperation extends BaseOperation { return Either.left(result); } - public Either<List<CatalogComponent>, StorageOperationStatus> getElementCatalogData() { - List<CatalogComponent> results = new ArrayList<>(); + public Either<List<CatalogComponent>, StorageOperationStatus> getElementCatalogData(boolean isCatalog, List<ResourceTypeEnum> excludeTypes) { StopWatch stopWatch = new StopWatch(); stopWatch.start(); - Either<Iterator<Vertex>, TitanOperationStatus> verticesEither = titanDao.getCatalogVerticies(); + Map<String, CatalogComponent> existInCatalog = new HashMap<>(); + Either<Iterator<Vertex>, TitanOperationStatus> verticesEither = titanDao.getCatalogOrArchiveVerticies(isCatalog); 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(); + handleCatalogComponent(existInCatalog, vertices.next(), excludeTypes); + } + stopWatch.stop(); + String timeToFetchElements = stopWatch.prettyPrint(); + log.info("time to fetch all catalog elements: {}", timeToFetchElements); + return Either.left(existInCatalog.values().stream().collect(Collectors.toList())); + } + + private void handleCatalogComponent(Map<String, CatalogComponent> existInCatalog, Vertex vertex, List<ResourceTypeEnum> excludeTypes) { + VertexProperty<Object> property = vertex.property(GraphPropertiesDictionary.METADATA.getProperty()); + String json = (String) property.value(); + Map<String, Object> metadatObj = JsonParserUtils.toMap(json); + String uniqueId = (String) metadatObj.get(JsonPresentationFields.UNIQUE_ID.getPresentation()); + Boolean isDeleted = (Boolean) metadatObj.get(JsonPresentationFields.IS_DELETED.getPresentation()); + + + if (isAddToCatalog(excludeTypes, metadatObj) && (existInCatalog.get(uniqueId) == null && (isDeleted == null || !isDeleted.booleanValue()))) { CatalogComponent catalogComponent = new CatalogComponent(); - Map<String, Object> metadatObj = JsonParserUtils.toMap(json); + catalogComponent.setUniqueId(uniqueId); 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())); @@ -1196,16 +1212,30 @@ public abstract class ToscaElementOperation extends BaseOperation { } else { setResourceCategoryFromGraphV(vertex, catalogComponent); } - results.add(catalogComponent); + List<String> tags = (List<String>) metadatObj.get(JsonPresentationFields.TAGS.getPresentation()); + if (tags != null) { + catalogComponent.setTags(tags); + } + existInCatalog.put(uniqueId, catalogComponent); + } + } + private boolean isAddToCatalog(List<ResourceTypeEnum> excludeTypes, Map<String, Object> metadatObj) { + boolean isAddToCatalog = true; + Object resourceTypeStr = metadatObj.get(JsonPresentationFields.RESOURCE_TYPE.getPresentation()); + if (resourceTypeStr != null) { + ResourceTypeEnum resourceType = ResourceTypeEnum.getType((String) resourceTypeStr); + if (!CollectionUtils.isEmpty(excludeTypes)) { + Optional<ResourceTypeEnum> op = excludeTypes.stream().filter(rt -> rt == resourceType).findAny(); + if (op.isPresent()) + isAddToCatalog = false; + } } - stopWatch.stop(); - String timeToFetchElements = stopWatch.prettyPrint(); - log.info("time to fetch all catalog elements: {}", timeToFetchElements); - return Either.left(results); + return isAddToCatalog; } - public Either<List<GraphVertex>, TitanOperationStatus> getListOfHighestComponents(ComponentTypeEnum componentType, List<ResourceTypeEnum> excludeTypes, JsonParseFlagEnum parseFlag) { + 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()); @@ -1216,12 +1246,14 @@ public abstract class ToscaElementOperation extends BaseOperation { propertiesHasNotToMatch.put(GraphPropertyEnum.RESOURCE_TYPE, excludeTypes); } propertiesHasNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); + propertiesHasNotToMatch.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683 return titanDao.getByCriteria(null, propertiesToMatch, propertiesHasNotToMatch, parseFlag); } // highest + (certified && !highest) - public Either<List<GraphVertex>, TitanOperationStatus> getListOfHighestAndAllCertifiedComponents(ComponentTypeEnum componentType, List<ResourceTypeEnum> excludeTypes) { + 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); @@ -1235,6 +1267,7 @@ public abstract class ToscaElementOperation extends BaseOperation { } propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_DELETED, true); + propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683 propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); Either<List<GraphVertex>, TitanOperationStatus> certifiedNotHighestNodes = titanDao.getByCriteria(null, propertiesToMatchCertified, propertiesHasNotToMatchCertified, JsonParseFlagEnum.ParseMetadata); @@ -1257,10 +1290,11 @@ public abstract class ToscaElementOperation extends BaseOperation { return Either.left(allNodes); } - protected Either<List<GraphVertex>, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) { + protected Either<List<GraphVertex>, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum + componentType) { // get all components marked for delete - Map<GraphPropertyEnum, Object> props = new HashMap<GraphPropertyEnum, Object>(); + Map<GraphPropertyEnum, Object> props = new HashMap<>(); props.put(GraphPropertyEnum.IS_DELETED, true); props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); @@ -1279,7 +1313,8 @@ public abstract class ToscaElementOperation extends BaseOperation { return Either.left(componentsToDelete.left().value()); } - protected TitanOperationStatus setAdditionalInformationFromGraph(GraphVertex componentV, ToscaElement toscaElement) { + 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()); @@ -1292,24 +1327,34 @@ public abstract class ToscaElementOperation extends BaseOperation { } // -------------------------------------------- - public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> getToscaElement(String uniqueId, ComponentParametersView componentParametersView); + 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> getToscaElement(GraphVertex toscaElementVertex, ComponentParametersView componentParametersView); - public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> deleteToscaElement(GraphVertex toscaElementVertex); + public abstract <T extends + ToscaElement> Either<T, StorageOperationStatus> deleteToscaElement(GraphVertex toscaElementVertex); - public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> createToscaElement(ToscaElement toscaElement); + 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 + setCategoriesFromGraph(GraphVertex vertexComponent, T toscaElement); - protected abstract <T extends ToscaElement> TitanOperationStatus setCapabilitiesFromGraph(GraphVertex componentV, 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> TitanOperationStatus + setRequirementsFromGraph(GraphVertex componentV, T toscaElement); - protected abstract <T extends ToscaElement> StorageOperationStatus validateCategories(T toscaElementToUpdate, GraphVertex elementV); + protected abstract <T extends ToscaElement> StorageOperationStatus + validateCategories(T toscaElementToUpdate, GraphVertex elementV); - protected abstract <T extends ToscaElement> StorageOperationStatus updateDerived(T toscaElementToUpdate, GraphVertex updateElementV); + 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 168b127c9c..aae73841a1 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 @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,2478 +20,2410 @@ 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; import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.tinkerpop.gremlin.structure.Direction; +import org.apache.tinkerpop.gremlin.structure.Edge; 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.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.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.PolicyDefinition; -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.datatypes.elements.*; +import org.openecomp.sdc.be.datatypes.enums.*; +import org.openecomp.sdc.be.model.*; +import org.openecomp.sdc.be.datatypes.elements.MapCapabilityProperty; +import org.openecomp.sdc.be.datatypes.elements.MapListCapabilityDataDefinition; 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; +import org.openecomp.sdc.be.model.operations.StorageException; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.be.resources.data.ComponentMetadataData; import org.openecomp.sdc.common.jsongraph.util.CommonUtility; import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.util.ValidationUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import fj.data.Either; - -@org.springframework.stereotype.Component("tosca-operation-facade") -public class ToscaOperationFacade { - - // region - Fields - - @Autowired - private NodeTypeOperation nodeTypeOperation; - @Autowired - private TopologyTemplateOperation topologyTemplateOperation; - @Autowired - private NodeTemplateOperation nodeTemplateOperation; - @Autowired - private GroupsOperation groupsOperation; - @Autowired - private TitanDao titanDao; - private static Logger log = LoggerFactory.getLogger(ToscaOperationFacade.class.getName()); - // endregion - - // region - ToscaElement - GetById - public static final String PROXY_SUFFIX = "_proxy"; - - public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId) { - - return getToscaElement(componentId, JsonParseFlagEnum.ParseAll); - - } - - public <T extends Component> Either<T, StorageOperationStatus> getToscaFullElement(String componentId) { - ComponentParametersView filters = new ComponentParametersView(); - filters.setIgnoreCapabiltyProperties(false); - filters.setIgnoreForwardingPath(false); - return getToscaElement(componentId, filters); - } - - public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, ComponentParametersView filters) { - - Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, filters.detectParseFlag()); - if (getVertexEither.isRight()) { - log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); - - } - return getToscaElementByOperation(getVertexEither.left().value(), filters); - } - - public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, JsonParseFlagEnum parseFlag) { - - Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, parseFlag); - if (getVertexEither.isRight()) { - log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); - - } - return getToscaElementByOperation(getVertexEither.left().value()); - } - - public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(GraphVertex componentVertex) { - return getToscaElementByOperation(componentVertex); - } - - public Either<Boolean, StorageOperationStatus> validateComponentExists(String componentId) { - - Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getVertexEither.isRight()) { - TitanOperationStatus status = getVertexEither.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - return Either.left(false); - } else { - log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); - } - } - return Either.left(true); - } - - public <T extends Component> Either<T, StorageOperationStatus> findLastCertifiedToscaElementByUUID(T component) { - Map<GraphPropertyEnum, Object> props = new HashMap<>(); - props.put(GraphPropertyEnum.UUID, component.getUUID()); - props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - - Either<List<GraphVertex>, TitanOperationStatus> getVertexEither = titanDao.getByCriteria(ModelConverter.getVertexType(component), props); - if (getVertexEither.isRight()) { - log.debug("Couldn't fetch component with and unique id {}, error: {}", component.getUniqueId(), getVertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); - - } - return getToscaElementByOperation(getVertexEither.left().value().get(0)); - } - - // endregion - // region - ToscaElement - GetByOperation - private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV) { - return getToscaElementByOperation(componentV, new ComponentParametersView()); - } - - private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV, ComponentParametersView filters) { - VertexTypeEnum label = componentV.getLabel(); - - ToscaElementOperation toscaOperation = getToscaElementOperation(componentV); - Either<ToscaElement, StorageOperationStatus> toscaElement; - String componentId = componentV.getUniqueId(); - if (toscaOperation != null) { - log.debug("Need to fetch tosca element for id {}", componentId); - toscaElement = toscaOperation.getToscaElement(componentV, filters); - } else { - log.debug("not supported tosca type {} for id {}", label, componentId); - toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST); - } - if (toscaElement.isRight()) { - return Either.right(toscaElement.right().value()); - } - return Either.left(ModelConverter.convertFromToscaElement(toscaElement.left().value())); - } - - // endregion - private ToscaElementOperation getToscaElementOperation(GraphVertex componentV) { - VertexTypeEnum label = componentV.getLabel(); - switch (label) { - case NODE_TYPE: - return nodeTypeOperation; - case TOPOLOGY_TEMPLATE: - return topologyTemplateOperation; - default: - return null; - } - } - - /** - * - * @param resource - * @return - */ - public <T extends Component> Either<T, StorageOperationStatus> createToscaComponent(T resource) { - ToscaElement toscaElement = ModelConverter.convertToToscaElement(resource); - - ToscaElementOperation toscaElementOperation = getToscaElementOperation(resource); - Either<ToscaElement, StorageOperationStatus> createToscaElement = toscaElementOperation.createToscaElement(toscaElement); - if (createToscaElement.isLeft()) { - log.debug("Component created successfully!!!"); - T dataModel = ModelConverter.convertFromToscaElement(createToscaElement.left().value()); - return Either.left(dataModel); - } - return Either.right(createToscaElement.right().value()); - } - - // region - ToscaElement Delete - /** - * - * @param componentToDelete - * @return - */ - public StorageOperationStatus markComponentToDelete(Component componentToDelete) { - - if ((componentToDelete.getIsDeleted() != null) && componentToDelete.getIsDeleted() && !componentToDelete.isHighestVersion()) { - // component already marked for delete - return StorageOperationStatus.OK; - } else { - - Either<GraphVertex, TitanOperationStatus> getResponse = titanDao.getVertexById(componentToDelete.getUniqueId(), JsonParseFlagEnum.ParseAll); - if (getResponse.isRight()) { - log.debug("Couldn't fetch component with and unique id {}, error: {}", componentToDelete.getUniqueId(), getResponse.right().value()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(getResponse.right().value()); - - } - GraphVertex componentV = getResponse.left().value(); - - // same operation for node type and topology template operations - Either<GraphVertex, StorageOperationStatus> result = nodeTypeOperation.markComponentToDelete(componentV); - if (result.isRight()) { - return result.right().value(); - } - return StorageOperationStatus.OK; - } - } - - /** - * - * @param componentId - * @return - */ - public <T extends Component> Either<T, StorageOperationStatus> deleteToscaComponent(String componentId) { - - Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll); - if (getVertexEither.isRight()) { - log.debug("Couldn't fetch component vertex with and unique id {}, error: {}", componentId, getVertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); - - } - Either<ToscaElement, StorageOperationStatus> deleteElement = deleteToscaElement(getVertexEither.left().value()); - if (deleteElement.isRight()) { - log.debug("Failed to delete component with and unique id {}, error: {}", componentId, deleteElement.right().value()); - return Either.right(deleteElement.right().value()); - } - T dataModel = ModelConverter.convertFromToscaElement(deleteElement.left().value()); - - return Either.left(dataModel); - } - - private Either<ToscaElement, StorageOperationStatus> deleteToscaElement(GraphVertex componentV) { - VertexTypeEnum label = componentV.getLabel(); - Either<ToscaElement, StorageOperationStatus> toscaElement; - Object componentId = componentV.getUniqueId(); - switch (label) { - case NODE_TYPE: - log.debug("Need to fetch node type for id {}", componentId); - toscaElement = nodeTypeOperation.deleteToscaElement(componentV); - break; - case TOPOLOGY_TEMPLATE: - log.debug("Need to fetch topology template for id {}", componentId); - toscaElement = topologyTemplateOperation.deleteToscaElement(componentV); - break; - default: - log.debug("not supported tosca type {} for id {}", label, componentId); - toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST); - break; - } - return toscaElement; - } - // endregion - - private ToscaElementOperation getToscaElementOperation(Component component) { - return ModelConverter.isAtomicComponent(component) ? nodeTypeOperation : topologyTemplateOperation; - } - - public <T extends Component> Either<T, StorageOperationStatus> getLatestByToscaResourceName(String toscaResourceName) { - return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName); - } - - public <T extends Component> Either<T, StorageOperationStatus> getFullLatestComponentByToscaResourceName(String toscaResourceName) { - 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) { - return getLatestByName(GraphPropertyEnum.NAME, resourceName); - - } - - public Either<Integer, StorageOperationStatus> validateCsarUuidUniqueness(String csarUUID) { - - Map<GraphPropertyEnum, Object> properties = new HashMap<GraphPropertyEnum, Object>(); - properties.put(GraphPropertyEnum.CSAR_UUID, csarUUID); - - Either<List<GraphVertex>, TitanOperationStatus> resources = titanDao.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata); - - if (resources.isRight()) { - if (resources.right().value() == TitanOperationStatus.NOT_FOUND) { - return Either.left(new Integer(0)); - } else { - log.debug("failed to get resources from graph with property name: {}", csarUUID); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value())); - } - } - - List<GraphVertex> resourceList = (resources.isLeft() ? resources.left().value() : null); - - return Either.left(new Integer(resourceList.size())); - - } - - public <T extends Component> Either<Set<T>, StorageOperationStatus> getFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, ComponentTypeEnum componentType) { - Either<List<ToscaElement>, StorageOperationStatus> followedResources; - if (componentType == ComponentTypeEnum.RESOURCE) { - followedResources = nodeTypeOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType); - } else { - followedResources = topologyTemplateOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType); - } - - Set<T> components = new HashSet<>(); - if (followedResources.isRight() && followedResources.right().value() != StorageOperationStatus.NOT_FOUND) { - return Either.right(followedResources.right().value()); - } - if (followedResources.isLeft()) { - List<ToscaElement> toscaElements = followedResources.left().value(); - toscaElements.forEach(te -> { - T component = ModelConverter.convertFromToscaElement(te); - components.add(component); - }); - } - return Either.left(components); - } - - public Either<Resource, StorageOperationStatus> getLatestCertifiedNodeTypeByToscaResourceName(String toscaResourceName) { - - return getLatestCertifiedByToscaResourceName(toscaResourceName, VertexTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata); - } - - public Either<Resource, StorageOperationStatus> getLatestCertifiedByToscaResourceName(String toscaResourceName, VertexTypeEnum vertexType, JsonParseFlagEnum parseFlag) { - - Either<Resource, StorageOperationStatus> result = null; - Map<GraphPropertyEnum, Object> props = new HashMap<GraphPropertyEnum, Object>(); - props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName); - props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - Either<List<GraphVertex>, TitanOperationStatus> getLatestRes = titanDao.getByCriteria(vertexType, props, parseFlag); - - if (getLatestRes.isRight()) { - TitanOperationStatus status = getLatestRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ", vertexType, toscaResourceName, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - if (result == null) { - List<GraphVertex> resources = getLatestRes.left().value(); - double version = 0.0; - GraphVertex highestResource = null; - for (GraphVertex resource : resources) { - double resourceVersion = Double.parseDouble((String) resource.getJsonMetadataField(JsonPresentationFields.VERSION)); - if (resourceVersion > version) { - version = resourceVersion; - highestResource = resource; - } - } - result = getToscaFullElement(highestResource.getUniqueId()); - } - return result; - } - - public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExists(String templateName) { - Either<Boolean, StorageOperationStatus> validateUniquenessRes = validateToscaResourceNameUniqueness(templateName); - if (validateUniquenessRes.isLeft()) { - return Either.left(!validateUniquenessRes.left().value()); - } - return validateUniquenessRes; - } - - public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) { - return nodeTemplateOperation.dissociateResourceInstances(componentId, requirementDef); - } - /** - * Allows to get fulfilled requirement by relation and received predicate - * @param componentId - * @param instanceId - * @param relation - * @param predicate - * @return - */ - public Either<RequirementDataDefinition, StorageOperationStatus> getFulfilledRequirementByRelation(String componentId, String instanceId, RequirementCapabilityRelDef relation, BiPredicate<RelationshipInfo, RequirementDataDefinition> predicate) { - return nodeTemplateOperation.getFulfilledRequirementByRelation(componentId, instanceId, relation, predicate); - } - /** - * Allows to get fulfilled capability by relation and received predicate - * @param componentId - * @param instanceId - * @param relation - * @param predicate - * @return - */ - 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()) { - return status.right().value(); - } - return StorageOperationStatus.OK; - } - - protected Either<Boolean, StorageOperationStatus> validateToscaResourceNameUniqueness(String name) { - - Map<GraphPropertyEnum, Object> properties = new HashMap<GraphPropertyEnum, Object>(); - properties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, name); - - Either<List<GraphVertex>, TitanOperationStatus> resources = titanDao.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata); - - if (resources.isRight() && resources.right().value() != TitanOperationStatus.NOT_FOUND) { - log.debug("failed to get resources from graph with property name: {}", name); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value())); - } - List<GraphVertex> resourceList = (resources.isLeft() ? resources.left().value() : null); - if (resourceList != null && resourceList.size() > 0) { - if (log.isDebugEnabled()) { - StringBuilder builder = new StringBuilder(); - for (GraphVertex resourceData : resourceList) { - builder.append(resourceData.getUniqueId() + "|"); - } - log.debug("resources with property name:{} exists in graph. found {}", name, builder.toString()); - } - return Either.left(false); - } else { - log.debug("resources with property name:{} does not exists in graph", name); - return Either.left(true); - } - - } - - // region - Component Update - /** - * - * @param newComponent - * @param oldComponent - * @return vendor - */ - public Either<Resource, StorageOperationStatus> overrideComponent(Resource newComponent, Resource oldComponent) { - - // TODO - // newComponent.setInterfaces(oldComponent.getInterfaces); - newComponent.setArtifacts(oldComponent.getArtifacts()); - newComponent.setDeploymentArtifacts(oldComponent.getDeploymentArtifacts()); - newComponent.setGroups(oldComponent.getGroups()); - newComponent.setLastUpdateDate(null); - newComponent.setHighestVersion(true); - - Either<GraphVertex, TitanOperationStatus> componentVEither = titanDao.getVertexById(oldComponent.getUniqueId(), JsonParseFlagEnum.NoParse); - if (componentVEither.isRight()) { - log.debug("Falied to fetch component {} error {}", oldComponent.getUniqueId(), componentVEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(componentVEither.right().value())); - } - GraphVertex componentv = componentVEither.left().value(); - Either<GraphVertex, TitanOperationStatus> parentVertexEither = titanDao.getParentVertex(componentv, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); - if (parentVertexEither.isRight() && parentVertexEither.right().value() != TitanOperationStatus.NOT_FOUND) { - log.debug("Falied to fetch parent version for component {} error {}", oldComponent.getUniqueId(), parentVertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentVertexEither.right().value())); - } - - Either<ToscaElement, StorageOperationStatus> deleteToscaComponent = deleteToscaElement(componentv); - if (deleteToscaComponent.isRight()) { - log.debug("Falied to remove old component {} error {}", oldComponent.getUniqueId(), deleteToscaComponent.right().value()); - return Either.right(deleteToscaComponent.right().value()); - } - Either<Resource, StorageOperationStatus> createToscaComponent = createToscaComponent(newComponent); - if (createToscaComponent.isRight()) { - log.debug("Falied to create tosca element component {} error {}", newComponent.getUniqueId(), createToscaComponent.right().value()); - return Either.right(createToscaComponent.right().value()); - } - Resource newElement = createToscaComponent.left().value(); - Either<GraphVertex, TitanOperationStatus> newVersionEither = titanDao.getVertexById(newElement.getUniqueId(), JsonParseFlagEnum.NoParse); - if (newVersionEither.isRight()) { - log.debug("Falied to fetch new tosca element component {} error {}", newComponent.getUniqueId(), newVersionEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(newVersionEither.right().value())); - } - if (parentVertexEither.isLeft()) { - GraphVertex previousVersionV = parentVertexEither.left().value(); - TitanOperationStatus createEdge = titanDao.createEdge(previousVersionV, newVersionEither.left().value(), EdgeLabelEnum.VERSION, null); - if (createEdge != TitanOperationStatus.OK) { - log.debug("Falied to associate to previous version {} new version {} error {}", previousVersionV.getUniqueId(), newVersionEither.right().value(), createEdge); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge)); - } - } - return Either.left(newElement); - } - - /** - * - * @param componentToUpdate - * @return - */ - public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate) { - return updateToscaElement(componentToUpdate, new ComponentParametersView()); - } - - /** - * - * @param componentToUpdate - * @param type - * @param filterResult - * @return - */ - public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate, ComponentParametersView filterResult) { - String componentId = componentToUpdate.getUniqueId(); - Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll); - if (getVertexEither.isRight()) { - log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); - } - GraphVertex elementV = getVertexEither.left().value(); - ToscaElementOperation toscaElementOperation = getToscaElementOperation(elementV); - - ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(componentToUpdate); - Either<ToscaElement, StorageOperationStatus> updateToscaElement = toscaElementOperation.updateToscaElement(toscaElementToUpdate, elementV, filterResult); - if (updateToscaElement.isRight()) { - log.debug("Failed to update tosca element {} error {}", componentId, updateToscaElement.right().value()); - return Either.right(updateToscaElement.right().value()); - } - return Either.left(ModelConverter.convertFromToscaElement(updateToscaElement.left().value())); - } - - private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName, 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); - Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); - - propertiesToMatch.put(property, nodeName); - propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - - propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); - - Either<List<GraphVertex>, TitanOperationStatus> highestResources = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, parseFlag); - if (highestResources.isRight()) { - TitanOperationStatus status = highestResources.right().value(); - log.debug("failed to find resource with name {}. status={} ", nodeName, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - - List<GraphVertex> resources = highestResources.left().value(); - double version = 0.0; - GraphVertex highestResource = null; - for (GraphVertex vertex : resources) { - Object versionObj = vertex.getMetadataProperty(GraphPropertyEnum.VERSION); - double resourceVersion = Double.valueOf((String) versionObj); - if (resourceVersion > version) { - version = resourceVersion; - highestResource = vertex; - } - } - return getToscaElementByOperation(highestResource, filter); - } - - // endregion - // region - Component Get By .. - private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName) { - return getLatestByName(property, nodeName, JsonParseFlagEnum.ParseMetadata); - } - - public <T extends Component> Either<List<T>, StorageOperationStatus> getBySystemName(ComponentTypeEnum componentType, String systemName) { - - Either<List<T>, StorageOperationStatus> result = null; - Either<T, StorageOperationStatus> getComponentRes; - List<T> components = new ArrayList<>(); - List<GraphVertex> componentVertices; - Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); - Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); - - propertiesToMatch.put(GraphPropertyEnum.SYSTEM_NAME, systemName); - if (componentType != null) - propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); - - propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); - - Either<List<GraphVertex>, TitanOperationStatus> getComponentsRes = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll); - if (getComponentsRes.isRight()) { - TitanOperationStatus status = getComponentsRes.right().value(); - log.debug("Failed to fetch the component with system name {}. Status is {} ", systemName, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - if (result == null) { - componentVertices = getComponentsRes.left().value(); - for (GraphVertex componentVertex : componentVertices) { - getComponentRes = getToscaElementByOperation(componentVertex); - if (getComponentRes.isRight()) { - log.debug("Failed to get the component {}. Status is {} ", componentVertex.getJsonMetadataField(JsonPresentationFields.NAME), getComponentRes.right().value()); - result = Either.right(getComponentRes.right().value()); - break; - } - T componentBySystemName = getComponentRes.left().value(); - log.debug("Found component, id: {}", componentBySystemName.getUniqueId()); - components.add(componentBySystemName); - } - } - if (result == null) { - result = Either.left(components); - } - return result; - } - - public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version) { - return getComponentByNameAndVersion(componentType, name, version, JsonParseFlagEnum.ParseAll); - } - - public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version, JsonParseFlagEnum parseFlag) { - Either<T, StorageOperationStatus> result; - - Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class); - Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class); - - hasProperties.put(GraphPropertyEnum.NAME, name); - hasProperties.put(GraphPropertyEnum.VERSION, version); - hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true); - if (componentType != null) { - hasProperties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); - } - Either<List<GraphVertex>, TitanOperationStatus> getResourceRes = titanDao.getByCriteria(null, hasProperties, hasNotProperties, parseFlag); - if (getResourceRes.isRight()) { - TitanOperationStatus status = getResourceRes.right().value(); - log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - return getToscaElementByOperation(getResourceRes.left().value().get(0)); - } - public 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) { - List<T> components = new ArrayList<>(); - Either<List<ToscaElement>, StorageOperationStatus> catalogDataResult; - List<ToscaElement> toscaElements = new ArrayList<>(); - List<ResourceTypeEnum> excludedResourceTypes = Optional.ofNullable(excludeTypes).orElse(Collections.emptyList()).stream().filter(type -> !type.equals(OriginTypeEnum.SERVICE)).map(type -> ResourceTypeEnum.getTypeByName(type.name())) - .collect(Collectors.toList()); - - switch (componentType) { - case RESOURCE: - catalogDataResult = nodeTypeOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, excludedResourceTypes, isHighestVersions); - if (catalogDataResult.isRight()) { - return Either.right(catalogDataResult.right().value()); - } - toscaElements = catalogDataResult.left().value(); - break; - case SERVICE: - if (excludeTypes != null && excludeTypes.contains(OriginTypeEnum.SERVICE)) { - break; - } - catalogDataResult = topologyTemplateOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, null, isHighestVersions); - if (catalogDataResult.isRight()) { - return Either.right(catalogDataResult.right().value()); - } - toscaElements = catalogDataResult.left().value(); - break; - default: - log.debug("Not supported component type {}", componentType); - return Either.right(StorageOperationStatus.BAD_REQUEST); - } - toscaElements.forEach(te -> { - T component = ModelConverter.convertFromToscaElement(te); - components.add(component); - }); - return Either.left(components); - } - - public Either<List<String>, StorageOperationStatus> deleteMarkedElements(ComponentTypeEnum componentType) { - Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion; - List<String> deleted = new ArrayList<>(); - switch (componentType) { - case RESOURCE: - allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType); - break; - case SERVICE: - case PRODUCT: - allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType); - break; - default: - log.debug("Not supported component type {}", componentType); - return Either.right(StorageOperationStatus.BAD_REQUEST); - } - if (allComponentsMarkedForDeletion.isRight()) { - return Either.right(allComponentsMarkedForDeletion.right().value()); - } - List<GraphVertex> allMarked = allComponentsMarkedForDeletion.left().value(); - - Either<List<GraphVertex>, TitanOperationStatus> allNotDeletedElements = topologyTemplateOperation.getAllNotDeletedElements(); - if (allNotDeletedElements.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(allNotDeletedElements.right().value())); - } - List<GraphVertex> allNonMarked = allNotDeletedElements.left().value(); - for (GraphVertex elementV : allMarked) { - if (topologyTemplateOperation.isInUse(elementV, allNonMarked) == false) { - Either<ToscaElement, StorageOperationStatus> deleteToscaElement = deleteToscaElement(elementV); - if (deleteToscaElement.isRight()) { - log.debug("Failed to delete marked element {} error {}", elementV.getUniqueId(), deleteToscaElement.right().value()); - } - } else { - deleted.add(elementV.getUniqueId()); - log.debug("Marked element {} in use. don't delete it", elementV.getUniqueId()); - } - } - return Either.left(deleted); - } - - public Either<List<String>, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) { - Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion; - switch (componentType) { - case RESOURCE: - allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType); - break; - case SERVICE: - case PRODUCT: - allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType); - break; - default: - log.debug("Not supported component type {}", componentType); - return Either.right(StorageOperationStatus.BAD_REQUEST); - } - if (allComponentsMarkedForDeletion.isRight()) { - return Either.right(allComponentsMarkedForDeletion.right().value()); - } - return Either.left(allComponentsMarkedForDeletion.left().value().stream().map(v -> v.getUniqueId()).collect(Collectors.toList())); - } - - public Either<Boolean, StorageOperationStatus> isComponentInUse(String componentId) { - Either<Boolean, StorageOperationStatus> result; - Either<List<GraphVertex>, TitanOperationStatus> allNotDeletedElements = topologyTemplateOperation.getAllNotDeletedElements(); - if (allNotDeletedElements.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(allNotDeletedElements.right().value())); - } else { - result = Either.left(topologyTemplateOperation.isInUse(componentId, allNotDeletedElements.left().value())); - } - return result; - } - - // region - Component Update - public Either<ImmutablePair<Component, String>, StorageOperationStatus> addComponentInstanceToTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance, boolean allowDeleted, User user) { - - Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null; - Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null; - if (StringUtils.isEmpty(componentInstance.getIcon())) { - componentInstance.setIcon(origComponent.getIcon()); - } - 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); - - if (addResult.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the component instance {} to container component {}. ", componentInstance.getName(), containerComponent.getName()); - result = Either.right(addResult.right().value()); - } - if (result == null) { - updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponent.getUniqueId()); - if (updateContainerComponentRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with updated component instance {}. ", containerComponent.getName(), componentInstance.getName()); - result = Either.right(updateContainerComponentRes.right().value()); - } - } - if (result == null) { - Component updatedComponent = ModelConverter.convertFromToscaElement(updateContainerComponentRes.left().value()); - String createdInstanceId = addResult.left().value().getRight(); - CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been added to container component {}. ", createdInstanceId, updatedComponent.getName()); - result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId)); - } - return result; - } - - public StorageOperationStatus associateComponentInstancesToComponent(Component containerComponent, Map<ComponentInstance, Resource> resourcesInstancesMap, boolean allowDeleted) { - - StorageOperationStatus result = null; - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to add component instances to component {}", containerComponent.getUniqueId()); - - Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(containerComponent.getUniqueId(), JsonParseFlagEnum.ParseAll); - if (metadataVertex.isRight()) { - TitanOperationStatus status = metadataVertex.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - if (result == null) { - result = nodeTemplateOperation.associateComponentInstancesToComponent(containerComponent, resourcesInstancesMap, metadataVertex.left().value(), allowDeleted); - } - return result; - } - - public Either<ImmutablePair<Component, String>, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance) { - - Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null; - - CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName()); - componentInstance.setIcon(origComponent.getIcon()); - Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), - ModelConverter.convertToToscaElement(origComponent), componentInstance); - if (updateResult.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName()); - result = Either.right(updateResult.right().value()); - } - if (result == null) { - Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft()); - String createdInstanceId = updateResult.left().value().getRight(); - CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata of the component instance {} has been updated to container component {}. ", createdInstanceId, updatedComponent.getName()); - result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId)); - } - return result; - } - - public Either<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent) { - return updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, new ComponentParametersView()); - } - - public Either<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, ComponentParametersView filter) { - - Either<Component, StorageOperationStatus> result = null; - - CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata belonging to container component {}. ", containerComponent.getName()); - - Either<TopologyTemplate, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), filter); - if (updateResult.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata belonging to container component {}. ", containerComponent.getName()); - result = Either.right(updateResult.right().value()); - } - if (result == null) { - Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value()); - CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata has been updated to container component {}. ", updatedComponent.getName()); - result = Either.left(updatedComponent); - } - return result; - } - // endregion - - public Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteComponentInstanceFromTopologyTemplate(Component containerComponent, String resourceInstanceId) { - - Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null; - - CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName()); - - Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.deleteComponentInstanceFromTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), resourceInstanceId); - if (updateResult.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName()); - result = Either.right(updateResult.right().value()); - } - if (result == null) { - Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft()); - String deletedInstanceId = updateResult.left().value().getRight(); - CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been deleted from container component {}. ", deletedInstanceId, updatedComponent.getName()); - result = Either.left(new ImmutablePair<>(updatedComponent, deletedInstanceId)); - } - return result; - } - - private String getNextComponentInstanceCounter(Component containerComponent, String originResourceName) { - - Integer nextCounter = 0; - - if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) { - - String normalizedName = ValidationUtils.normalizeComponentInstanceName(originResourceName); - Integer maxCounterFromNames = getMaxCounterFromNames(containerComponent, normalizedName); - Integer maxCounterFromIds = getMaxCounterFromIds(containerComponent, normalizedName); - - if (maxCounterFromNames == null && maxCounterFromIds != null) { - nextCounter = maxCounterFromIds + 1; - } else if (maxCounterFromIds == null && maxCounterFromNames != null) { - nextCounter = maxCounterFromNames + 1; - } else if (maxCounterFromIds != null && maxCounterFromNames != null) { - nextCounter = maxCounterFromNames > maxCounterFromIds ? maxCounterFromNames + 1 : maxCounterFromIds + 1; - } - } - return nextCounter.toString(); - } - - private Integer getMaxCounterFromNames(Component containerComponent, String normalizedName) { - - Integer maxCounter = 0; - List<String> countersStr = containerComponent.getComponentInstances().stream().filter(ci -> ci.getNormalizedName() != null && ci.getNormalizedName().startsWith(normalizedName)).map(ci -> ci.getNormalizedName().split(normalizedName)[1]) - .collect(Collectors.toList()); - - if (CollectionUtils.isEmpty(countersStr)) { - return null; - } - Integer currCounter = null; - for (String counter : countersStr) { - if (StringUtils.isEmpty(counter)) { - continue; - } - try { - currCounter = Integer.parseInt(counter); - } catch (Exception e) { - continue; - } - maxCounter = maxCounter < currCounter ? currCounter : maxCounter; - } - if (currCounter == null) { - return null; - } - return maxCounter; - } - - private Integer getMaxCounterFromIds(Component containerComponent, String normalizedName) { - - Integer maxCounter = 0; - List<String> countersStr = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId() != null && ci.getUniqueId().contains(normalizedName)).map(ci -> ci.getUniqueId().split(normalizedName)[1]) - .collect(Collectors.toList()); - - if (CollectionUtils.isEmpty(countersStr)) { - return null; - } - Integer currCounter = null; - for (String counter : countersStr) { - if (StringUtils.isEmpty(counter)) { - continue; - } - try { - currCounter = Integer.parseInt(counter); - } catch (Exception e) { - continue; - } - maxCounter = maxCounter < currCounter ? currCounter : maxCounter; - } - if (currCounter == null) { - return null; - } - return maxCounter; - } - - public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) { - return nodeTemplateOperation.associateResourceInstances(componentId, requirementDef); - - } - - public Either<List<InputDefinition>, StorageOperationStatus> createAndAssociateInputs(Map<String, InputDefinition> inputs, String componentId) { - - Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getVertexEither.isRight()) { - log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); - - } - - GraphVertex vertex = getVertexEither.left().value(); - Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue()))); - - StorageOperationStatus status = topologyTemplateOperation.associateInputsToComponent(vertex, inputsMap, componentId); - - if (StorageOperationStatus.OK == status) { - log.debug("Component created successfully!!!"); - List<InputDefinition> inputsResList = null; - if (inputsMap != null && !inputsMap.isEmpty()) { - inputsResList = inputsMap.values().stream().map(i -> new InputDefinition(i)).collect(Collectors.toList()); - } - return Either.left(inputsResList); - } - return Either.right(status); - - } - - public Either<List<InputDefinition>, StorageOperationStatus> addInputsToComponent(Map<String, InputDefinition> inputs, String componentId) { - - Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getVertexEither.isRight()) { - log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); - - } - - GraphVertex vertex = getVertexEither.left().value(); - Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue()))); - - StorageOperationStatus status = topologyTemplateOperation.addToscaDataToToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsMap, JsonPresentationFields.NAME); - - if (StorageOperationStatus.OK == status) { - log.debug("Component created successfully!!!"); - List<InputDefinition> inputsResList = null; - if (inputsMap != null && !inputsMap.isEmpty()) { - inputsResList = inputsMap.values().stream().map(i -> new InputDefinition(i)).collect(Collectors.toList()); - } - return Either.left(inputsResList); - } - return Either.right(status); - - } - - public Either<List<InputDefinition>, StorageOperationStatus> updateInputsToComponent(List<InputDefinition> inputs, String componentId) { - - Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getVertexEither.isRight()) { - log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); - - } - - GraphVertex vertex = getVertexEither.left().value(); - List<PropertyDataDefinition> inputsAsDataDef = inputs.stream().map(PropertyDataDefinition::new).collect(Collectors.toList()); - - StorageOperationStatus status = topologyTemplateOperation.updateToscaDataOfToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsAsDataDef, JsonPresentationFields.NAME); - - if (StorageOperationStatus.OK == status) { - log.debug("Component created successfully!!!"); - List<InputDefinition> inputsResList = null; - if (inputsAsDataDef != null && !inputsAsDataDef.isEmpty()) { - inputsResList = inputsAsDataDef.stream().map(InputDefinition::new).collect(Collectors.toList()); - } - return Either.left(inputsResList); - } - return Either.right(status); - - } - - // region - ComponentInstance - public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> associateComponentInstancePropertiesToComponent(Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) { - - Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getVertexEither.isRight()) { - log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); - - } - - GraphVertex vertex = getVertexEither.left().value(); - Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>(); - if (instProperties != null) { - - MapPropertiesDataDefinition propertiesMap; - for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) { - propertiesMap = new MapPropertiesDataDefinition(); - - propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e))); - - instPropsMap.put(entry.getKey(), propertiesMap); - } - } - - StorageOperationStatus status = topologyTemplateOperation.associateInstPropertiesToComponent(vertex, instPropsMap); - - if (StorageOperationStatus.OK == status) { - log.debug("Component created successfully!!!"); - return Either.left(instProperties); - } - return Either.right(status); - - } - - /** - * saves the instInputs as the updated instance inputs of the component container in DB - * @param instInputs - * @param componentId - * @return - */ - public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> updateComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instInputs, String componentId) { - if (instInputs == null || instInputs.isEmpty()) { - return Either.left(instInputs); - } - StorageOperationStatus status; - for ( Entry<String, List<ComponentInstanceInput>> inputsPerIntance : instInputs.entrySet() ) { - List<ComponentInstanceInput> toscaDataListPerInst = inputsPerIntance.getValue(); - List<String> pathKeysPerInst = new ArrayList<>(); - pathKeysPerInst.add(inputsPerIntance.getKey()); - status = topologyTemplateOperation.updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.NAME); - if ( status != StorageOperationStatus.OK) { - log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}", inputsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_INPUTS, status); - return Either.right(status); - } - } - - return Either.left(instInputs); - } - - /** - * saves the instProps as the updated instance properties of the component container in DB - * @param instProps - * @param componentId - * @return - */ - public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> updateComponentInstancePropsToComponent(Map<String, List<ComponentInstanceProperty>> instProps, String componentId) { - if (instProps == null || instProps.isEmpty()) { - return Either.left(instProps); - } - StorageOperationStatus status; - for ( Entry<String, List<ComponentInstanceProperty>> propsPerIntance : instProps.entrySet() ) { - List<ComponentInstanceProperty> toscaDataListPerInst = propsPerIntance.getValue(); - List<String> pathKeysPerInst = new ArrayList<>(); - pathKeysPerInst.add(propsPerIntance.getKey()); - status = topologyTemplateOperation.updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.NAME); - if ( status != StorageOperationStatus.OK) { - log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}", propsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_PROPERTIES, status); - return Either.right(status); - } - } - - return Either.left(instProps); - } - - public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> associateComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instInputs, String componentId) { - - Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getVertexEither.isRight()) { - log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); - - } - GraphVertex vertex = getVertexEither.left().value(); - Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>(); - if (instInputs != null) { - - MapPropertiesDataDefinition propertiesMap; - for (Entry<String, List<ComponentInstanceInput>> entry : instInputs.entrySet()) { - propertiesMap = new MapPropertiesDataDefinition(); - - propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e))); - - instPropsMap.put(entry.getKey(), propertiesMap); - } - } - - StorageOperationStatus status = topologyTemplateOperation.associateInstInputsToComponent(vertex, instPropsMap); - - if (StorageOperationStatus.OK == status) { - log.debug("Component created successfully!!!"); - return Either.left(instInputs); - } - return Either.right(status); - - } - - public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addComponentInstanceInputsToComponent(Component containerComponent, Map<String, List<ComponentInstanceInput>> instProperties) { - - StorageOperationStatus status = StorageOperationStatus.OK; - if (instProperties != null) { - - for (Entry<String, List<ComponentInstanceInput>> entry : instProperties.entrySet()) { - List<ComponentInstanceInput> props = entry.getValue(); - String componentInstanseId = entry.getKey(); - if (props != null && !props.isEmpty()) { - for (ComponentInstanceInput property : props) { - List<ComponentInstanceInput> componentInstancesInputs = containerComponent.getComponentInstancesInputs().get(componentInstanseId); - Optional<ComponentInstanceInput> instanceProperty = componentInstancesInputs.stream().filter(p -> p.getName().equals(property.getName())).findAny(); - if (instanceProperty.isPresent()) { - status = updateComponentInstanceInput(containerComponent, componentInstanseId, property); - } else { - status = addComponentInstanceInput(containerComponent, componentInstanseId, property); - } - if (status != StorageOperationStatus.OK) { - log.debug("Failed to update instance input {} for instance {} error {} ", property, componentInstanseId, status); - return Either.right(status); - } else { - log.trace("instance input {} for instance {} updated", property, componentInstanseId); - } - } - } - } - } - return Either.left(instProperties); - } - - public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addComponentInstancePropertiesToComponent(Component containerComponent, Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) { - - if (instProperties != null) { - - for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) { - List<ComponentInstanceProperty> props = entry.getValue(); - String componentInstanseId = entry.getKey(); - List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanseId); - if (props != null && !props.isEmpty()) { - for (ComponentInstanceProperty property : props) { - Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny(); - if (instanceProperty.isPresent()) { - updateComponentInstanceProperty(containerComponent, componentInstanseId, property); - } else { - addComponentInstanceProperty(containerComponent, componentInstanseId, property); - } - - } - } - } - } - - return Either.left(instProperties); - - } - - public StorageOperationStatus associateDeploymentArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts, String componentId, User user) { - - Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getVertexEither.isRight()) { - log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()); - - } - - GraphVertex vertex = getVertexEither.left().value(); - Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>(); - if (instDeploymentArtifacts != null) { - - MapArtifactDataDefinition artifactsMap; - for (Entry<String, Map<String, ArtifactDefinition>> entry : instDeploymentArtifacts.entrySet()) { - Map<String, ArtifactDefinition> artList = entry.getValue(); - Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); - artifactsMap = nodeTemplateOperation.prepareInstDeploymentArtifactPerInstance(artifacts, entry.getKey(), user, NodeTemplateOperation.HEAT_VF_ENV_NAME); - - instArtMap.put(entry.getKey(), artifactsMap); - } - } - - return topologyTemplateOperation.associateInstDeploymentArtifactsToComponent(vertex, instArtMap); +import java.util.*; +import java.util.Map.Entry; +import java.util.function.BiPredicate; +import java.util.stream.Collectors; - } +import static java.util.Objects.requireNonNull; +import static org.apache.commons.collections.CollectionUtils.isEmpty; +import static org.apache.commons.collections.CollectionUtils.isNotEmpty; - public StorageOperationStatus associateArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instArtifacts, String componentId, User user) { - Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getVertexEither.isRight()) { - log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()); +@org.springframework.stereotype.Component("tosca-operation-facade") +public class ToscaOperationFacade { - } + // region - Fields + + private static final String COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR = "Couldn't fetch a component with and UniqueId {}, error: {}"; + private static final String FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS = "Failed to find recently added property {} on the resource {}. Status is {}. "; + private static final String FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS = "Failed to get updated resource {}. Status is {}. "; + private static final String FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS = "Failed to add the property {} to the resource {}. Status is {}. "; + private static final String SERVICE = "service"; + private static final String NOT_SUPPORTED_COMPONENT_TYPE = "Not supported component type {}"; + private static final String COMPONENT_CREATED_SUCCESSFULLY = "Component created successfully!!!"; + private static final String COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR = "Couldn't fetch component with and unique id {}, error: {}"; + @Autowired + private NodeTypeOperation nodeTypeOperation; + @Autowired + private TopologyTemplateOperation topologyTemplateOperation; + @Autowired + private NodeTemplateOperation nodeTemplateOperation; + @Autowired + private GroupsOperation groupsOperation; + @Autowired + private TitanDao titanDao; + + private static final Logger log = Logger.getLogger(ToscaOperationFacade.class.getName()); + // endregion + + // region - ToscaElement - GetById + public static final String PROXY_SUFFIX = "_proxy"; + + public <T extends Component> Either<T, StorageOperationStatus> getToscaFullElement(String componentId) { + ComponentParametersView filters = new ComponentParametersView(); + filters.setIgnoreCapabiltyProperties(false); + filters.setIgnoreForwardingPath(false); + return getToscaElement(componentId, filters); + } + + public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId) { + + return getToscaElement(componentId, JsonParseFlagEnum.ParseAll); + + } + + public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, ComponentParametersView filters) { + + Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, filters.detectParseFlag()); + if (getVertexEither.isRight()) { + log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); + + } + return getToscaElementByOperation(getVertexEither.left().value(), filters); + } + + public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, JsonParseFlagEnum parseFlag) { + + Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, parseFlag); + if (getVertexEither.isRight()) { + log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); + + } + return getToscaElementByOperation(getVertexEither.left().value()); + } + + public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(GraphVertex componentVertex) { + return getToscaElementByOperation(componentVertex); + } + + public Either<Boolean, StorageOperationStatus> validateComponentExists(String componentId) { + + Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + TitanOperationStatus status = getVertexEither.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + return Either.left(false); + } else { + log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); + } + } + return Either.left(true); + } + + public <T extends Component> Either<T, StorageOperationStatus> findLastCertifiedToscaElementByUUID(T component) { + Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class); + props.put(GraphPropertyEnum.UUID, component.getUUID()); + props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + + Either<List<GraphVertex>, TitanOperationStatus> getVertexEither = titanDao.getByCriteria(ModelConverter.getVertexType(component), props); + if (getVertexEither.isRight()) { + log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); + + } + return getToscaElementByOperation(getVertexEither.left().value().get(0)); + } + + // endregion + // region - ToscaElement - GetByOperation + private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV) { + return getToscaElementByOperation(componentV, new ComponentParametersView()); + } + + private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV, ComponentParametersView filters) { + VertexTypeEnum label = componentV.getLabel(); + + ToscaElementOperation toscaOperation = getToscaElementOperation(componentV); + Either<ToscaElement, StorageOperationStatus> toscaElement; + String componentId = componentV.getUniqueId(); + if (toscaOperation != null) { + log.debug("Need to fetch tosca element for id {}", componentId); + toscaElement = toscaOperation.getToscaElement(componentV, filters); + } else { + log.debug("not supported tosca type {} for id {}", label, componentId); + toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST); + } + if (toscaElement.isRight()) { + return Either.right(toscaElement.right().value()); + } + return Either.left(ModelConverter.convertFromToscaElement(toscaElement.left().value())); + } + + // endregion + private ToscaElementOperation getToscaElementOperation(GraphVertex componentV) { + VertexTypeEnum label = componentV.getLabel(); + switch (label) { + case NODE_TYPE: + return nodeTypeOperation; + case TOPOLOGY_TEMPLATE: + return topologyTemplateOperation; + default: + return null; + } + } + + public <T extends Component> Either<T, StorageOperationStatus> createToscaComponent(T resource) { + ToscaElement toscaElement = ModelConverter.convertToToscaElement(resource); + + ToscaElementOperation toscaElementOperation = getToscaElementOperation(resource); + Either<ToscaElement, StorageOperationStatus> createToscaElement = toscaElementOperation.createToscaElement(toscaElement); + if (createToscaElement.isLeft()) { + log.debug(COMPONENT_CREATED_SUCCESSFULLY); + T dataModel = ModelConverter.convertFromToscaElement(createToscaElement.left().value()); + return Either.left(dataModel); + } + return Either.right(createToscaElement.right().value()); + } + + // region - ToscaElement Delete + public StorageOperationStatus markComponentToDelete(Component componentToDelete) { + + if ((componentToDelete.getIsDeleted() != null) && componentToDelete.getIsDeleted() && !componentToDelete.isHighestVersion()) { + // component already marked for delete + return StorageOperationStatus.OK; + } else { + + Either<GraphVertex, TitanOperationStatus> getResponse = titanDao.getVertexById(componentToDelete.getUniqueId(), JsonParseFlagEnum.ParseAll); + if (getResponse.isRight()) { + log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentToDelete.getUniqueId(), getResponse.right().value()); + return DaoStatusConverter.convertTitanStatusToStorageStatus(getResponse.right().value()); + + } + GraphVertex componentV = getResponse.left().value(); + + // same operation for node type and topology template operations + Either<GraphVertex, StorageOperationStatus> result = nodeTypeOperation.markComponentToDelete(componentV); + if (result.isRight()) { + return result.right().value(); + } + return StorageOperationStatus.OK; + } + } + + public <T extends Component> Either<T, StorageOperationStatus> deleteToscaComponent(String componentId) { + + Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll); + if (getVertexEither.isRight()) { + log.debug("Couldn't fetch component vertex with and unique id {}, error: {}", componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); + + } + Either<ToscaElement, StorageOperationStatus> deleteElement = deleteToscaElement(getVertexEither.left().value()); + if (deleteElement.isRight()) { + log.debug("Failed to delete component with and unique id {}, error: {}", componentId, deleteElement.right().value()); + return Either.right(deleteElement.right().value()); + } + T dataModel = ModelConverter.convertFromToscaElement(deleteElement.left().value()); + + return Either.left(dataModel); + } + + private Either<ToscaElement, StorageOperationStatus> deleteToscaElement(GraphVertex componentV) { + VertexTypeEnum label = componentV.getLabel(); + Either<ToscaElement, StorageOperationStatus> toscaElement; + Object componentId = componentV.getUniqueId(); + switch (label) { + case NODE_TYPE: + log.debug("Need to fetch node type for id {}", componentId); + toscaElement = nodeTypeOperation.deleteToscaElement(componentV); + break; + case TOPOLOGY_TEMPLATE: + log.debug("Need to fetch topology template for id {}", componentId); + toscaElement = topologyTemplateOperation.deleteToscaElement(componentV); + break; + default: + log.debug("not supported tosca type {} for id {}", label, componentId); + toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST); + break; + } + return toscaElement; + } + // endregion + + private ToscaElementOperation getToscaElementOperation(Component component) { + return ModelConverter.isAtomicComponent(component) ? nodeTypeOperation : topologyTemplateOperation; + } + + public <T extends Component> Either<T, StorageOperationStatus> getLatestByToscaResourceName(String toscaResourceName) { + return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName); + } + + public <T extends Component> Either<T, StorageOperationStatus> getFullLatestComponentByToscaResourceName(String toscaResourceName) { + 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) { + return getLatestByName(GraphPropertyEnum.NAME, resourceName); + + } + + public StorageOperationStatus validateCsarUuidUniqueness(String csarUUID) { + + Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class); + properties.put(GraphPropertyEnum.CSAR_UUID, csarUUID); + + Either<List<GraphVertex>, TitanOperationStatus> resources = titanDao.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata); + + if (resources.isRight()) { + if (resources.right().value() == TitanOperationStatus.NOT_FOUND) { + return StorageOperationStatus.OK; + } else { + log.debug("failed to get resources from graph with property name: {}", csarUUID); + return DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value()); + } + } + return StorageOperationStatus.ENTITY_ALREADY_EXISTS; + + } + + public <T extends Component> Either<Set<T>, StorageOperationStatus> getFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, ComponentTypeEnum componentType) { + Either<List<ToscaElement>, StorageOperationStatus> followedResources; + if (componentType == ComponentTypeEnum.RESOURCE) { + followedResources = nodeTypeOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType); + } else { + followedResources = topologyTemplateOperation.getFollowedComponent(userId, lifecycleStates, lastStateStates, componentType); + } + + Set<T> components = new HashSet<>(); + if (followedResources.isRight() && followedResources.right().value() != StorageOperationStatus.NOT_FOUND) { + return Either.right(followedResources.right().value()); + } + if (followedResources.isLeft()) { + List<ToscaElement> toscaElements = followedResources.left().value(); + toscaElements.forEach(te -> { + T component = ModelConverter.convertFromToscaElement(te); + components.add(component); + }); + } + return Either.left(components); + } + + public Either<Resource, StorageOperationStatus> getLatestCertifiedNodeTypeByToscaResourceName(String toscaResourceName) { + + return getLatestCertifiedByToscaResourceName(toscaResourceName, VertexTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata); + } + + public Either<Resource, StorageOperationStatus> getLatestCertifiedByToscaResourceName(String toscaResourceName, VertexTypeEnum vertexType, JsonParseFlagEnum parseFlag) { + + Either<Resource, StorageOperationStatus> result = null; + Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class); + props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName); + props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + Either<List<GraphVertex>, TitanOperationStatus> getLatestRes = titanDao.getByCriteria(vertexType, props, parseFlag); + + if (getLatestRes.isRight()) { + TitanOperationStatus status = getLatestRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ", vertexType, toscaResourceName, status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + if (result == null) { + List<GraphVertex> resources = getLatestRes.left().value(); + double version = 0.0; + GraphVertex highestResource = null; + for (GraphVertex resource : resources) { + double resourceVersion = Double.parseDouble((String) resource.getJsonMetadataField(JsonPresentationFields.VERSION)); + if (resourceVersion > version) { + version = resourceVersion; + highestResource = resource; + } + } + result = getToscaFullElement(highestResource.getUniqueId()); + } + return result; + } + + public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExists(String templateName) { + Either<Boolean, StorageOperationStatus> validateUniquenessRes = validateToscaResourceNameUniqueness(templateName); + if (validateUniquenessRes.isLeft()) { + return Either.left(!validateUniquenessRes.left().value()); + } + return validateUniquenessRes; + } + + public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) { + return nodeTemplateOperation.dissociateResourceInstances(componentId, requirementDef); + } + + /** + * Allows to get fulfilled requirement by relation and received predicate + */ + public Either<RequirementDataDefinition, StorageOperationStatus> getFulfilledRequirementByRelation(String componentId, String instanceId, RequirementCapabilityRelDef relation, BiPredicate<RelationshipInfo, RequirementDataDefinition> predicate) { + return nodeTemplateOperation.getFulfilledRequirementByRelation(componentId, instanceId, relation, predicate); + } + + /** + * Allows to get fulfilled capability by relation and received predicate + */ + 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()) { + return status.right().value(); + } + return StorageOperationStatus.OK; + } + + protected Either<Boolean, StorageOperationStatus> validateToscaResourceNameUniqueness(String name) { + + Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class); + properties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, name); + + Either<List<GraphVertex>, TitanOperationStatus> resources = titanDao.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata); + + if (resources.isRight() && resources.right().value() != TitanOperationStatus.NOT_FOUND) { + log.debug("failed to get resources from graph with property name: {}", name); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value())); + } + List<GraphVertex> resourceList = (resources.isLeft() ? resources.left().value() : null); + if (isNotEmpty(resourceList)) { + if (log.isDebugEnabled()) { + StringBuilder builder = new StringBuilder(); + for (GraphVertex resourceData : resourceList) { + builder.append(resourceData.getUniqueId() + "|"); + } + log.debug("resources with property name:{} exists in graph. found {}", name, builder); + } + return Either.left(false); + } else { + log.debug("resources with property name:{} does not exists in graph", name); + return Either.left(true); + } + + } + + // region - Component Update + + public Either<Resource, StorageOperationStatus> overrideComponent(Resource newComponent, Resource oldComponent) { + + copyArtifactsToNewComponent(newComponent, oldComponent); + + Either<GraphVertex, TitanOperationStatus> componentVEither = titanDao.getVertexById(oldComponent.getUniqueId(), JsonParseFlagEnum.NoParse); + if (componentVEither.isRight()) { + log.debug("Falied to fetch component {} error {}", oldComponent.getUniqueId(), componentVEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(componentVEither.right().value())); + } + GraphVertex componentv = componentVEither.left().value(); + Either<GraphVertex, TitanOperationStatus> parentVertexEither = titanDao.getParentVertex(componentv, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); + if (parentVertexEither.isRight() && parentVertexEither.right().value() != TitanOperationStatus.NOT_FOUND) { + log.debug("Falied to fetch parent version for component {} error {}", oldComponent.getUniqueId(), parentVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentVertexEither.right().value())); + } + + Either<ToscaElement, StorageOperationStatus> deleteToscaComponent = deleteToscaElement(componentv); + if (deleteToscaComponent.isRight()) { + log.debug("Falied to remove old component {} error {}", oldComponent.getUniqueId(), deleteToscaComponent.right().value()); + return Either.right(deleteToscaComponent.right().value()); + } + Either<Resource, StorageOperationStatus> createToscaComponent = createToscaComponent(newComponent); + if (createToscaComponent.isRight()) { + log.debug("Falied to create tosca element component {} error {}", newComponent.getUniqueId(), createToscaComponent.right().value()); + return Either.right(createToscaComponent.right().value()); + } + Resource newElement = createToscaComponent.left().value(); + Either<GraphVertex, TitanOperationStatus> newVersionEither = titanDao.getVertexById(newElement.getUniqueId(), JsonParseFlagEnum.NoParse); + if (newVersionEither.isRight()) { + log.debug("Falied to fetch new tosca element component {} error {}", newComponent.getUniqueId(), newVersionEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(newVersionEither.right().value())); + } + if (parentVertexEither.isLeft()) { + GraphVertex previousVersionV = parentVertexEither.left().value(); + TitanOperationStatus createEdge = titanDao.createEdge(previousVersionV, newVersionEither.left().value(), EdgeLabelEnum.VERSION, null); + if (createEdge != TitanOperationStatus.OK) { + log.debug("Falied to associate to previous version {} new version {} error {}", previousVersionV.getUniqueId(), newVersionEither.right().value(), createEdge); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge)); + } + } + return Either.left(newElement); + } + + void copyArtifactsToNewComponent(Resource newComponent, Resource oldComponent) { + // TODO - check if required + Map<String, ArtifactDefinition> toscaArtifacts = oldComponent.getToscaArtifacts(); + if (toscaArtifacts != null && !toscaArtifacts.isEmpty()) { + toscaArtifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE)); + } + newComponent.setToscaArtifacts(toscaArtifacts); + + Map<String, ArtifactDefinition> artifacts = oldComponent.getArtifacts(); + if (artifacts != null && !artifacts.isEmpty()) { + artifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE)); + } + newComponent.setArtifacts(artifacts); + + Map<String, ArtifactDefinition> depArtifacts = oldComponent.getDeploymentArtifacts(); + if (depArtifacts != null && !depArtifacts.isEmpty()) { + depArtifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE)); + } + newComponent.setDeploymentArtifacts(depArtifacts); + + newComponent.setGroups(oldComponent.getGroups()); + newComponent.setLastUpdateDate(null); + newComponent.setHighestVersion(true); + } + + public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate) { + return updateToscaElement(componentToUpdate, new ComponentParametersView()); + } + + public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate, ComponentParametersView filterResult) { + String componentId = componentToUpdate.getUniqueId(); + Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll); + if (getVertexEither.isRight()) { + log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); + } + GraphVertex elementV = getVertexEither.left().value(); + ToscaElementOperation toscaElementOperation = getToscaElementOperation(elementV); + + ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(componentToUpdate); + Either<ToscaElement, StorageOperationStatus> updateToscaElement = toscaElementOperation.updateToscaElement(toscaElementToUpdate, elementV, filterResult); + if (updateToscaElement.isRight()) { + log.debug("Failed to update tosca element {} error {}", componentId, updateToscaElement.right().value()); + return Either.right(updateToscaElement.right().value()); + } + return Either.left(ModelConverter.convertFromToscaElement(updateToscaElement.left().value())); + } + + private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName, 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); + Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); + + propertiesToMatch.put(property, nodeName); + propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + + propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); + + Either<List<GraphVertex>, TitanOperationStatus> highestResources = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, parseFlag); + if (highestResources.isRight()) { + TitanOperationStatus status = highestResources.right().value(); + log.debug("failed to find resource with name {}. status={} ", nodeName, status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + return result; + } + + List<GraphVertex> resources = highestResources.left().value(); + double version = 0.0; + GraphVertex highestResource = null; + for (GraphVertex vertex : resources) { + Object versionObj = vertex.getMetadataProperty(GraphPropertyEnum.VERSION); + double resourceVersion = Double.parseDouble((String) versionObj); + if (resourceVersion > version) { + version = resourceVersion; + highestResource = vertex; + } + } + return getToscaElementByOperation(highestResource, filter); + } + + // endregion + // region - Component Get By .. + private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName) { + return getLatestByName(property, nodeName, JsonParseFlagEnum.ParseMetadata); + } + + public <T extends Component> Either<List<T>, StorageOperationStatus> getBySystemName(ComponentTypeEnum componentType, String systemName) { + + Either<List<T>, StorageOperationStatus> result = null; + Either<T, StorageOperationStatus> getComponentRes; + List<T> components = new ArrayList<>(); + List<GraphVertex> componentVertices; + Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); + + propertiesToMatch.put(GraphPropertyEnum.SYSTEM_NAME, systemName); + if (componentType != null) + propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); + + propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); + + Either<List<GraphVertex>, TitanOperationStatus> getComponentsRes = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll); + if (getComponentsRes.isRight()) { + TitanOperationStatus status = getComponentsRes.right().value(); + log.debug("Failed to fetch the component with system name {}. Status is {} ", systemName, status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + if (result == null) { + componentVertices = getComponentsRes.left().value(); + for (GraphVertex componentVertex : componentVertices) { + getComponentRes = getToscaElementByOperation(componentVertex); + if (getComponentRes.isRight()) { + log.debug("Failed to get the component {}. Status is {} ", componentVertex.getJsonMetadataField(JsonPresentationFields.NAME), getComponentRes.right().value()); + result = Either.right(getComponentRes.right().value()); + break; + } + T componentBySystemName = getComponentRes.left().value(); + log.debug("Found component, id: {}", componentBySystemName.getUniqueId()); + components.add(componentBySystemName); + } + } + if (result == null) { + result = Either.left(components); + } + return result; + } + + public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version) { + return getComponentByNameAndVersion(componentType, name, version, JsonParseFlagEnum.ParseAll); + } + + public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version, JsonParseFlagEnum parseFlag) { + Either<T, StorageOperationStatus> result; + + Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class); + Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class); + + hasProperties.put(GraphPropertyEnum.NAME, name); + hasProperties.put(GraphPropertyEnum.VERSION, version); + hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true); + if (componentType != null) { + hasProperties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); + } + Either<List<GraphVertex>, TitanOperationStatus> getResourceRes = titanDao.getByCriteria(null, hasProperties, hasNotProperties, parseFlag); + if (getResourceRes.isRight()) { + TitanOperationStatus status = getResourceRes.right().value(); + log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + return result; + } + return getToscaElementByOperation(getResourceRes.left().value().get(0)); + } + + public Either<List<CatalogComponent>, StorageOperationStatus> getCatalogOrArchiveComponents(boolean isCatalog, List<OriginTypeEnum> excludeTypes) { + List<ResourceTypeEnum> excludedResourceTypes = Optional.ofNullable(excludeTypes).orElse(Collections.emptyList()).stream().filter(type -> !type.equals(OriginTypeEnum.SERVICE)).map(type -> ResourceTypeEnum.getTypeByName(type.name())) + .collect(Collectors.toList()); + return topologyTemplateOperation.getElementCatalogData(isCatalog, excludedResourceTypes); + } + + // endregion + public <T extends Component> Either<List<T>, StorageOperationStatus> getCatalogComponents(ComponentTypeEnum componentType, List<OriginTypeEnum> excludeTypes, boolean isHighestVersions) { + List<T> components = new ArrayList<>(); + Either<List<ToscaElement>, StorageOperationStatus> catalogDataResult; + List<ToscaElement> toscaElements = new ArrayList<>(); + List<ResourceTypeEnum> excludedResourceTypes = Optional.ofNullable(excludeTypes).orElse(Collections.emptyList()).stream().filter(type -> !type.equals(OriginTypeEnum.SERVICE)).map(type -> ResourceTypeEnum.getTypeByName(type.name())) + .collect(Collectors.toList()); + + switch (componentType) { + case RESOURCE: + catalogDataResult = nodeTypeOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE, excludedResourceTypes, isHighestVersions); + if (catalogDataResult.isRight()) { + return Either.right(catalogDataResult.right().value()); + } + toscaElements = catalogDataResult.left().value(); + break; + case SERVICE: + if (excludeTypes != null && excludeTypes.contains(OriginTypeEnum.SERVICE)) { + break; + } + catalogDataResult = topologyTemplateOperation.getElementCatalogData(ComponentTypeEnum.SERVICE, null, isHighestVersions); + if (catalogDataResult.isRight()) { + return Either.right(catalogDataResult.right().value()); + } + toscaElements = catalogDataResult.left().value(); + break; + default: + log.debug(NOT_SUPPORTED_COMPONENT_TYPE, componentType); + return Either.right(StorageOperationStatus.BAD_REQUEST); + } + toscaElements.forEach(te -> { + T component = ModelConverter.convertFromToscaElement(te); + components.add(component); + }); + return Either.left(components); + } + + public Either<List<String>, StorageOperationStatus> deleteMarkedElements(ComponentTypeEnum componentType) { + Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion; + switch (componentType) { + case RESOURCE: + allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType); + break; + case SERVICE: + case PRODUCT: + allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType); + break; + default: + log.debug(NOT_SUPPORTED_COMPONENT_TYPE, componentType); + return Either.right(StorageOperationStatus.BAD_REQUEST); + } + if (allComponentsMarkedForDeletion.isRight()) { + return Either.right(allComponentsMarkedForDeletion.right().value()); + } + List<GraphVertex> allMarked = allComponentsMarkedForDeletion.left().value(); + return Either.left(checkIfInUseAndDelete(allMarked)); + } + + private List<String> checkIfInUseAndDelete(List<GraphVertex> allMarked) { + final List<EdgeLabelEnum> forbiddenEdgeLabelEnums = Arrays.asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF, EdgeLabelEnum.ALLOTTED_OF); + List<String> deleted = new ArrayList<>(); + + for (GraphVertex elementV : allMarked) { + boolean isAllowedToDelete = true; + + for (EdgeLabelEnum edgeLabelEnum : forbiddenEdgeLabelEnums) { + Either<Edge, TitanOperationStatus> belongingEdgeByCriteria = titanDao.getBelongingEdgeByCriteria(elementV, edgeLabelEnum, null); + if (belongingEdgeByCriteria.isLeft()){ + log.debug("Marked element {} in use. don't delete it", elementV.getUniqueId()); + isAllowedToDelete = false; + break; + } + } + + if (isAllowedToDelete) { + Either<ToscaElement, StorageOperationStatus> deleteToscaElement = deleteToscaElement(elementV); + if (deleteToscaElement.isRight()) { + log.debug("Failed to delete marked element UniqueID {}, Name {}, error {}", elementV.getUniqueId(), elementV.getMetadataProperties().get(GraphPropertyEnum.NAME), deleteToscaElement.right().value()); + continue; + } + deleted.add(elementV.getUniqueId()); + } + } + return deleted; + } + + public Either<List<String>, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) { + Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion; + switch (componentType) { + case RESOURCE: + allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType); + break; + case SERVICE: + case PRODUCT: + allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType); + break; + default: + log.debug(NOT_SUPPORTED_COMPONENT_TYPE, componentType); + return Either.right(StorageOperationStatus.BAD_REQUEST); + } + if (allComponentsMarkedForDeletion.isRight()) { + return Either.right(allComponentsMarkedForDeletion.right().value()); + } + return Either.left(allComponentsMarkedForDeletion.left().value().stream().map(GraphVertex::getUniqueId).collect(Collectors.toList())); + } + + // region - Component Update + public Either<ImmutablePair<Component, String>, StorageOperationStatus> addComponentInstanceToTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance, boolean allowDeleted, User user) { + + Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null; + Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null; + if (StringUtils.isEmpty(componentInstance.getIcon())) { + componentInstance.setIcon(origComponent.getIcon()); + } + 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); + + if (addResult.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the component instance {} to container component {}. ", componentInstance.getName(), containerComponent.getName()); + result = Either.right(addResult.right().value()); + } + if (result == null) { + updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponent.getUniqueId()); + if (updateContainerComponentRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with updated component instance {}. ", containerComponent.getName(), componentInstance.getName()); + result = Either.right(updateContainerComponentRes.right().value()); + } + } + if (result == null) { + Component updatedComponent = ModelConverter.convertFromToscaElement(updateContainerComponentRes.left().value()); + String createdInstanceId = addResult.left().value().getRight(); + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been added to container component {}. ", createdInstanceId, updatedComponent.getName()); + result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId)); + } + return result; + } + + public StorageOperationStatus associateComponentInstancesToComponent(Component containerComponent, Map<ComponentInstance, Resource> resourcesInstancesMap, boolean allowDeleted) { + + StorageOperationStatus result = null; + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to add component instances to component {}", containerComponent.getUniqueId()); + + Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(containerComponent.getUniqueId(), JsonParseFlagEnum.ParseAll); + if (metadataVertex.isRight()) { + TitanOperationStatus status = metadataVertex.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); + } + if (result == null) { + result = nodeTemplateOperation.associateComponentInstancesToComponent(containerComponent, resourcesInstancesMap, metadataVertex.left().value(), allowDeleted); + } + return result; + } + + public Either<ImmutablePair<Component, String>, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance) { + + Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null; + + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName()); + componentInstance.setIcon(origComponent.getIcon()); + Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), + ModelConverter.convertToToscaElement(origComponent), componentInstance); + if (updateResult.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName()); + result = Either.right(updateResult.right().value()); + } + if (result == null) { + Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft()); + String createdInstanceId = updateResult.left().value().getRight(); + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata of the component instance {} has been updated to container component {}. ", createdInstanceId, updatedComponent.getName()); + result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId)); + } + return result; + } + + public Either<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent) { + return updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, new ComponentParametersView()); + } + + public Either<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, ComponentParametersView filter) { + + Either<Component, StorageOperationStatus> result = null; + + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata belonging to container component {}. ", containerComponent.getName()); + + Either<TopologyTemplate, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), filter); + if (updateResult.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata belonging to container component {}. ", containerComponent.getName()); + result = Either.right(updateResult.right().value()); + } + if (result == null) { + Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value()); + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata has been updated to container component {}. ", updatedComponent.getName()); + result = Either.left(updatedComponent); + } + return result; + } + // endregion + + public Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteComponentInstanceFromTopologyTemplate(Component containerComponent, String resourceInstanceId) { + + Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null; + + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName()); + + Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.deleteComponentInstanceFromTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), resourceInstanceId); + if (updateResult.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName()); + result = Either.right(updateResult.right().value()); + } + if (result == null) { + Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft()); + String deletedInstanceId = updateResult.left().value().getRight(); + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been deleted from container component {}. ", deletedInstanceId, updatedComponent.getName()); + result = Either.left(new ImmutablePair<>(updatedComponent, deletedInstanceId)); + } + return result; + } + + private String getNextComponentInstanceCounter(Component containerComponent, String originResourceName) { + Integer nextCounter = 0; + if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) { + String normalizedName = ValidationUtils.normalizeComponentInstanceName(originResourceName); + Integer maxCounter = getMaxCounterFromNamesAndIds(containerComponent, normalizedName); + if (maxCounter != null) { + nextCounter = maxCounter + 1; + } + } + return nextCounter.toString(); + } + + /** + * @return max counter of component instance Id's, null if not found + */ + private Integer getMaxCounterFromNamesAndIds(Component containerComponent, String normalizedName) { + List<String> countersInNames = containerComponent.getComponentInstances().stream() + .filter(ci -> ci.getNormalizedName() != null && ci.getNormalizedName().startsWith(normalizedName)) + .map(ci -> ci.getNormalizedName().split(normalizedName)[1]) + .collect(Collectors.toList()); + List<String> countersInIds = containerComponent.getComponentInstances().stream() + .filter(ci -> ci.getUniqueId() != null && ci.getUniqueId().contains(normalizedName)) + .map(ci -> ci.getUniqueId().split(normalizedName)[1]) + .collect(Collectors.toList()); + List<String> namesAndIdsList = new ArrayList<>(countersInNames); + namesAndIdsList.addAll(countersInIds); + return getMaxInteger(namesAndIdsList); + } + + private Integer getMaxInteger(List<String> counters) { + Integer maxCounter = 0; + Integer currCounter = null; + for (String counter : counters) { + try { + currCounter = Integer.parseInt(counter); + if (maxCounter < currCounter) { + maxCounter = currCounter; + } + } catch (NumberFormatException e) { + continue; + } + } + return currCounter == null ? null : maxCounter; + } + + public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) { + return nodeTemplateOperation.associateResourceInstances(componentId, requirementDef); + + } + + public Either<List<InputDefinition>, StorageOperationStatus> createAndAssociateInputs(Map<String, InputDefinition> inputs, String componentId) { + + Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); + + } + + GraphVertex vertex = getVertexEither.left().value(); + Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue()))); + + StorageOperationStatus status = topologyTemplateOperation.associateInputsToComponent(vertex, inputsMap, componentId); + + if (StorageOperationStatus.OK == status) { + log.debug(COMPONENT_CREATED_SUCCESSFULLY); + List<InputDefinition> inputsResList = null; + if (inputsMap != null && !inputsMap.isEmpty()) { + inputsResList = inputsMap.values().stream() + .map(InputDefinition::new) + .collect(Collectors.toList()); + } + return Either.left(inputsResList); + } + return Either.right(status); + + } + + public Either<List<InputDefinition>, StorageOperationStatus> addInputsToComponent(Map<String, InputDefinition> inputs, String componentId) { + + Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); + + } + + GraphVertex vertex = getVertexEither.left().value(); + Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue()))); + + StorageOperationStatus status = topologyTemplateOperation.addToscaDataToToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsMap, JsonPresentationFields.NAME); + + if (StorageOperationStatus.OK == status) { + log.debug(COMPONENT_CREATED_SUCCESSFULLY); + List<InputDefinition> inputsResList = null; + if (inputsMap != null && !inputsMap.isEmpty()) { + inputsResList = inputsMap.values().stream().map(InputDefinition::new).collect(Collectors.toList()); + } + return Either.left(inputsResList); + } + return Either.right(status); + + } + + public Either<List<InputDefinition>, StorageOperationStatus> updateInputsToComponent(List<InputDefinition> inputs, String componentId) { + + Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); + + } + + GraphVertex vertex = getVertexEither.left().value(); + List<PropertyDataDefinition> inputsAsDataDef = inputs.stream().map(PropertyDataDefinition::new).collect(Collectors.toList()); + + StorageOperationStatus status = topologyTemplateOperation.updateToscaDataOfToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsAsDataDef, JsonPresentationFields.NAME); + + if (StorageOperationStatus.OK == status) { + log.debug(COMPONENT_CREATED_SUCCESSFULLY); + List<InputDefinition> inputsResList = null; + if (inputsAsDataDef != null && !inputsAsDataDef.isEmpty()) { + inputsResList = inputsAsDataDef.stream().map(InputDefinition::new).collect(Collectors.toList()); + } + return Either.left(inputsResList); + } + return Either.right(status); + + } + + // region - ComponentInstance + public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> associateComponentInstancePropertiesToComponent(Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) { + + Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); + + } + + GraphVertex vertex = getVertexEither.left().value(); + Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>(); + if (instProperties != null) { + + MapPropertiesDataDefinition propertiesMap; + for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) { + propertiesMap = new MapPropertiesDataDefinition(); + + propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, e -> e))); + + instPropsMap.put(entry.getKey(), propertiesMap); + } + } + + StorageOperationStatus status = topologyTemplateOperation.associateInstPropertiesToComponent(vertex, instPropsMap); + + if (StorageOperationStatus.OK == status) { + log.debug(COMPONENT_CREATED_SUCCESSFULLY); + return Either.left(instProperties); + } + return Either.right(status); + + } + + /** + * saves the instInputs as the updated instance inputs of the component container in DB + */ + public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> updateComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instInputs, String componentId) { + if (instInputs == null || instInputs.isEmpty()) { + return Either.left(instInputs); + } + StorageOperationStatus status; + for (Entry<String, List<ComponentInstanceInput>> inputsPerIntance : instInputs.entrySet()) { + List<ComponentInstanceInput> toscaDataListPerInst = inputsPerIntance.getValue(); + List<String> pathKeysPerInst = new ArrayList<>(); + pathKeysPerInst.add(inputsPerIntance.getKey()); + status = topologyTemplateOperation.updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.NAME); + if (status != StorageOperationStatus.OK) { + log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}", inputsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_INPUTS, status); + return Either.right(status); + } + } + + return Either.left(instInputs); + } + + /** + * saves the instProps as the updated instance properties of the component container in DB + */ + public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> updateComponentInstancePropsToComponent(Map<String, List<ComponentInstanceProperty>> instProps, String componentId) { + if (instProps == null || instProps.isEmpty()) { + return Either.left(instProps); + } + StorageOperationStatus status; + for (Entry<String, List<ComponentInstanceProperty>> propsPerIntance : instProps.entrySet()) { + List<ComponentInstanceProperty> toscaDataListPerInst = propsPerIntance.getValue(); + List<String> pathKeysPerInst = new ArrayList<>(); + pathKeysPerInst.add(propsPerIntance.getKey()); + status = topologyTemplateOperation.updateToscaDataDeepElementsOfToscaElement(componentId, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, toscaDataListPerInst, pathKeysPerInst, JsonPresentationFields.NAME); + if (status != StorageOperationStatus.OK) { + log.debug("Failed to update component instance inputs for instance {} in component {} edge type {} error {}", propsPerIntance.getKey(), componentId, EdgeLabelEnum.INST_PROPERTIES, status); + return Either.right(status); + } + } + + return Either.left(instProps); + } + + public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> associateComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instInputs, String componentId) { + + Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); + + } + GraphVertex vertex = getVertexEither.left().value(); + Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>(); + if (instInputs != null) { + + MapPropertiesDataDefinition propertiesMap; + for (Entry<String, List<ComponentInstanceInput>> entry : instInputs.entrySet()) { + propertiesMap = new MapPropertiesDataDefinition(); + + propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, e -> e))); + + instPropsMap.put(entry.getKey(), propertiesMap); + } + } + + StorageOperationStatus status = topologyTemplateOperation.associateInstInputsToComponent(vertex, instPropsMap); + + if (StorageOperationStatus.OK == status) { + log.debug(COMPONENT_CREATED_SUCCESSFULLY); + return Either.left(instInputs); + } + return Either.right(status); + + } + + public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addComponentInstanceInputsToComponent(Component containerComponent, Map<String, List<ComponentInstanceInput>> instProperties) { + requireNonNull(instProperties); + StorageOperationStatus status; + for (Entry<String, List<ComponentInstanceInput>> entry : instProperties.entrySet()) { + List<ComponentInstanceInput> props = entry.getValue(); + String componentInstanceId = entry.getKey(); + if (!isEmpty(props)) { + for (ComponentInstanceInput property : props) { + List<ComponentInstanceInput> componentInstancesInputs = containerComponent.getComponentInstancesInputs().get(componentInstanceId); + Optional<ComponentInstanceInput> instanceProperty = componentInstancesInputs.stream() + .filter(p -> p.getName().equals(property.getName())) + .findAny(); + if (instanceProperty.isPresent()) { + status = updateComponentInstanceInput(containerComponent, componentInstanceId, property); + } else { + status = addComponentInstanceInput(containerComponent, componentInstanceId, property); + } + if (status != StorageOperationStatus.OK) { + log.debug("Failed to update instance input {} for instance {} error {} ", property, componentInstanceId, status); + return Either.right(status); + } else { + log.trace("instance input {} for instance {} updated", property, componentInstanceId); + } + } + } + } + return Either.left(instProperties); + } + + public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addComponentInstancePropertiesToComponent(Component containerComponent, Map<String, List<ComponentInstanceProperty>> instProperties) { + requireNonNull(instProperties); + StorageOperationStatus status; + for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) { + List<ComponentInstanceProperty> props = entry.getValue(); + String componentInstanceId = entry.getKey(); + List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanceId); + if (!isEmpty(props)) { + for (ComponentInstanceProperty property : props) { + Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream() + .filter(p -> p.getUniqueId().equals(property.getUniqueId())) + .findAny(); + if (instanceProperty.isPresent()) { + status = updateComponentInstanceProperty(containerComponent, componentInstanceId, property); + } else { + status = addComponentInstanceProperty(containerComponent, componentInstanceId, property); + } + if (status != StorageOperationStatus.OK) { + log.debug("Failed to update instance property {} for instance {} error {} ", property, componentInstanceId, status); + return Either.right(status); + } + } + } + } + return Either.left(instProperties); + } + + public StorageOperationStatus associateDeploymentArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts, String componentId, User user) { + + Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); + return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()); + + } + + GraphVertex vertex = getVertexEither.left().value(); + Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>(); + if (instDeploymentArtifacts != null) { + + MapArtifactDataDefinition artifactsMap; + for (Entry<String, Map<String, ArtifactDefinition>> entry : instDeploymentArtifacts.entrySet()) { + Map<String, ArtifactDefinition> artList = entry.getValue(); + Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); + artifactsMap = nodeTemplateOperation.prepareInstDeploymentArtifactPerInstance(artifacts, entry.getKey(), user, NodeTemplateOperation.HEAT_VF_ENV_NAME); + + instArtMap.put(entry.getKey(), artifactsMap); + } + } + + return topologyTemplateOperation.associateInstDeploymentArtifactsToComponent(vertex, instArtMap); + + } + + public StorageOperationStatus associateArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instArtifacts, String componentId) { + + Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); + return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()); + + } + + GraphVertex vertex = getVertexEither.left().value(); + Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>(); + if (instArtifacts != null) { + + MapArtifactDataDefinition artifactsMap; + for (Entry<String, Map<String, ArtifactDefinition>> entry : instArtifacts.entrySet()) { + Map<String, ArtifactDefinition> artList = entry.getValue(); + Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); + artifactsMap = new MapArtifactDataDefinition(artifacts); + + instArtMap.put(entry.getKey(), artifactsMap); + } + } + + return topologyTemplateOperation.associateInstArtifactsToComponent(vertex, instArtMap); + + } + + public StorageOperationStatus associateInstAttributeToComponentToInstances(Map<String, List<PropertyDefinition>> instArttributes, String componentId) { + + Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); + return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()); + + } + + GraphVertex vertex = getVertexEither.left().value(); + Map<String, MapPropertiesDataDefinition> instAttr = new HashMap<>(); + if (instArttributes != null) { + + MapPropertiesDataDefinition attributesMap; + for (Entry<String, List<PropertyDefinition>> entry : instArttributes.entrySet()) { + attributesMap = new MapPropertiesDataDefinition(); + attributesMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, e -> e))); + instAttr.put(entry.getKey(), attributesMap); + } + } + + return topologyTemplateOperation.associateInstAttributeToComponent(vertex, instAttr); + + } + // endregion + + public StorageOperationStatus associateOrAddCalculatedCapReq(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReg, String componentId) { + Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); + return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()); + + } + + GraphVertex vertex = getVertexEither.left().value(); + + Map<String, MapListRequirementDataDefinition> calcRequirements = new HashMap<>(); + + Map<String, MapListCapabilityDataDefinition> calcCapabilty = new HashMap<>(); + Map<String, MapCapabilityProperty> calculatedCapabilitiesProperties = new HashMap<>(); + if (instCapabilties != null) { + for (Entry<ComponentInstance, Map<String, List<CapabilityDefinition>>> entry : instCapabilties.entrySet()) { + + Map<String, List<CapabilityDefinition>> caps = entry.getValue(); + Map<String, ListCapabilityDataDefinition> mapToscaDataDefinition = new HashMap<>(); + for (Entry<String, List<CapabilityDefinition>> instCapability : caps.entrySet()) { + mapToscaDataDefinition.put(instCapability.getKey(), new ListCapabilityDataDefinition(instCapability.getValue().stream().map(CapabilityDataDefinition::new).collect(Collectors.toList()))); + } + + ComponentInstanceDataDefinition componentInstance = new ComponentInstanceDataDefinition(entry.getKey()); + MapListCapabilityDataDefinition capMap = nodeTemplateOperation.prepareCalculatedCapabiltyForNodeType(mapToscaDataDefinition, componentInstance); + + MapCapabilityProperty MapCapabilityProperty = ModelConverter.convertToMapOfMapCapabiltyProperties(caps, componentInstance.getUniqueId(), true); + + calcCapabilty.put(entry.getKey().getUniqueId(), capMap); + calculatedCapabilitiesProperties.put(entry.getKey().getUniqueId(), MapCapabilityProperty); + } + } + + if (instReg != null) { + for (Entry<ComponentInstance, Map<String, List<RequirementDefinition>>> entry : instReg.entrySet()) { + + Map<String, List<RequirementDefinition>> req = entry.getValue(); + Map<String, ListRequirementDataDefinition> mapToscaDataDefinition = new HashMap<>(); + for (Entry<String, List<RequirementDefinition>> instReq : req.entrySet()) { + mapToscaDataDefinition.put(instReq.getKey(), new ListRequirementDataDefinition(instReq.getValue().stream().map(RequirementDataDefinition::new).collect(Collectors.toList()))); + } + + MapListRequirementDataDefinition capMap = nodeTemplateOperation.prepareCalculatedRequirementForNodeType(mapToscaDataDefinition, new ComponentInstanceDataDefinition(entry.getKey())); + + calcRequirements.put(entry.getKey().getUniqueId(), capMap); + } + } + + return topologyTemplateOperation.associateOrAddCalcCapReqToComponent(vertex, calcRequirements, calcCapabilty, calculatedCapabilitiesProperties); + } + + private Either<List<Service>, StorageOperationStatus> getLatestVersionNonCheckoutServicesMetadataOnly(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps) { + List<Service> services = new ArrayList<>(); + List<LifecycleStateEnum> states = new ArrayList<>(); + // include props + hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); + hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + + // exclude props + states.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + hasNotProps.put(GraphPropertyEnum.STATE, states); + hasNotProps.put(GraphPropertyEnum.IS_DELETED, true); + hasNotProps.put(GraphPropertyEnum.IS_ARCHIVED, true); + return fetchServicesByCriteria(services, hasProps, hasNotProps); + } + + private Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractToscaElementsMetadataOnly(boolean isAbstract, ComponentTypeEnum componentTypeEnum, String internalComponentType, VertexTypeEnum vertexType) { + List<Service> services = null; + Map<GraphPropertyEnum, Object> hasProps = new EnumMap<>(GraphPropertyEnum.class); + Map<GraphPropertyEnum, Object> hasNotProps = new EnumMap<>(GraphPropertyEnum.class); + fillPropsMap(hasProps, hasNotProps, internalComponentType, componentTypeEnum, isAbstract, vertexType); + Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(vertexType, hasProps, hasNotProps, JsonParseFlagEnum.ParseMetadata); + if (getRes.isRight()) { + if (getRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { + return Either.left(new ArrayList<>()); + } else { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value())); + } + } + // region -> Fetch non checked-out services + if (internalComponentType != null && internalComponentType.toLowerCase().trim().equals(SERVICE) && VertexTypeEnum.NODE_TYPE == vertexType) { + Either<List<Service>, StorageOperationStatus> result = getLatestVersionNonCheckoutServicesMetadataOnly(new EnumMap<>(GraphPropertyEnum.class), new EnumMap<>(GraphPropertyEnum.class)); + if (result.isRight()) { + log.debug("Failed to fetch services for"); + return Either.right(result.right().value()); + } + services = result.left().value(); + if (log.isTraceEnabled() && isEmpty(services)) + log.trace("No relevant services available"); + } + // endregion + List<Component> nonAbstractLatestComponents = new ArrayList<>(); + ComponentParametersView params = new ComponentParametersView(true); + params.setIgnoreAllVersions(false); + for (GraphVertex vertexComponent : getRes.left().value()) { + Either<ToscaElement, StorageOperationStatus> componentRes = topologyTemplateOperation.getLightComponent(vertexComponent, componentTypeEnum, params); + if (componentRes.isRight()) { + log.debug("Failed to fetch light element for {} error {}", vertexComponent.getUniqueId(), componentRes.right().value()); + return Either.right(componentRes.right().value()); + } else { + Component component = ModelConverter.convertFromToscaElement(componentRes.left().value()); + nonAbstractLatestComponents.add(component); + } + } + if (CollectionUtils.isNotEmpty(services)) { + nonAbstractLatestComponents.addAll(services); + } + return Either.left(nonAbstractLatestComponents); + } + + public Either<ComponentMetadataData, StorageOperationStatus> getLatestComponentMetadataByUuid(String componentUuid, JsonParseFlagEnum parseFlag, Boolean isHighest) { + + Either<ComponentMetadataData, StorageOperationStatus> result; + Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class); + hasProperties.put(GraphPropertyEnum.UUID, componentUuid); + if (isHighest != null) { + hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest); + } + Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); + propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); + propertiesNotToMatch.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683 + + Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(null, hasProperties, propertiesNotToMatch, parseFlag); + if (getRes.isRight()) { + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value())); + } else { + List<ComponentMetadataData> latestVersionList = getRes.left().value().stream().map(ModelConverter::convertToComponentMetadata).collect(Collectors.toList()); + ComponentMetadataData latestVersion = latestVersionList.size() == 1 ? latestVersionList.get(0) + : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getMetadataDataDefinition().getVersion()), Double.parseDouble(c2.getMetadataDataDefinition().getVersion()))).get(); + result = Either.left(latestVersion); + } + return result; + } + + public Either<ComponentMetadataData, StorageOperationStatus> getComponentMetadata(String componentId) { + Either<ComponentMetadataData, StorageOperationStatus> result; + Either<GraphVertex, TitanOperationStatus> getRes = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata); + if (getRes.isRight()) { + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value())); + } else { + ComponentMetadataData componentMetadata = ModelConverter.convertToComponentMetadata(getRes.left().value()); + result = Either.left(componentMetadata); + } + return result; + } + + public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractComponents(boolean isAbstract, ComponentTypeEnum componentTypeEnum, + String internalComponentType, List<String> componentUids) { + + List<Component> components = new ArrayList<>(); + if (componentUids == null) { + Either<List<String>, StorageOperationStatus> componentUidsRes = getComponentUids(isAbstract, componentTypeEnum, internalComponentType); + if (componentUidsRes.isRight()) { + return Either.right(componentUidsRes.right().value()); + } + componentUids = componentUidsRes.left().value(); + } + if (!isEmpty(componentUids)) { + for (String componentUid : componentUids) { + ComponentParametersView componentParametersView = buildComponentViewForNotAbstract(); + if ("vl".equalsIgnoreCase(internalComponentType)) { + componentParametersView.setIgnoreCapabilities(false); + componentParametersView.setIgnoreRequirements(false); + } + Either<ToscaElement, StorageOperationStatus> getToscaElementRes = nodeTemplateOperation.getToscaElementOperation(componentTypeEnum).getLightComponent(componentUid, componentTypeEnum, componentParametersView); + if (getToscaElementRes.isRight()) { + log.debug("Failed to fetch resource for error is {}", getToscaElementRes.right().value()); + return Either.right(getToscaElementRes.right().value()); + } + Component component = ModelConverter.convertFromToscaElement(getToscaElementRes.left().value()); + nullifySomeComponentProperties(component); + components.add(component); + } + } + return Either.left(components); + } + + public void nullifySomeComponentProperties(Component component) { + component.setContactId(null); + component.setCreationDate(null); + component.setCreatorUserId(null); + component.setCreatorFullName(null); + component.setLastUpdateDate(null); + component.setLastUpdaterUserId(null); + component.setLastUpdaterFullName(null); + component.setNormalizedName(null); + } + + private Either<List<String>, StorageOperationStatus> getComponentUids(boolean isAbstract, ComponentTypeEnum componentTypeEnum, String internalComponentType) { + + Either<List<Component>, StorageOperationStatus> getToscaElementsRes = getLatestVersionNotAbstractMetadataOnly(isAbstract, componentTypeEnum, internalComponentType); + if (getToscaElementsRes.isRight()) { + return Either.right(getToscaElementsRes.right().value()); + } + List<Component> collection = getToscaElementsRes.left().value(); + List<String> componentUids; + if (collection == null) { + componentUids = new ArrayList<>(); + } else { + componentUids = collection.stream() + .map(Component::getUniqueId) + .collect(Collectors.toList()); + } + return Either.left(componentUids); + } + + private ComponentParametersView buildComponentViewForNotAbstract() { + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.disableAll(); + componentParametersView.setIgnoreCategories(false); + componentParametersView.setIgnoreAllVersions(false); + return componentParametersView; + } + + public Either<Boolean, StorageOperationStatus> validateComponentNameExists(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) { + Either<Boolean, StorageOperationStatus> result = validateComponentNameUniqueness(name, resourceType, componentType); + if (result.isLeft()) { + result = Either.left(!result.left().value()); + } + return result; + } + + public Either<Boolean, StorageOperationStatus> validateComponentNameUniqueness(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) { + VertexTypeEnum vertexType = ModelConverter.isAtomicComponent(resourceType) ? VertexTypeEnum.NODE_TYPE : VertexTypeEnum.TOPOLOGY_TEMPLATE; + String normalizedName = ValidationUtils.normaliseComponentName(name); + Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class); + properties.put(GraphPropertyEnum.NORMALIZED_NAME, normalizedName); + properties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); + + Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(vertexType, properties, JsonParseFlagEnum.NoParse); + if (vertexEither.isRight() && vertexEither.right().value() != TitanOperationStatus.NOT_FOUND) { + log.debug("failed to get vertex from graph with property normalizedName: {}", normalizedName); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value())); + } + List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null; + if (vertexList != null && !vertexList.isEmpty()) { + return Either.left(false); + } else { + return Either.left(true); + } + } + + private void fillNodeTypePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType) { + switch (internalComponentType.toLowerCase()) { + case "vf": + case "cvfc": + hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, Arrays.asList(ResourceTypeEnum.VFCMT.name(), ResourceTypeEnum.Configuration.name())); + break; + case SERVICE: + case "pnf": + case "cr": + hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, Arrays.asList(ResourceTypeEnum.VFC.name(), ResourceTypeEnum.VFCMT.name())); + break; + case "vl": + hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VL.name()); + break; + default: + break; + } + } + + private void fillTopologyTemplatePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, ComponentTypeEnum componentTypeEnum) { + switch (componentTypeEnum) { + case RESOURCE: + hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); + break; + case SERVICE: + hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); + break; + default: + break; + } + hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.CVFC.name()); + } + + private void fillPropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType, ComponentTypeEnum componentTypeEnum, boolean isAbstract, VertexTypeEnum internalVertexType) { + hasNotProps.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()); + + hasNotProps.put(GraphPropertyEnum.IS_DELETED, true); + hasNotProps.put(GraphPropertyEnum.IS_ARCHIVED, true); + hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + if (VertexTypeEnum.NODE_TYPE == internalVertexType) { + hasProps.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract); + if (internalComponentType != null) { + fillNodeTypePropsMap(hasProps, hasNotProps, internalComponentType); + } + } else { + fillTopologyTemplatePropsMap(hasProps, hasNotProps, componentTypeEnum); + } + } + + private List<VertexTypeEnum> getInternalVertexTypes(ComponentTypeEnum componentTypeEnum, String internalComponentType) { + List<VertexTypeEnum> internalVertexTypes = new ArrayList<>(); + if (ComponentTypeEnum.RESOURCE == componentTypeEnum) { + internalVertexTypes.add(VertexTypeEnum.NODE_TYPE); + } + if (ComponentTypeEnum.SERVICE == componentTypeEnum || SERVICE.equalsIgnoreCase(internalComponentType)) { + internalVertexTypes.add(VertexTypeEnum.TOPOLOGY_TEMPLATE); + } + return internalVertexTypes; + } + + public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractMetadataOnly(boolean isAbstract, ComponentTypeEnum componentTypeEnum, String internalComponentType) { + List<VertexTypeEnum> internalVertexTypes = getInternalVertexTypes(componentTypeEnum, internalComponentType); + List<Component> result = new ArrayList<>(); + for (VertexTypeEnum vertexType : internalVertexTypes) { + Either<List<Component>, StorageOperationStatus> listByVertexType = getLatestVersionNotAbstractToscaElementsMetadataOnly(isAbstract, componentTypeEnum, internalComponentType, vertexType); + if (listByVertexType.isRight()) { + return listByVertexType; + } + result.addAll(listByVertexType.left().value()); + } + return Either.left(result); + + } + + 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); + return getComponentListByUuid(componentUuid, propertiesToMatch); + } + + 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); + + if (additionalPropertiesToMatch != null) { + propertiesToMatch.putAll(additionalPropertiesToMatch); + } + + propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid); + + Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); + propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); + propertiesNotToMatch.put(GraphPropertyEnum.IS_ARCHIVED, true); //US382674, US382683 + + Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll); + + if (vertexEither.isRight()) { + log.debug("Couldn't fetch metadata for component with uuid {}, error: {}", componentUuid, vertexEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value())); + } + List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null; + + if (vertexList == null || vertexList.isEmpty()) { + log.debug("Component with uuid {} was not found", componentUuid); + return Either.right(StorageOperationStatus.NOT_FOUND); + } + + ArrayList<Component> latestComponents = new ArrayList<>(); + for (GraphVertex vertex : vertexList) { + Either<Component, StorageOperationStatus> toscaElementByOperation = getToscaElementByOperation(vertex); + + if (toscaElementByOperation.isRight()) { + log.debug("Could not fetch the following Component by UUID {}", vertex.getUniqueId()); + return Either.right(toscaElementByOperation.right().value()); + } + + latestComponents.add(toscaElementByOperation.left().value()); + } + + if (latestComponents.size() > 1) { + for (Component component : latestComponents) { + if (component.isHighestVersion()) { + LinkedList<Component> highestComponent = new LinkedList<>(); + highestComponent.add(component); + return Either.left(highestComponent); + } + } + } + + return Either.left(latestComponents); + } + + public Either<Component, StorageOperationStatus> getLatestServiceByUuid(String serviceUuid) { + Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + 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, propertiesToMatch); + + if (latestVersionListEither.isRight()) { + return Either.right(latestVersionListEither.right().value()); + } + + List<Component> latestVersionList = latestVersionListEither.left().value(); + + if (latestVersionList.isEmpty()) { + return Either.right(StorageOperationStatus.NOT_FOUND); + } + Component component = latestVersionList.size() == 1 ? latestVersionList.get(0) : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getVersion()), Double.parseDouble(c2.getVersion()))).get(); + + return Either.left(component); + } + + public Either<List<Resource>, StorageOperationStatus> getAllCertifiedResources(boolean isAbstract, Boolean isHighest) { + + List<Resource> resources = new ArrayList<>(); + Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); + + propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract); + if (isHighest != null) { + propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest); + } + propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); + propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); + + Either<List<GraphVertex>, TitanOperationStatus> getResourcesRes = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll); + + if (getResourcesRes.isRight()) { + log.debug("Failed to fetch all certified resources. Status is {}", getResourcesRes.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getResourcesRes.right().value())); + } + List<GraphVertex> resourceVerticies = getResourcesRes.left().value(); + for (GraphVertex resourceV : resourceVerticies) { + Either<Resource, StorageOperationStatus> getResourceRes = getToscaElement(resourceV); + if (getResourceRes.isRight()) { + return Either.right(getResourceRes.right().value()); + } + resources.add(getResourceRes.left().value()); + } + return Either.left(resources); + } + + public <T extends Component> Either<T, StorageOperationStatus> getLatestByNameAndVersion(String name, String version, JsonParseFlagEnum parseFlag) { + Either<T, StorageOperationStatus> result; + + Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class); + Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class); + + hasProperties.put(GraphPropertyEnum.NAME, name); + hasProperties.put(GraphPropertyEnum.VERSION, version); + hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + + hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true); + + Either<List<GraphVertex>, TitanOperationStatus> getResourceRes = titanDao.getByCriteria(null, hasProperties, hasNotProperties, parseFlag); + if (getResourceRes.isRight()) { + TitanOperationStatus status = getResourceRes.right().value(); + log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + return result; + } + return getToscaElementByOperation(getResourceRes.left().value().get(0)); + } + + public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName) { + return getLatestComponentByCsarOrName(componentType, csarUUID, systemName, JsonParseFlagEnum.ParseAll); + } + + public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName, JsonParseFlagEnum parseFlag) { + Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class); + Map<GraphPropertyEnum, Object> propsHasNot = new EnumMap<>(GraphPropertyEnum.class); + props.put(GraphPropertyEnum.CSAR_UUID, csarUUID); + props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + if (componentType != null) { + props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); + } + propsHasNot.put(GraphPropertyEnum.IS_DELETED, true); + + GraphVertex resourceMetadataData = null; + List<GraphVertex> resourceMetadataDataList = null; + Either<List<GraphVertex>, TitanOperationStatus> byCsar = titanDao.getByCriteria(null, props, propsHasNot, JsonParseFlagEnum.ParseMetadata); + if (byCsar.isRight()) { + if (TitanOperationStatus.NOT_FOUND == byCsar.right().value()) { + // Fix Defect DE256036 + if (StringUtils.isEmpty(systemName)) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.NOT_FOUND)); + } + + props.clear(); + props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + props.put(GraphPropertyEnum.SYSTEM_NAME, systemName); + Either<List<GraphVertex>, TitanOperationStatus> bySystemname = titanDao.getByCriteria(null, props, JsonParseFlagEnum.ParseMetadata); + if (bySystemname.isRight()) { + log.debug("getLatestResourceByCsarOrName - Failed to find by system name {} error {} ", systemName, bySystemname.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(bySystemname.right().value())); + } + if (bySystemname.left().value().size() > 2) { + log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) must return only 2 latest version, but was returned - {}", bySystemname.left().value().size()); + return Either.right(StorageOperationStatus.GENERAL_ERROR); + } + resourceMetadataDataList = bySystemname.left().value(); + if (resourceMetadataDataList.size() == 1) { + resourceMetadataData = resourceMetadataDataList.get(0); + } else { + for (GraphVertex curResource : resourceMetadataDataList) { + if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) { + resourceMetadataData = curResource; + break; + } + } + } + if (resourceMetadataData == null) { + log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) returned 2 latest CERTIFIED versions"); + return Either.right(StorageOperationStatus.GENERAL_ERROR); + } + if (resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID) != null && !((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID)).equals(csarUUID)) { + log.debug("getLatestResourceByCsarOrName - same system name {} but different csarUUID. exist {} and new {} ", systemName, resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID), csarUUID); + // correct error will be returned from create flow. with all + // correct audit records!!!!! + return Either.right(StorageOperationStatus.NOT_FOUND); + } + return getToscaElement((String) resourceMetadataData.getUniqueId()); + } + } else { + resourceMetadataDataList = byCsar.left().value(); + if (resourceMetadataDataList.size() > 2) { + log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) must return only 2 latest version, but was returned - {}", byCsar.left().value().size()); + return Either.right(StorageOperationStatus.GENERAL_ERROR); + } + if (resourceMetadataDataList.size() == 1) { + resourceMetadataData = resourceMetadataDataList.get(0); + } else { + for (GraphVertex curResource : resourceMetadataDataList) { + if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) { + resourceMetadataData = curResource; + break; + } + } + } + if (resourceMetadataData == null) { + log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) returned 2 latest CERTIFIED versions"); + return Either.right(StorageOperationStatus.GENERAL_ERROR); + } + return getToscaElement((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID), parseFlag); + } + return null; + } + + public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends) { + + String currentTemplateNameChecked = templateNameExtends; + + while (currentTemplateNameChecked != null && !currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) { + Either<Resource, StorageOperationStatus> latestByToscaResourceName = getLatestByToscaResourceName(currentTemplateNameChecked); + + if (latestByToscaResourceName.isRight()) { + return latestByToscaResourceName.right().value() == StorageOperationStatus.NOT_FOUND ? Either.left(false) : Either.right(latestByToscaResourceName.right().value()); + } + + Resource value = latestByToscaResourceName.left().value(); + + if (value.getDerivedFrom() != null) { + currentTemplateNameChecked = value.getDerivedFrom().get(0); + } else { + currentTemplateNameChecked = null; + } + } + + return (currentTemplateNameChecked != null && currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) ? Either.left(true) : Either.left(false); + } + + public Either<List<Component>, StorageOperationStatus> fetchMetaDataByResourceType(String resourceType, ComponentParametersView filterBy) { + Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class); + props.put(GraphPropertyEnum.RESOURCE_TYPE, resourceType); + props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + Map<GraphPropertyEnum, Object> propsHasNotToMatch = new EnumMap<>(GraphPropertyEnum.class); + 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())); + } + + List<GraphVertex> vertexList = resourcesByTypeEither.left().value(); + List<Component> components = new ArrayList<>(); + + for (GraphVertex vertex : vertexList) { + components.add(getToscaElementByOperation(vertex, filterBy).left().value()); + } + + return Either.left(components); + } + + public void commit() { + titanDao.commit(); + } + + public Either<Service, StorageOperationStatus> updateDistributionStatus(Service service, User user, DistributionStatusEnum distributionStatus) { + Either<GraphVertex, StorageOperationStatus> updateDistributionStatus = topologyTemplateOperation.updateDistributionStatus(service.getUniqueId(), user, distributionStatus); + if (updateDistributionStatus.isRight()) { + return Either.right(updateDistributionStatus.right().value()); + } + GraphVertex serviceV = updateDistributionStatus.left().value(); + service.setDistributionStatus(distributionStatus); + service.setLastUpdateDate((Long) serviceV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE)); + return Either.left(service); + } + + public Either<ComponentMetadataData, StorageOperationStatus> updateComponentLastUpdateDateOnGraph(Component component) { + + Either<ComponentMetadataData, StorageOperationStatus> result = null; + GraphVertex serviceVertex; + Either<GraphVertex, TitanOperationStatus> updateRes = null; + Either<GraphVertex, TitanOperationStatus> getRes = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.ParseMetadata); + if (getRes.isRight()) { + TitanOperationStatus status = getRes.right().value(); + log.error("Failed to fetch component {}. status is {}", component.getUniqueId(), status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + if (result == null) { + serviceVertex = getRes.left().value(); + long lastUpdateDate = System.currentTimeMillis(); + serviceVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate); + component.setLastUpdateDate(lastUpdateDate); + updateRes = titanDao.updateVertex(serviceVertex); + if (updateRes.isRight()) { + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateRes.right().value())); + } + } + if (result == null) { + result = Either.left(ModelConverter.convertToComponentMetadata(updateRes.left().value())); + } + return result; + } + + public TitanDao getTitanDao() { + return titanDao; + } + + public Either<List<Service>, StorageOperationStatus> getCertifiedServicesWithDistStatus(Set<DistributionStatusEnum> distStatus) { + Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + + return getServicesWithDistStatus(distStatus, propertiesToMatch); + } + + public Either<List<Service>, StorageOperationStatus> getServicesWithDistStatus(Set<DistributionStatusEnum> distStatus, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) { + + List<Service> servicesAll = new ArrayList<>(); + + Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); + + if (additionalPropertiesToMatch != null && !additionalPropertiesToMatch.isEmpty()) { + propertiesToMatch.putAll(additionalPropertiesToMatch); + } + + propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); + + propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); + + if (distStatus != null && !distStatus.isEmpty()) { + for (DistributionStatusEnum state : distStatus) { + propertiesToMatch.put(GraphPropertyEnum.DISTRIBUTION_STATUS, state.name()); + Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria = fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch); + if (fetchServicesByCriteria.isRight()) { + return fetchServicesByCriteria; + } else { + servicesAll = fetchServicesByCriteria.left().value(); + } + } + return Either.left(servicesAll); + } else { + return fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch); + } + } + + private Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria(List<Service> servicesAll, Map<GraphPropertyEnum, Object> propertiesToMatch, Map<GraphPropertyEnum, Object> propertiesNotToMatch) { + Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll); + if (getRes.isRight()) { + if (getRes.right().value() != TitanOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch, propertiesNotToMatch, getRes.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value())); + } + } else { + for (GraphVertex vertex : getRes.left().value()) { + Either<ToscaElement, StorageOperationStatus> getServiceRes = topologyTemplateOperation.getLightComponent(vertex, ComponentTypeEnum.SERVICE, new ComponentParametersView(true)); + + if (getServiceRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ", vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value()); + return Either.right(getServiceRes.right().value()); + } else { + servicesAll.add(ModelConverter.convertFromToscaElement(getServiceRes.left().value())); + } + } + } + return Either.left(servicesAll); + } + + public void rollback() { + titanDao.rollback(); + } + + public StorageOperationStatus addDeploymentArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map<String, ArtifactDefinition> finalDeploymentArtifacts) { + Map<String, ArtifactDataDefinition> instDeplArtifacts = finalDeploymentArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); + + return nodeTemplateOperation.addDeploymentArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts); + } + + public StorageOperationStatus addInformationalArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map<String, ArtifactDefinition> artifacts) { + StorageOperationStatus status = StorageOperationStatus.OK; + if (MapUtils.isNotEmpty(artifacts)) { + Map<String, ArtifactDataDefinition> instDeplArtifacts = artifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); + status = nodeTemplateOperation.addInformationalArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts); + } + return status; + } + + public StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId) { + return nodeTemplateOperation.generateCustomizationUUIDOnInstance(componentId, instanceId); + } + + public StorageOperationStatus generateCustomizationUUIDOnInstanceGroup(String componentId, String instanceId, List<String> groupInstances) { + return nodeTemplateOperation.generateCustomizationUUIDOnInstanceGroup(componentId, instanceId, groupInstances); + } + + /* + * adds property to a resource + * @warn this method has SIDE EFFECT on ownerId ,use it with caution + * */ + public Either<PropertyDefinition, StorageOperationStatus> addPropertyToResource(String propertyName, PropertyDefinition newPropertyDefinition, Resource resource) { + + Either<PropertyDefinition, StorageOperationStatus> result = null; + Either<Component, StorageOperationStatus> getUpdatedComponentRes = null; + newPropertyDefinition.setName(propertyName); + StorageOperationStatus status = getToscaElementOperation(resource).addToscaDataToToscaElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, propertyName, resource.getName(), status); + result = Either.right(status); + } + if (result == null) { + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreProperties(false); + getUpdatedComponentRes = getToscaElement(resource.getUniqueId(), filter); + if (getUpdatedComponentRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, resource.getUniqueId(), getUpdatedComponentRes.right().value()); + result = Either.right(status); + } + } + if (result == null) { + PropertyDefinition newProperty = null; + List<PropertyDefinition> properties = ((Resource) getUpdatedComponentRes.left().value()).getProperties(); + if (CollectionUtils.isNotEmpty(properties)) { + Optional<PropertyDefinition> newPropertyOptional = properties.stream().filter(p -> p.getName().equals(propertyName)).findAny(); + if (newPropertyOptional.isPresent()) { + newProperty = newPropertyOptional.get(); + } + } + if (newProperty == null) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS, propertyName, resource.getUniqueId(), StorageOperationStatus.NOT_FOUND); + result = Either.right(StorageOperationStatus.NOT_FOUND); + } else { + result = Either.left(newProperty); + } + } + return result; + } + + public StorageOperationStatus deletePropertyOfResource(Resource resource, String propertyName) { + return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, propertyName, JsonPresentationFields.NAME); + } + + public StorageOperationStatus deleteAttributeOfResource(Component component, String attributeName) { + return getToscaElementOperation(component).deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, attributeName, JsonPresentationFields.NAME); + } + + public StorageOperationStatus deleteInputOfResource(Component resource, String inputName) { + return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputName, JsonPresentationFields.NAME); + } + + public Either<PropertyDefinition, StorageOperationStatus> updatePropertyOfResource(Resource resource, PropertyDefinition newPropertyDefinition) { + + Either<Component, StorageOperationStatus> getUpdatedComponentRes = null; + Either<PropertyDefinition, StorageOperationStatus> result = null; + StorageOperationStatus status = getToscaElementOperation(resource).updateToscaDataOfToscaElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newPropertyDefinition.getName(), resource.getName(), status); + result = Either.right(status); + } + if (result == null) { + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreProperties(false); + getUpdatedComponentRes = getToscaElement(resource.getUniqueId(), filter); + if (getUpdatedComponentRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, resource.getUniqueId(), getUpdatedComponentRes.right().value()); + result = Either.right(status); + } + } + if (result == null) { + Optional<PropertyDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getProperties().stream().filter(p -> p.getName().equals(newPropertyDefinition.getName())).findAny(); + if (newProperty.isPresent()) { + result = Either.left(newProperty.get()); + } else { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS, newPropertyDefinition.getName(), resource.getUniqueId(), StorageOperationStatus.NOT_FOUND); + result = Either.right(StorageOperationStatus.NOT_FOUND); + } + } + return result; + } + + public Either<PropertyDefinition, StorageOperationStatus> addAttributeOfResource(Component component, PropertyDefinition newAttributeDef) { + + Either<Component, StorageOperationStatus> getUpdatedComponentRes = null; + Either<PropertyDefinition, StorageOperationStatus> result = null; + if (newAttributeDef.getUniqueId() == null || newAttributeDef.getUniqueId().isEmpty()) { + String attUniqueId = UniqueIdBuilder.buildAttributeUid(component.getUniqueId(), newAttributeDef.getName()); + newAttributeDef.setUniqueId(attUniqueId); + } + + StorageOperationStatus status = getToscaElementOperation(component).addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getName(), status); + result = Either.right(status); + } + if (result == null) { + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreAttributesFrom(false); + getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter); + if (getUpdatedComponentRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(), getUpdatedComponentRes.right().value()); + result = Either.right(status); + } + } + if (result == null) { + Optional<PropertyDefinition> newAttribute = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny(); + if (newAttribute.isPresent()) { + result = Either.left(newAttribute.get()); + } else { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND); + result = Either.right(StorageOperationStatus.NOT_FOUND); + } + } + return result; + } + + public Either<PropertyDefinition, StorageOperationStatus> updateAttributeOfResource(Component component, PropertyDefinition newAttributeDef) { + + Either<Component, StorageOperationStatus> getUpdatedComponentRes = null; + Either<PropertyDefinition, StorageOperationStatus> result = null; + StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getName(), status); + result = Either.right(status); + } + if (result == null) { + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreAttributesFrom(false); + getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter); + if (getUpdatedComponentRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(), getUpdatedComponentRes.right().value()); + result = Either.right(status); + } + } + if (result == null) { + Optional<PropertyDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny(); + if (newProperty.isPresent()) { + result = Either.left(newProperty.get()); + } else { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND); + result = Either.right(StorageOperationStatus.NOT_FOUND); + } + } + return result; + } + + public Either<InputDefinition, StorageOperationStatus> updateInputOfComponent(Component component, InputDefinition newInputDefinition) { + + Either<Component, StorageOperationStatus> getUpdatedComponentRes = null; + Either<InputDefinition, StorageOperationStatus> result = null; + StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputDefinition, JsonPresentationFields.NAME); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the input {} to the component {}. Status is {}. ", newInputDefinition.getName(), component.getName(), status); + result = Either.right(status); + } + if (result == null) { + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreInputs(false); + getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter); + if (getUpdatedComponentRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(), getUpdatedComponentRes.right().value()); + result = Either.right(status); + } + } + if (result == null) { + Optional<InputDefinition> updatedInput = getUpdatedComponentRes.left().value().getInputs().stream().filter(p -> p.getName().equals(newInputDefinition.getName())).findAny(); + if (updatedInput.isPresent()) { + result = Either.left(updatedInput.get()); + } else { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently updated inputs {} on the resource {}. Status is {}. ", newInputDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND); + result = Either.right(StorageOperationStatus.NOT_FOUND); + } + } + return result; + } + + /** + * method - ename the group instances after referenced container name renamed flow - VF rename -(triggers)-> Group rename + * + * @param containerComponent - container such as service + * @param componentInstance - context component + * @param componentInstanceId - id + * @return - successfull/failed status + **/ + public Either<StorageOperationStatus, StorageOperationStatus> cleanAndAddGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, String componentInstanceId) { + String uniqueId = componentInstance.getUniqueId(); + StorageOperationStatus status = nodeTemplateOperation.deleteToscaDataDeepElementsBlockOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, uniqueId); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete group instances for container {}. error {] ", componentInstanceId, status); + return Either.right(status); + } + if (componentInstance.getGroupInstances() != null) { + status = addGroupInstancesToComponentInstance(containerComponent, componentInstance, componentInstance.getGroupInstances()); + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add group instances for container {}. error {] ", componentInstanceId, status); + return Either.right(status); + } + } + return Either.left(status); + } + + public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupDefinition> groups, Map<String, List<ArtifactDefinition>> groupInstancesArtifacts) { + return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groups, groupInstancesArtifacts); + } + + public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsOnComponent(Component component, List<GroupDataDefinition> updatedGroups) { + return groupsOperation.updateGroups(component, updatedGroups, true); + } + + public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstancesOnComponent(Component component, String instanceId, List<GroupInstance> updatedGroupInstances) { + return groupsOperation.updateGroupInstances(component, instanceId, updatedGroupInstances); + } + + public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupInstance> groupInstances) { + return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groupInstances); + } + + public StorageOperationStatus addDeploymentArtifactsToComponentInstance(Component containerComponent, ComponentInstance componentInstance, Map<String, ArtifactDefinition> deploymentArtifacts) { + return nodeTemplateOperation.addDeploymentArtifactsToComponentInstance(containerComponent, componentInstance, deploymentArtifacts); + } + + public StorageOperationStatus updateComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) { + return nodeTemplateOperation.updateComponentInstanceProperty(containerComponent, componentInstanceId, property); + } + + public StorageOperationStatus updateComponentInstanceProperties(Component containerComponent, String componentInstanceId, List<ComponentInstanceProperty> properties) { + return nodeTemplateOperation.updateComponentInstanceProperties(containerComponent, componentInstanceId, properties); + } + + + public StorageOperationStatus addComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) { + return nodeTemplateOperation.addComponentInstanceProperty(containerComponent, componentInstanceId, property); + } + + public StorageOperationStatus updateComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) { + return nodeTemplateOperation.updateComponentInstanceInput(containerComponent, componentInstanceId, property); + } + + public StorageOperationStatus updateComponentInstanceInputs(Component containerComponent, String componentInstanceId, List<ComponentInstanceInput> instanceInputs) { + return nodeTemplateOperation.updateComponentInstanceInputs(containerComponent, componentInstanceId, instanceInputs); + } + + public StorageOperationStatus addComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) { + return nodeTemplateOperation.addComponentInstanceInput(containerComponent, componentInstanceId, property); + } + + public void setNodeTypeOperation(NodeTypeOperation nodeTypeOperation) { + this.nodeTypeOperation = nodeTypeOperation; + } + + public void setTopologyTemplateOperation(TopologyTemplateOperation topologyTemplateOperation) { + this.topologyTemplateOperation = topologyTemplateOperation; + } + + public StorageOperationStatus deleteComponentInstanceInputsFromTopologyTemplate(Component containerComponent, List<InputDefinition> inputsToDelete) { + return topologyTemplateOperation.deleteToscaDataElements(containerComponent.getUniqueId(), EdgeLabelEnum.INPUTS, inputsToDelete.stream().map(PropertyDataDefinition::getName).collect(Collectors.toList())); + } + + public StorageOperationStatus updateComponentInstanceCapabiltyProperty(Component containerComponent, String componentInstanceUniqueId, String capabilityUniqueId, ComponentInstanceProperty property) { + 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, MapCapabilityProperty> MapCapabilityPropertyMap = convertComponentCapabilitiesProperties(containerComponent); + return nodeTemplateOperation.overrideComponentCapabilitiesProperties(containerComponent, MapCapabilityPropertyMap); + } + + public StorageOperationStatus deleteAllCalculatedCapabilitiesRequirements(String topologyTemplateId) { + StorageOperationStatus status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES); + if (status == StorageOperationStatus.OK) { + status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS); + } + if (status == StorageOperationStatus.OK) { + status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES); + } + return status; + } + + public Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived(Resource clonedResource) { + String componentId = clonedResource.getUniqueId(); + Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); + + } + GraphVertex nodeTypeV = getVertexEither.left().value(); + + ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(clonedResource); + + Either<ToscaElement, StorageOperationStatus> shouldUpdateDerivedVersion = nodeTypeOperation.shouldUpdateDerivedVersion(toscaElementToUpdate, nodeTypeV); + if (shouldUpdateDerivedVersion.isRight() && StorageOperationStatus.OK != shouldUpdateDerivedVersion.right().value()) { + log.debug("Failed to update derived version for node type {} derived {}, error: {}", componentId, clonedResource.getDerivedFrom().get(0), shouldUpdateDerivedVersion.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); + } + if (shouldUpdateDerivedVersion.isLeft()) { + return Either.left(ModelConverter.convertFromToscaElement(shouldUpdateDerivedVersion.left().value())); + } + return Either.left(clonedResource); + } + + /** + * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId + */ + 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, MapCapabilityProperty> convertComponentCapabilitiesProperties(Component currComponent) { + Map<String, MapCapabilityProperty> map = ModelConverter.extractCapabilityPropertiesFromGroups(currComponent.getGroups(), true); + map.putAll(ModelConverter.extractCapabilityProperteisFromInstances(currComponent.getComponentInstances(), true)); + return map; + } + + private Optional<MapCapabilityProperty> 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(COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_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 StorageOperationStatus associatePoliciesToComponent(String componentId, List<PolicyDefinition> policies) { + log.debug("#associatePoliciesToComponent - associating policies for component {}.", componentId); + return titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata) + .either(containerVertex -> topologyTemplateOperation.addPoliciesToToscaElement(containerVertex, policies), + DaoStatusConverter::convertTitanStatusToStorageStatus); + } + + 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(COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_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(COULDNT_FETCH_A_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); + status = DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()); + } + if (status == null) { + status = topologyTemplateOperation.removePolicyFromToscaElement(getVertexEither.left().value(), policyId); + } + return status; + } + + public boolean canAddGroups(String componentId) { + GraphVertex vertex = titanDao.getVertexById(componentId) + .left() + .on(this::onTitanError); + return topologyTemplateOperation.hasEdgeOfType(vertex, EdgeLabelEnum.GROUPS); + } + + GraphVertex onTitanError(TitanOperationStatus toe) { + throw new StorageException( + DaoStatusConverter.convertTitanStatusToStorageStatus(toe)); + } + + public void updateNamesOfCalculatedCapabilitiesRequirements(String componentId){ + topologyTemplateOperation + .updateNamesOfCalculatedCapabilitiesRequirements(componentId, getTopologyTemplate(componentId)); + } + + public void revertNamesOfCalculatedCapabilitiesRequirements(String componentId) { + topologyTemplateOperation + .revertNamesOfCalculatedCapabilitiesRequirements(componentId, getTopologyTemplate(componentId)); + } + + private TopologyTemplate getTopologyTemplate(String componentId) { + return (TopologyTemplate)topologyTemplateOperation + .getToscaElement(componentId, getFilterComponentWithCapProperties()) + .left() + .on(this::throwStorageException); + } + + private ComponentParametersView getFilterComponentWithCapProperties() { + ComponentParametersView filter = new ComponentParametersView(); + filter.setIgnoreCapabiltyProperties(false); + return filter; + } + + private ToscaElement throwStorageException(StorageOperationStatus status) { + throw new StorageException(status); + } - GraphVertex vertex = getVertexEither.left().value(); - Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>(); - if (instArtifacts != null) { - - MapArtifactDataDefinition artifactsMap; - for (Entry<String, Map<String, ArtifactDefinition>> entry : instArtifacts.entrySet()) { - Map<String, ArtifactDefinition> artList = entry.getValue(); - Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); - artifactsMap = new MapArtifactDataDefinition(artifacts); - - instArtMap.put(entry.getKey(), artifactsMap); - } - } - - return topologyTemplateOperation.associateInstArtifactsToComponent(vertex, instArtMap); - - } - - public StorageOperationStatus associateInstAttributeToComponentToInstances(Map<String, List<PropertyDefinition>> instArttributes, String componentId) { - - Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getVertexEither.isRight()) { - log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()); - - } - - GraphVertex vertex = getVertexEither.left().value(); - Map<String, MapPropertiesDataDefinition> instAttr = new HashMap<>(); - if (instArttributes != null) { - - MapPropertiesDataDefinition attributesMap; - for (Entry<String, List<PropertyDefinition>> entry : instArttributes.entrySet()) { - attributesMap = new MapPropertiesDataDefinition(); - attributesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e))); - instAttr.put(entry.getKey(), attributesMap); - } - } - - return topologyTemplateOperation.associateInstAttributeToComponent(vertex, instAttr); - - } - // endregion - - public StorageOperationStatus associateCalculatedCapReq(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReg, String componentId) { - Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getVertexEither.isRight()) { - log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()); - - } - - GraphVertex vertex = getVertexEither.left().value(); - - Map<String, MapListRequirementDataDefinition> calcRequirements = new HashMap<>(); - - Map<String, MapListCapabiltyDataDefinition> calcCapabilty = new HashMap<>(); - Map<String, MapCapabiltyProperty> calculatedCapabilitiesProperties = new HashMap<>(); - ; - if (instCapabilties != null) { - for (Entry<ComponentInstance, Map<String, List<CapabilityDefinition>>> entry : instCapabilties.entrySet()) { - - Map<String, List<CapabilityDefinition>> caps = entry.getValue(); - Map<String, ListCapabilityDataDefinition> mapToscaDataDefinition = new HashMap<>(); - for (Entry<String, List<CapabilityDefinition>> instCapability : caps.entrySet()) { - mapToscaDataDefinition.put(instCapability.getKey(), new ListCapabilityDataDefinition(instCapability.getValue().stream().map(iCap -> new CapabilityDataDefinition(iCap)).collect(Collectors.toList()))); - } - - ComponentInstanceDataDefinition componentInstance = new ComponentInstanceDataDefinition(entry.getKey()); - MapListCapabiltyDataDefinition capMap = nodeTemplateOperation.prepareCalculatedCapabiltyForNodeType(mapToscaDataDefinition, componentInstance); - - MapCapabiltyProperty mapCapabiltyProperty = ModelConverter.convertToMapOfMapCapabiltyProperties(caps, componentInstance.getUniqueId(), true); - - calcCapabilty.put(entry.getKey().getUniqueId(), capMap); - calculatedCapabilitiesProperties.put(entry.getKey().getUniqueId(), mapCapabiltyProperty); - } - } - - if (instReg != null) { - for (Entry<ComponentInstance, Map<String, List<RequirementDefinition>>> entry : instReg.entrySet()) { - - Map<String, List<RequirementDefinition>> req = entry.getValue(); - Map<String, ListRequirementDataDefinition> mapToscaDataDefinition = new HashMap<>(); - for (Entry<String, List<RequirementDefinition>> instReq : req.entrySet()) { - mapToscaDataDefinition.put(instReq.getKey(), new ListRequirementDataDefinition(instReq.getValue().stream().map(iCap -> new RequirementDataDefinition(iCap)).collect(Collectors.toList()))); - } - - MapListRequirementDataDefinition capMap = nodeTemplateOperation.prepareCalculatedRequirementForNodeType(mapToscaDataDefinition, new ComponentInstanceDataDefinition(entry.getKey())); - - calcRequirements.put(entry.getKey().getUniqueId(), capMap); - } - } - - StorageOperationStatus status = topologyTemplateOperation.associateCalcCapReqToComponent(vertex, calcRequirements, calcCapabilty, calculatedCapabilitiesProperties); - - return status; - } - - private Either<List<Service>, StorageOperationStatus> getLatestVersionNonCheckoutServicesMetadataOnly(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps) { - List<Service> services = new ArrayList<>(); - List<LifecycleStateEnum> states = new ArrayList<>(); - // include props - hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); - hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - - // exclude props - states.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - hasNotProps.put(GraphPropertyEnum.STATE, states); - hasNotProps.put(GraphPropertyEnum.IS_DELETED, true); - return fetchServicesByCriteria(services, hasProps, hasNotProps); - } - - private Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractToscaElementsMetadataOnly(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, VertexTypeEnum vertexType) { - List<Service> services = null; - Map<GraphPropertyEnum, Object> hasProps = new EnumMap<>(GraphPropertyEnum.class); - Map<GraphPropertyEnum, Object> hasNotProps = new EnumMap<>(GraphPropertyEnum.class); - fillPropsMap(hasProps, hasNotProps, internalComponentType, componentTypeEnum, isAbstract, vertexType); - Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(vertexType, hasProps, hasNotProps, JsonParseFlagEnum.ParseMetadata); - if (getRes.isRight()) { - if (getRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { - return Either.left(new ArrayList<>()); - } else { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value())); - } - } else { - // region -> Fetch non checked-out services - if (internalComponentType != null && internalComponentType.toLowerCase().trim().equals("service") && VertexTypeEnum.NODE_TYPE == vertexType) { // and NODE_TYPE==vertextype - Either<List<Service>, StorageOperationStatus> result = getLatestVersionNonCheckoutServicesMetadataOnly(new EnumMap<>(GraphPropertyEnum.class), new EnumMap<>(GraphPropertyEnum.class)); - if (result.isRight()) { - log.debug("Failed to fetch services for"); - return Either.right(result.right().value()); - } - services = result.left().value(); - if (CollectionUtils.isEmpty(services) && log.isTraceEnabled()) - log.trace("No relevant services available"); - } - // endregion - List<Component> nonAbstractLatestComponents = new ArrayList<>(); - ComponentParametersView params = new ComponentParametersView(true); - params.setIgnoreAllVersions(false); - for (GraphVertex vertexComponent : getRes.left().value()) { - Either<ToscaElement, StorageOperationStatus> componentRes = topologyTemplateOperation.getLightComponent(vertexComponent, componentTypeEnum, params); - if (componentRes.isRight()) { - log.debug("Failed to fetch ligth element for {} error {}", vertexComponent.getUniqueId(), componentRes.right().value()); - return Either.right(componentRes.right().value()); - } else { - Component component = ModelConverter.convertFromToscaElement(componentRes.left().value()); - nonAbstractLatestComponents.add(component); - } - } - if (CollectionUtils.isNotEmpty(services)) - nonAbstractLatestComponents.addAll(services); - return Either.left(nonAbstractLatestComponents); - } - } - - public Either<ComponentMetadataData, StorageOperationStatus> getLatestComponentMetadataByUuid(String componentUuid, JsonParseFlagEnum parseFlag, Boolean isHighest) { - - Either<ComponentMetadataData, StorageOperationStatus> result; - - Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class); - - hasProperties.put(GraphPropertyEnum.UUID, componentUuid); - if (isHighest != null) { - hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest.booleanValue()); - } - - Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); - propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); - - Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(null, hasProperties, propertiesNotToMatch, parseFlag); - if (getRes.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value())); - } else { - List<ComponentMetadataData> latestVersionList = getRes.left().value().stream().map(ModelConverter::convertToComponentMetadata).collect(Collectors.toList()); - ComponentMetadataData latestVersion = latestVersionList.size() == 1 ? latestVersionList.get(0) - : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getMetadataDataDefinition().getVersion()), Double.parseDouble(c2.getMetadataDataDefinition().getVersion()))).get(); - result = Either.left(latestVersion); - } - return result; - } - - public Either<ComponentMetadataData, StorageOperationStatus> getComponentMetadata(String componentId) { - - Either<ComponentMetadataData, StorageOperationStatus> result; - Either<GraphVertex, TitanOperationStatus> getRes = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata); - if (getRes.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value())); - } else { - ComponentMetadataData componentMetadata = ModelConverter.convertToComponentMetadata(getRes.left().value()); - result = Either.left(componentMetadata); - } - return result; - } - - public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractComponents(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids) { - - Either<List<Component>, StorageOperationStatus> result = null; - List<Component> components = new ArrayList<>(); - if (componentUids == null) { - Either<List<String>, StorageOperationStatus> componentUidsRes = getComponentUids(isAbstract, isHighest, componentTypeEnum, internalComponentType, componentUids); - if (componentUidsRes.isRight()) { - result = Either.right(componentUidsRes.right().value()); - } else { - componentUids = componentUidsRes.left().value(); - } - } - if (!componentUids.isEmpty()) { - for (String componentUid : componentUids) { - ComponentParametersView componentParametersView = buildComponentViewForNotAbstract(); - if (internalComponentType != null && "vl".equalsIgnoreCase(internalComponentType)) { - componentParametersView.setIgnoreCapabilities(false); - componentParametersView.setIgnoreRequirements(false); - } - Either<ToscaElement, StorageOperationStatus> getToscaElementRes = nodeTemplateOperation.getToscaElementOperation(componentTypeEnum).getLightComponent(componentUid, componentTypeEnum, componentParametersView); - if (getToscaElementRes.isRight()) { - if (log.isDebugEnabled()) - log.debug("Failed to fetch resource for error is {}", getToscaElementRes.right().value()); - result = Either.right(getToscaElementRes.right().value()); - break; - } - Component component = ModelConverter.convertFromToscaElement(getToscaElementRes.left().value()); - component.setContactId(null); - component.setCreationDate(null); - component.setCreatorUserId(null); - component.setCreatorFullName(null); - component.setLastUpdateDate(null); - component.setLastUpdaterUserId(null); - component.setLastUpdaterFullName(null); - component.setNormalizedName(null); - components.add(component); - } - } - if (result == null) { - result = Either.left(components); - } - return result; - } - - private Either<List<String>, StorageOperationStatus> getComponentUids(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids) { - - Either<List<String>, StorageOperationStatus> result = null; - Either<List<Component>, StorageOperationStatus> getToscaElementsRes = getLatestVersionNotAbstractMetadataOnly(isAbstract, isHighest, componentTypeEnum, internalComponentType); - if (getToscaElementsRes.isRight()) { - result = Either.right(getToscaElementsRes.right().value()); - } else { - List<Component> collection = getToscaElementsRes.left().value(); - if (collection == null) { - componentUids = new ArrayList<>(); - } else { - componentUids = collection.stream().map(p -> p.getUniqueId()).collect(Collectors.toList()); - } - } - if (result == null) { - result = Either.left(componentUids); - } - return result; - } - - private ComponentParametersView buildComponentViewForNotAbstract() { - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnoreCategories(false); - componentParametersView.setIgnoreAllVersions(false); - return componentParametersView; - } - - public Either<Boolean, StorageOperationStatus> validateComponentNameExists(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) { - Either<Boolean, StorageOperationStatus> result = validateComponentNameUniqueness(name, resourceType, componentType); - if (result.isLeft()) { - result = Either.left(!result.left().value()); - } - return result; - } - - public Either<Boolean, StorageOperationStatus> validateComponentNameUniqueness(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) { - VertexTypeEnum vertexType = ModelConverter.isAtomicComponent(resourceType) ? VertexTypeEnum.NODE_TYPE : VertexTypeEnum.TOPOLOGY_TEMPLATE; - String normalizedName = ValidationUtils.normaliseComponentName(name); - Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class); - properties.put(GraphPropertyEnum.NORMALIZED_NAME, normalizedName); - properties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); - - Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(vertexType, properties, JsonParseFlagEnum.NoParse); - if (vertexEither.isRight() && vertexEither.right().value() != TitanOperationStatus.NOT_FOUND) { - log.debug("failed to get vertex from graph with property normalizedName: {}", normalizedName); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value())); - } - List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null; - if (vertexList != null && !vertexList.isEmpty()) { - return Either.left(false); - } else { - return Either.left(true); - } - } - - private void fillNodeTypePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType) { - switch (internalComponentType.toLowerCase()) { - case "vf": - case "cvfc": - hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, Arrays.asList(ResourceTypeEnum.VFCMT.name(), ResourceTypeEnum.Configuration.name())); - break; - case "service": - case "pnf": - case "cr": - hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, Arrays.asList(ResourceTypeEnum.VFC.name(), ResourceTypeEnum.VFCMT.name())); - break; - case "vl": - hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VL.name()); - break; - default: - break; - } - } - - private void fillTopologyTemplatePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, ComponentTypeEnum componentTypeEnum, String internalComponentType) { - switch (componentTypeEnum) { - case RESOURCE: - hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); - break; - case SERVICE: - hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); - break; - default: - break; - } - switch (internalComponentType.toLowerCase()) { - case "vf": - case "cvfc": - hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.CVFC.name()); - break; - case "service": - hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.CVFC.name()); - break; - default: - break; - } - } - - private void fillPropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType, ComponentTypeEnum componentTypeEnum, boolean isAbstract, VertexTypeEnum internalVertexType) { - hasNotProps.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()); - - hasNotProps.put(GraphPropertyEnum.IS_DELETED, true); - hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - if (VertexTypeEnum.NODE_TYPE == internalVertexType) { - hasProps.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract); - if (internalComponentType != null) { - fillNodeTypePropsMap(hasProps, hasNotProps, internalComponentType); - } - } else { - fillTopologyTemplatePropsMap(hasProps, hasNotProps, componentTypeEnum, internalComponentType); - } - } - - private List<VertexTypeEnum> getInternalVertexTypes(ComponentTypeEnum componentTypeEnum, String internalComponentType) { - List<VertexTypeEnum> internalVertexTypes = new ArrayList<>(); - if (ComponentTypeEnum.RESOURCE == componentTypeEnum) { - internalVertexTypes.add(VertexTypeEnum.NODE_TYPE); - } - if (ComponentTypeEnum.SERVICE == componentTypeEnum || "service".equalsIgnoreCase(internalComponentType) || "vf".equalsIgnoreCase(internalComponentType)) { - internalVertexTypes.add(VertexTypeEnum.TOPOLOGY_TEMPLATE); - } - return internalVertexTypes; - } - - public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractMetadataOnly(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType) { - List<VertexTypeEnum> internalVertexTypes = getInternalVertexTypes(componentTypeEnum, internalComponentType); - List<Component> result = new ArrayList<>(); - for (VertexTypeEnum vertexType : internalVertexTypes) { - Either<List<Component>, StorageOperationStatus> listByVertexType = getLatestVersionNotAbstractToscaElementsMetadataOnly(isAbstract, isHighest, componentTypeEnum, internalComponentType, vertexType); - if (listByVertexType.isRight()) { - return listByVertexType; - } - result.addAll(listByVertexType.left().value()); - } - return Either.left(result); - - } - - 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); - - if (additionalPropertiesToMatch != null) { - propertiesToMatch.putAll(additionalPropertiesToMatch); - } - - propertiesToMatch.put(GraphPropertyEnum.UUID, componentUuid); - - 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()) { - log.debug("Couldn't fetch metadata for component with type {} and uuid {}, error: {}", componentUuid, vertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value())); - } - List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null; - - if (vertexList == null || vertexList.isEmpty()) { - log.debug("Component with uuid {} was not found", componentUuid); - return Either.right(StorageOperationStatus.NOT_FOUND); - } - - ArrayList<Component> latestComponents = new ArrayList<>(); - for (GraphVertex vertex : vertexList) { - Either<Component, StorageOperationStatus> toscaElementByOperation = getToscaElementByOperation(vertex); - - if (toscaElementByOperation.isRight()) { - log.debug("Could not fetch the following Component by UUID {}", vertex.getUniqueId()); - return Either.right(toscaElementByOperation.right().value()); - } - - latestComponents.add(toscaElementByOperation.left().value()); - } - - if (latestComponents.size() > 1) { - for (Component component : latestComponents) { - if (component.isHighestVersion()) { - LinkedList<Component> highestComponent = new LinkedList<>(); - highestComponent.add(component); - return Either.left(highestComponent); - } - } - } - - 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, propertiesToMatch); - - if (latestVersionListEither.isRight()) { - return Either.right(latestVersionListEither.right().value()); - } - - List<Component> latestVersionList = latestVersionListEither.left().value(); - - if (latestVersionList.isEmpty()) { - return Either.right(StorageOperationStatus.NOT_FOUND); - } - Component component = latestVersionList.size() == 1 ? latestVersionList.get(0) : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getVersion()), Double.parseDouble(c2.getVersion()))).get(); - - return Either.left(component); - } - - public Either<List<Resource>, StorageOperationStatus> getAllCertifiedResources(boolean isAbstract, Boolean isHighest) { - - List<Resource> resources = new ArrayList<>(); - Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); - Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); - - propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract); - if (isHighest != null) { - propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest.booleanValue()); - } - propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); - propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); - - Either<List<GraphVertex>, TitanOperationStatus> getResourcesRes = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll); - - if (getResourcesRes.isRight()) { - log.debug("Failed to fetch all certified resources. Status is {}", getResourcesRes.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getResourcesRes.right().value())); - } - List<GraphVertex> resourceVerticies = getResourcesRes.left().value(); - for (GraphVertex resourceV : resourceVerticies) { - Either<Resource, StorageOperationStatus> getResourceRes = getToscaElement(resourceV); - if (getResourceRes.isRight()) { - return Either.right(getResourceRes.right().value()); - } - resources.add(getResourceRes.left().value()); - } - return Either.left(resources); - } - - public <T extends Component> Either<T, StorageOperationStatus> getLatestByNameAndVersion(String name, String version, JsonParseFlagEnum parseFlag) { - Either<T, StorageOperationStatus> result; - - Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class); - Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class); - - hasProperties.put(GraphPropertyEnum.NAME, name); - hasProperties.put(GraphPropertyEnum.VERSION, version); - hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - - hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true); - - Either<List<GraphVertex>, TitanOperationStatus> getResourceRes = titanDao.getByCriteria(null, hasProperties, hasNotProperties, parseFlag); - if (getResourceRes.isRight()) { - TitanOperationStatus status = getResourceRes.right().value(); - log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - return getToscaElementByOperation(getResourceRes.left().value().get(0)); - } - - public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName) { - return getLatestComponentByCsarOrName(componentType, csarUUID, systemName, false, JsonParseFlagEnum.ParseAll); - } - - public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName, boolean allowDeleted, JsonParseFlagEnum parseFlag) { - Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class); - props.put(GraphPropertyEnum.CSAR_UUID, csarUUID); - props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - if (componentType != null) { - props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); - } - Map<GraphPropertyEnum, Object> propsHasNot = new EnumMap<>(GraphPropertyEnum.class); - propsHasNot.put(GraphPropertyEnum.IS_DELETED, true); - - GraphVertex resourceMetadataData = null; - List<GraphVertex> resourceMetadataDataList = null; - Either<List<GraphVertex>, TitanOperationStatus> byCsar = titanDao.getByCriteria(null, props, propsHasNot, JsonParseFlagEnum.ParseMetadata); - if (byCsar.isRight()) { - if (TitanOperationStatus.NOT_FOUND == byCsar.right().value()) { - // Fix Defect DE256036 - if (StringUtils.isEmpty(systemName)) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.NOT_FOUND)); - } - - props.clear(); - props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - props.put(GraphPropertyEnum.SYSTEM_NAME, systemName); - Either<List<GraphVertex>, TitanOperationStatus> bySystemname = titanDao.getByCriteria(null, props, JsonParseFlagEnum.ParseMetadata); - if (bySystemname.isRight()) { - log.debug("getLatestResourceByCsarOrName - Failed to find by system name {} error {} ", systemName, bySystemname.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(bySystemname.right().value())); - } - if (bySystemname.left().value().size() > 2) { - log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) must return only 2 latest version, but was returned - {}", bySystemname.left().value().size()); - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - resourceMetadataDataList = bySystemname.left().value(); - if (resourceMetadataDataList.size() == 1) { - resourceMetadataData = resourceMetadataDataList.get(0); - } else { - for (GraphVertex curResource : resourceMetadataDataList) { - if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) { - resourceMetadataData = curResource; - break; - } - } - } - if (resourceMetadataData == null) { - log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) returned 2 latest CERTIFIED versions"); - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - if (resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID) != null && !((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID)).equals(csarUUID)) { - log.debug("getLatestResourceByCsarOrName - same system name {} but different csarUUID. exist {} and new {} ", systemName, resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID), csarUUID); - // correct error will be returned from create flow. with all - // correct audit records!!!!! - return Either.right(StorageOperationStatus.NOT_FOUND); - } - Either<Resource, StorageOperationStatus> resource = getToscaElement((String) resourceMetadataData.getUniqueId()); - return resource; - } - } else { - resourceMetadataDataList = byCsar.left().value(); - if (resourceMetadataDataList.size() > 2) { - log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) must return only 2 latest version, but was returned - {}", byCsar.left().value().size()); - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - if (resourceMetadataDataList.size() == 1) { - resourceMetadataData = resourceMetadataDataList.get(0); - } else { - for (GraphVertex curResource : resourceMetadataDataList) { - if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) { - resourceMetadataData = curResource; - break; - } - } - } - if (resourceMetadataData == null) { - log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) returned 2 latest CERTIFIED versions"); - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - Either<Resource, StorageOperationStatus> resource = getToscaElement((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID), parseFlag); - return resource; - } - return null; - } - - public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends) { - - String currentTemplateNameChecked = templateNameExtends; - - while (currentTemplateNameChecked != null && !currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) { - Either<Resource, StorageOperationStatus> latestByToscaResourceName = getLatestByToscaResourceName(currentTemplateNameChecked); - - if (latestByToscaResourceName.isRight()) { - return latestByToscaResourceName.right().value() == StorageOperationStatus.NOT_FOUND ? Either.left(false) : Either.right(latestByToscaResourceName.right().value()); - } - - Resource value = latestByToscaResourceName.left().value(); - - if (value.getDerivedFrom() != null) { - currentTemplateNameChecked = value.getDerivedFrom().get(0); - } else { - currentTemplateNameChecked = null; - } - } - - return (currentTemplateNameChecked != null && currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) ? Either.left(true) : Either.left(false); - } - - public Either<List<Component>, StorageOperationStatus> fetchMetaDataByResourceType(String resourceType, ComponentParametersView filterBy) { - Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class); - props.put(GraphPropertyEnum.RESOURCE_TYPE, resourceType); - props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); - 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())); - } - - List<GraphVertex> vertexList = resourcesByTypeEither.left().value(); - List<Component> components = new ArrayList<>(); - - for (GraphVertex vertex : vertexList) { - components.add(getToscaElementByOperation(vertex, filterBy).left().value()); - } - - return Either.left(components); - } - - public void commit() { - titanDao.commit(); - } - - public Either<Service, StorageOperationStatus> updateDistributionStatus(Service service, User user, DistributionStatusEnum distributionStatus) { - Either<GraphVertex, StorageOperationStatus> updateDistributionStatus = topologyTemplateOperation.updateDistributionStatus(service.getUniqueId(), user, distributionStatus); - if (updateDistributionStatus.isRight()) { - return Either.right(updateDistributionStatus.right().value()); - } - GraphVertex serviceV = updateDistributionStatus.left().value(); - service.setDistributionStatus(distributionStatus); - service.setLastUpdateDate((Long) serviceV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE)); - return Either.left(service); - } - - public Either<ComponentMetadataData, StorageOperationStatus> updateComponentLastUpdateDateOnGraph(Component component, Long modificationTime) { - - Either<ComponentMetadataData, StorageOperationStatus> result = null; - GraphVertex serviceVertex; - Either<GraphVertex, TitanOperationStatus> updateRes = null; - Either<GraphVertex, TitanOperationStatus> getRes = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.ParseMetadata); - if (getRes.isRight()) { - TitanOperationStatus status = getRes.right().value(); - log.error("Failed to fetch component {}. status is {}", component.getUniqueId(), status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - if (result == null) { - serviceVertex = getRes.left().value(); - long lastUpdateDate = System.currentTimeMillis(); - serviceVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate); - component.setLastUpdateDate(lastUpdateDate); - updateRes = titanDao.updateVertex(serviceVertex); - if (updateRes.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateRes.right().value())); - } - } - if (result == null) { - result = Either.left(ModelConverter.convertToComponentMetadata(updateRes.left().value())); - } - return result; - } - - public TitanDao getTitanDao() { - return titanDao; - } - - public Either<List<Service>, StorageOperationStatus> getCertifiedServicesWithDistStatus(Set<DistributionStatusEnum> distStatus) { - Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); - propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); - - return getServicesWithDistStatus(distStatus, propertiesToMatch); - } - - public Either<List<Service>, StorageOperationStatus> getServicesWithDistStatus(Set<DistributionStatusEnum> distStatus, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) { - - List<Service> servicesAll = new ArrayList<>(); - - Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); - Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); - - if (additionalPropertiesToMatch != null && !additionalPropertiesToMatch.isEmpty()) { - propertiesToMatch.putAll(additionalPropertiesToMatch); - } - - propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); - - propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); - - if (distStatus != null && !distStatus.isEmpty()) { - for (DistributionStatusEnum state : distStatus) { - propertiesToMatch.put(GraphPropertyEnum.DISTRIBUTION_STATUS, state.name()); - Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria = fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch); - if (fetchServicesByCriteria.isRight()) { - return fetchServicesByCriteria; - } else { - servicesAll = fetchServicesByCriteria.left().value(); - } - } - return Either.left(servicesAll); - } else { - return fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch); - } - } - - private Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria(List<Service> servicesAll, Map<GraphPropertyEnum, Object> propertiesToMatch, Map<GraphPropertyEnum, Object> propertiesNotToMatch) { - Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll); - if (getRes.isRight()) { - if (getRes.right().value() != TitanOperationStatus.NOT_FOUND) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch, propertiesNotToMatch, getRes.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value())); - } - } else { - for (GraphVertex vertex : getRes.left().value()) { - // Either<Component, StorageOperationStatus> getServiceRes = getToscaElementByOperation(vertex); - Either<ToscaElement, StorageOperationStatus> getServiceRes = topologyTemplateOperation.getLightComponent(vertex, ComponentTypeEnum.SERVICE, new ComponentParametersView(true)); - - if (getServiceRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ", vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value()); - return Either.right(getServiceRes.right().value()); - } else { - servicesAll.add(ModelConverter.convertFromToscaElement(getServiceRes.left().value())); - } - } - } - return Either.left(servicesAll); - } - - public void rollback() { - titanDao.rollback(); - } - - public StorageOperationStatus addDeploymentArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map<String, ArtifactDefinition> finalDeploymentArtifacts) { - Map<String, ArtifactDataDefinition> instDeplArtifacts = finalDeploymentArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); - - return nodeTemplateOperation.addDeploymentArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts); - } - - public StorageOperationStatus addInformationalArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map<String, ArtifactDefinition> artifacts) { - StorageOperationStatus status = StorageOperationStatus.OK; - if (MapUtils.isNotEmpty(artifacts)) { - Map<String, ArtifactDataDefinition> instDeplArtifacts = artifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); - status = nodeTemplateOperation.addInformationalArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts); - } - return status; - } - - public StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId) { - return nodeTemplateOperation.generateCustomizationUUIDOnInstance(componentId, instanceId); - } - - public StorageOperationStatus generateCustomizationUUIDOnInstanceGroup(String componentId, String instanceId, List<String> groupInstances) { - return nodeTemplateOperation.generateCustomizationUUIDOnInstanceGroup(componentId, instanceId, groupInstances); - } - - /* - * adds property to a resource - * @warn this method has SIDE EFFECT on ownerId ,use it with caution - * */ - public Either<PropertyDefinition, StorageOperationStatus> addPropertyToResource(String propertyName, PropertyDefinition newPropertyDefinition, Resource resource) { - - Either<PropertyDefinition, StorageOperationStatus> result = null; - Either<Component, StorageOperationStatus> getUpdatedComponentRes = null; - newPropertyDefinition.setName(propertyName); - StorageOperationStatus status = getToscaElementOperation(resource).addToscaDataToToscaElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", propertyName, resource.getName(), status); - result = Either.right(status); - } - if (result == null) { - ComponentParametersView filter = new ComponentParametersView(true); - filter.setIgnoreProperties(false); - getUpdatedComponentRes = getToscaElement(resource.getUniqueId(), filter); - if (getUpdatedComponentRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", resource.getUniqueId(), getUpdatedComponentRes.right().value()); - result = Either.right(status); - } - } - if (result == null) { - PropertyDefinition newProperty = null; - List<PropertyDefinition> properties = ((Resource) getUpdatedComponentRes.left().value()).getProperties(); - if (CollectionUtils.isNotEmpty(properties)) { - Optional<PropertyDefinition> newPropertyOptional = properties.stream().filter(p -> p.getName().equals(propertyName)).findAny(); - if (newPropertyOptional.isPresent()) { - newProperty = newPropertyOptional.get(); - } - } - if (newProperty == null) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", propertyName, resource.getUniqueId(), StorageOperationStatus.NOT_FOUND); - result = Either.right(StorageOperationStatus.NOT_FOUND); - } else { - result = Either.left(newProperty); - } - } - return result; - } - - public StorageOperationStatus deletePropertyOfResource(Resource resource, String propertyName) { - return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, propertyName, JsonPresentationFields.NAME); - } - - public StorageOperationStatus deleteAttributeOfResource(Component component, String attributeName) { - return getToscaElementOperation(component).deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, attributeName, JsonPresentationFields.NAME); - } - - public StorageOperationStatus deleteInputOfResource(Component resource, String inputName) { - return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputName, JsonPresentationFields.NAME); - } - - public Either<PropertyDefinition, StorageOperationStatus> updatePropertyOfResource(Resource resource, PropertyDefinition newPropertyDefinition) { - - Either<Component, StorageOperationStatus> getUpdatedComponentRes = null; - Either<PropertyDefinition, StorageOperationStatus> result = null; - StorageOperationStatus status = getToscaElementOperation(resource).updateToscaDataOfToscaElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newPropertyDefinition.getName(), resource.getName(), status); - result = Either.right(status); - } - if (result == null) { - ComponentParametersView filter = new ComponentParametersView(true); - filter.setIgnoreProperties(false); - getUpdatedComponentRes = getToscaElement(resource.getUniqueId(), filter); - if (getUpdatedComponentRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", resource.getUniqueId(), getUpdatedComponentRes.right().value()); - result = Either.right(status); - } - } - if (result == null) { - Optional<PropertyDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getProperties().stream().filter(p -> p.getName().equals(newPropertyDefinition.getName())).findAny(); - if (newProperty.isPresent()) { - result = Either.left(newProperty.get()); - } else { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newPropertyDefinition.getName(), resource.getUniqueId(), StorageOperationStatus.NOT_FOUND); - result = Either.right(StorageOperationStatus.NOT_FOUND); - } - } - return result; - } - - public Either<PropertyDefinition, StorageOperationStatus> addAttributeOfResource(Component component, PropertyDefinition newAttributeDef) { - - Either<Component, StorageOperationStatus> getUpdatedComponentRes = null; - Either<PropertyDefinition, StorageOperationStatus> result = null; - if (newAttributeDef.getUniqueId() == null || newAttributeDef.getUniqueId().isEmpty()) { - String attUniqueId = UniqueIdBuilder.buildAttributeUid(component.getUniqueId(), newAttributeDef.getName()); - newAttributeDef.setUniqueId(attUniqueId); - } - - StorageOperationStatus status = getToscaElementOperation(component).addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newAttributeDef.getName(), component.getName(), status); - result = Either.right(status); - } - if (result == null) { - ComponentParametersView filter = new ComponentParametersView(true); - filter.setIgnoreAttributesFrom(false); - getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter); - if (getUpdatedComponentRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value()); - result = Either.right(status); - } - } - if (result == null) { - Optional<PropertyDefinition> newAttribute = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny(); - if (newAttribute.isPresent()) { - result = Either.left(newAttribute.get()); - } else { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND); - result = Either.right(StorageOperationStatus.NOT_FOUND); - } - } - return result; - } - - public Either<PropertyDefinition, StorageOperationStatus> updateAttributeOfResource(Component component, PropertyDefinition newAttributeDef) { - - Either<Component, StorageOperationStatus> getUpdatedComponentRes = null; - Either<PropertyDefinition, StorageOperationStatus> result = null; - StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newAttributeDef.getName(), component.getName(), status); - result = Either.right(status); - } - if (result == null) { - ComponentParametersView filter = new ComponentParametersView(true); - filter.setIgnoreAttributesFrom(false); - getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter); - if (getUpdatedComponentRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value()); - result = Either.right(status); - } - } - if (result == null) { - Optional<PropertyDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny(); - if (newProperty.isPresent()) { - result = Either.left(newProperty.get()); - } else { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND); - result = Either.right(StorageOperationStatus.NOT_FOUND); - } - } - return result; - } - - public Either<InputDefinition, StorageOperationStatus> updateInputOfComponent(Component component, InputDefinition newInputDefinition) { - - Either<Component, StorageOperationStatus> getUpdatedComponentRes = null; - Either<InputDefinition, StorageOperationStatus> result = null; - StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputDefinition, JsonPresentationFields.NAME); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the input {} to the component {}. Status is {}. ", newInputDefinition.getName(), component.getName(), status); - result = Either.right(status); - } - if (result == null) { - ComponentParametersView filter = new ComponentParametersView(true); - filter.setIgnoreInputs(false); - getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter); - if (getUpdatedComponentRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value()); - result = Either.right(status); - } - } - if (result == null) { - Optional<InputDefinition> updatedInput = getUpdatedComponentRes.left().value().getInputs().stream().filter(p -> p.getName().equals(newInputDefinition.getName())).findAny(); - if (updatedInput.isPresent()) { - result = Either.left(updatedInput.get()); - } else { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently updated inputs {} on the resource {}. Status is {}. ", newInputDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND); - result = Either.right(StorageOperationStatus.NOT_FOUND); - } - } - return result; - } - - /** - * method - ename the group instances after referenced container name renamed flow - VF rename -(triggers)-> Group rename - * - * @param containerComponent - * - container such as service - * @param componentInstance - * - context component - * @param componentInstanceId - * - id - * - * @return - successfull/failed status - **/ - public Either<StorageOperationStatus, StorageOperationStatus> cleanAndAddGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, String componentInstanceId) { - String uniqueId = componentInstance.getUniqueId(); - StorageOperationStatus status = nodeTemplateOperation.deleteToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, uniqueId); - if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete group instances for container {}. error {] ", componentInstanceId, status); - return Either.right(status); - } - if (componentInstance.getGroupInstances() != null) { - status = addGroupInstancesToComponentInstance(containerComponent, componentInstance, componentInstance.getGroupInstances()); - if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add group instances for container {}. error {] ", componentInstanceId, status); - return Either.right(status); - } - } - return Either.left(status); - } - - public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupDefinition> groups, Map<String, List<ArtifactDefinition>> groupInstancesArtifacts) { - return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groups, groupInstancesArtifacts); - } - - public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsOnComponent(Component component, 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, instanceId, updatedGroupInstances); - } - - public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupInstance> groupInstances) { - return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groupInstances); - } - - public StorageOperationStatus addDeploymentArtifactsToComponentInstance(Component containerComponent, ComponentInstance componentInstance, Map<String, ArtifactDefinition> deploymentArtifacts) { - return nodeTemplateOperation.addDeploymentArtifactsToComponentInstance(containerComponent, componentInstance, deploymentArtifacts); - } - - public StorageOperationStatus updateComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) { - return nodeTemplateOperation.updateComponentInstanceProperty(containerComponent, componentInstanceId, property); - } - - public StorageOperationStatus updateComponentInstanceProperties(Component containerComponent, String componentInstanceId, List<ComponentInstanceProperty> properties) { - return nodeTemplateOperation.updateComponentInstanceProperties(containerComponent, componentInstanceId, properties); - } - - - public StorageOperationStatus addComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) { - return nodeTemplateOperation.addComponentInstanceProperty(containerComponent, componentInstanceId, property); - } - - public StorageOperationStatus updateComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) { - return nodeTemplateOperation.updateComponentInstanceInput(containerComponent, componentInstanceId, property); - } - - public StorageOperationStatus updateComponentInstanceInputs(Component containerComponent, String componentInstanceId, List<ComponentInstanceInput> instanceInputs) { - return nodeTemplateOperation.updateComponentInstanceInputs(containerComponent, componentInstanceId, instanceInputs); - } - - public StorageOperationStatus addComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) { - return nodeTemplateOperation.addComponentInstanceInput(containerComponent, componentInstanceId, property); - } - - public void setNodeTypeOperation(NodeTypeOperation nodeTypeOperation) { - this.nodeTypeOperation = nodeTypeOperation; - } - - public void setTopologyTemplateOperation(TopologyTemplateOperation topologyTemplateOperation) { - this.topologyTemplateOperation = topologyTemplateOperation; - } - - public StorageOperationStatus deleteComponentInstanceInputsFromTopologyTemplate(Component containerComponent, ComponentTypeEnum componentType, List<InputDefinition> inputsToDelete) { - return topologyTemplateOperation.deleteToscaDataElements(containerComponent.getUniqueId(), EdgeLabelEnum.INPUTS, inputsToDelete.stream().map(i -> i.getName()).collect(Collectors.toList())); - } - - public StorageOperationStatus updateComponentInstanceCapabiltyProperty(Component containerComponent, String componentInstanceUniqueId, String capabilityUniqueId, ComponentInstanceProperty property) { - 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) { - status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS); - } - if(status == StorageOperationStatus.OK){ - status = topologyTemplateOperation.removeToscaData(topologyTemplateId, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES); - } - return status; - } - - public Either<Component, StorageOperationStatus> shouldUpgradeToLatestDerived(Resource clonedResource) { - String componentId = clonedResource.getUniqueId(); - Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getVertexEither.isRight()) { - log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); - - } - GraphVertex nodeTypeV = getVertexEither.left().value(); - - ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(clonedResource); - - Either<ToscaElement, StorageOperationStatus> shouldUpdateDerivedVersion = nodeTypeOperation.shouldUpdateDerivedVersion(toscaElementToUpdate, nodeTypeV); - if ( shouldUpdateDerivedVersion.isRight() && StorageOperationStatus.OK != shouldUpdateDerivedVersion.right().value() ){ - log.debug("Failed to update derived version for node type {} derived {}, error: {}", componentId, clonedResource.getDerivedFrom().get(0), shouldUpdateDerivedVersion.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); - } - if ( shouldUpdateDerivedVersion.isLeft() ){ - return Either.left(ModelConverter.convertFromToscaElement(shouldUpdateDerivedVersion.left().value())); - } - return Either.left(clonedResource); - } - /** - * 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, 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; - } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/UpgradeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/UpgradeOperation.java new file mode 100644 index 0000000000..5faa6bb8ad --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/UpgradeOperation.java @@ -0,0 +1,225 @@ +package org.openecomp.sdc.be.model.jsontitan.operations; + +import com.thinkaurelius.titan.core.TitanVertex; +import fj.data.Either; +import org.apache.tinkerpop.gremlin.structure.Direction; +import org.apache.tinkerpop.gremlin.structure.Edge; +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.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.model.ComponentDependency; +import org.openecomp.sdc.be.model.jsontitan.enums.JsonConstantKeysEnum; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.springframework.stereotype.Component; + +import java.util.*; +import java.util.function.Function; +import java.util.stream.Collectors; + +@Component +public class UpgradeOperation extends BaseOperation { + private static final Logger log = Logger.getLogger(UpgradeOperation.class.getName()); + + public Either<List<ComponentDependency>, StorageOperationStatus> getComponentDependencies(String componentId) { + Either<GraphVertex, TitanOperationStatus> vertexById = titanDao.getVertexById(componentId); + if (vertexById.isRight()) { + log.debug("Failed to fetch vertex with id {} error {}", componentId, vertexById.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexById.right().value())); + } + List<ComponentDependency> dependencies = new ArrayList<>(); + + GraphVertex vertex = vertexById.left().value(); + + StorageOperationStatus status = fillDependenciesByVertex(componentId, dependencies, vertex); + if (status != StorageOperationStatus.OK) { + return Either.right(status); + } + + GraphVertex vertexToStart = vertex; + Function<GraphVertex, Either<GraphVertex, TitanOperationStatus>> getNextElement = vertexP -> titanDao.getParentVertex(vertexP, EdgeLabelEnum.VERSION, JsonParseFlagEnum.ParseAll); + status = handleVersionChain(componentId, dependencies, vertex, getNextElement); + if (status != StorageOperationStatus.OK) { + return Either.right(status); + } + vertex = vertexToStart; + getNextElement = vertexP -> titanDao.getChildVertex(vertexP, EdgeLabelEnum.VERSION, JsonParseFlagEnum.ParseAll); + status = handleVersionChain(componentId, dependencies, vertex, getNextElement); + + return status == StorageOperationStatus.OK ? Either.left(dependencies) : Either.right(status); + } + + private StorageOperationStatus handleVersionChain(String componentId, List<ComponentDependency> dependencies, GraphVertex vertexToStart, Function<GraphVertex, Either<GraphVertex, TitanOperationStatus>> getNextElement) { + + StorageOperationStatus status; + boolean nextInChain = true; + GraphVertex vertex = vertexToStart; + Either<GraphVertex, TitanOperationStatus> nextInChainV; + while (nextInChain) { + nextInChainV = getNextElement.apply(vertex); + if (nextInChainV.isRight()) { + nextInChain = false; + } else { + vertex = nextInChainV.left().value(); + status = fillDependenciesByVertex(componentId, dependencies, vertex); + if (status != StorageOperationStatus.OK) { + return status; + } + } + } + return StorageOperationStatus.OK; + } + + private StorageOperationStatus fillDependenciesByVertex(String componentId, List<ComponentDependency> dependencies, GraphVertex vertex) { + StorageOperationStatus status = StorageOperationStatus.OK; + if ( needToAddToDepenedency(vertex) ) { + ComponentDependency dependency = fillDataFromVertex(vertex, null, null); + + List<EdgeLabelEnum> dependList = Arrays.asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF, EdgeLabelEnum.ALLOTTED_OF); + for (EdgeLabelEnum label : dependList) { + status = fillDependenciesByLabel(componentId, vertex, dependency, label); + if (status != StorageOperationStatus.OK) { + log.debug("Failed to create dependencies for component {} and label {} status {}", componentId, label, status); + break; + } + } + if (status == StorageOperationStatus.OK) { + dependencies.add(dependency); + } + } + return status; + } + private boolean needToAddToDepenedency(GraphVertex vertex){ + Boolean isDeleted = (Boolean) vertex.getMetadataProperty(GraphPropertyEnum.IS_DELETED); + Boolean isArchived = (Boolean) vertex.getMetadataProperty(GraphPropertyEnum.IS_ARCHIVED); + return ( isDeleted == Boolean.TRUE || isArchived == Boolean.TRUE) ? false : true; + } + + private StorageOperationStatus fillDependenciesByLabel(String componentId, GraphVertex vertex, ComponentDependency dependency, EdgeLabelEnum label) { + Either<List<GraphVertex>, TitanOperationStatus> parentVertecies = titanDao.getParentVertecies(vertex, label, JsonParseFlagEnum.ParseAll); + if (parentVertecies.isRight() && parentVertecies.right().value() != TitanOperationStatus.NOT_FOUND) { + log.debug("Failed to fetch parent verticies by label INSTANCE_OF for vertex with id {} error {}", componentId, parentVertecies.right().value()); + return DaoStatusConverter.convertTitanStatusToStorageStatus(parentVertecies.right().value()); + } + if (parentVertecies.isLeft()) { + List<ComponentDependency> existIn = new ArrayList<>( ); + parentVertecies.left().value().forEach(v -> handleHighestVersion(vertex, label, existIn, v) ); + dependency.addDependencies(existIn); + } + return StorageOperationStatus.OK; + } + + private void handleHighestVersion(GraphVertex vertexOrigin, EdgeLabelEnum label, List<ComponentDependency> exisIn, GraphVertex containerVertex) { + Boolean isHighest = (Boolean) containerVertex.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION); + if ( isHighest && needToAddToDepenedency(containerVertex) ) { + TitanVertex titanVertex = containerVertex.getVertex(); + Iterator<Edge> edges = titanVertex.edges(Direction.OUT, EdgeLabelEnum.VERSION.name()); + //verify that it is a last version - highest by version number + if ( edges == null || !edges.hasNext() ){ + ComponentDependency container = fillDataFromVertex(containerVertex, vertexOrigin.getUniqueId(), label); + boolean addToDependency = true; + if (label == EdgeLabelEnum.ALLOTTED_OF) { + //in case of not full allotted chain not add to dependency list + addToDependency = findAllottedChain(containerVertex, container); + } + if ( addToDependency ){ + exisIn.add(container); + } + } + } + } + + private boolean findAllottedChain(GraphVertex vertex, ComponentDependency container) { + Either<List<GraphVertex>, TitanOperationStatus> parentVertecies = titanDao.getParentVertecies(vertex, EdgeLabelEnum.INSTANCE_OF, JsonParseFlagEnum.ParseAll); + if (parentVertecies.isLeft()) { + List<ComponentDependency> existIn = new ArrayList<>(); + parentVertecies.left().value().forEach(v -> { + Boolean isHighest = (Boolean) v.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION); + if ( isHighest && needToAddToDepenedency(v) ) { + TitanVertex titanVertex = v.getVertex(); + Iterator<Edge> edges = titanVertex.edges(Direction.OUT, EdgeLabelEnum.VERSION.name()); + //verify that it is a last version - highest by version number + if ( edges == null || !edges.hasNext() ){ + ComponentDependency parentContainer = fillDataFromVertex(v, vertex.getUniqueId(), EdgeLabelEnum.INSTANCE_OF); + existIn.add(parentContainer); + } + } + }); + if ( !existIn.isEmpty() ){ + container.setDependencies(existIn); + return true; + } + } + return false; + } + + private ComponentDependency fillDataFromVertex(GraphVertex v, String originId, EdgeLabelEnum edgeLabel) { + ComponentDependency container = new ComponentDependency(); + container.setName((String) v.getMetadataProperty(GraphPropertyEnum.NAME)); + container.setVersion((String) v.getMetadataProperty(GraphPropertyEnum.VERSION)); + container.setUniqueId(v.getUniqueId()); + container.setType((String) v.getMetadataProperty(GraphPropertyEnum.COMPONENT_TYPE)); + container.setIcon((String) v.getJsonMetadataField(JsonPresentationFields.ICON)); + container.setState((String) v.getMetadataProperty(GraphPropertyEnum.STATE)); + + if (edgeLabel == EdgeLabelEnum.PROXY_OF || edgeLabel == EdgeLabelEnum.ALLOTTED_OF) { + findInstanceNames(v, originId, edgeLabel, container); + } + return container; + } + + private void findInstanceNames(GraphVertex v, String originId, EdgeLabelEnum edgeLabel, ComponentDependency container) { + Map<String, CompositionDataDefinition> jsonComposition = (Map<String, CompositionDataDefinition>) v.getJson(); + CompositionDataDefinition compositionDataDefinition = jsonComposition.get(JsonConstantKeysEnum.COMPOSITION.getValue()); + TitanVertex vertex = v.getVertex(); + Iterator<Edge> edges = vertex.edges(Direction.OUT, edgeLabel.name()); + while (edges != null && edges.hasNext()) { + Edge edge = edges.next(); + TitanVertex inVertex = (TitanVertex) edge.inVertex(); + String id = (String) titanDao.getProperty(inVertex, GraphPropertyEnum.UNIQUE_ID.getProperty()); + if (id.equals(originId)) { + List<String> instanceOnEdge = (List<String>) titanDao.getProperty(edge, EdgePropertyEnum.INSTANCES); + Map<String, ComponentInstanceDataDefinition> componentInstances = compositionDataDefinition.getComponentInstances(); + + if (componentInstances != null) { + List<String> ciNames = componentInstances + .values() + .stream() + .filter(ci -> instanceOnEdge.contains(ci.getUniqueId())) + .map(ComponentInstanceDataDefinition::getName) + .collect(Collectors.toList()); + if (ciNames != null && !ciNames.isEmpty()) { + container.setInstanceNames(ciNames); + break; + } + } + } + } + } + + public List<String> getInstanceIdFromAllottedEdge(String resourceId, String serviceInvariantUUID) { + Either<GraphVertex, TitanOperationStatus> vertexById = titanDao.getVertexById(resourceId); + if ( vertexById.isLeft() ){ + GraphVertex vertexG = vertexById.left().value(); + TitanVertex vertex = vertexG.getVertex(); + Iterator<Edge> edges = vertex.edges(Direction.OUT, EdgeLabelEnum.ALLOTTED_OF.name()); + while ( edges != null && edges.hasNext() ){ + Edge edge = edges.next(); + TitanVertex inVertex = (TitanVertex)edge.inVertex(); + String vertexInInvUUID = (String) titanDao.getProperty(inVertex, GraphPropertyEnum.INVARIANT_UUID.getProperty()); + if ( vertexInInvUUID.equals(serviceInvariantUUID) ){ + return (List<String>) titanDao.getProperty(edge, EdgePropertyEnum.INSTANCES) ; + } + } + } + return new ArrayList<>(); + } + +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/IdMapper.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/IdMapper.java index 37c21e812f..2c3c98e133 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/IdMapper.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/IdMapper.java @@ -1,24 +1,23 @@ package org.openecomp.sdc.be.model.jsontitan.utils; -import java.util.Map; -import java.util.Optional; - import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition; import org.openecomp.sdc.be.model.jsontitan.enums.JsonConstantKeysEnum; import org.openecomp.sdc.be.model.jsontitan.operations.ExternalReferencesOperation; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.stereotype.Component; +import java.util.Map; +import java.util.Optional; + /** * Created by yavivi on 12/02/2018. */ @Component public class IdMapper { - private static final Logger log = LoggerFactory.getLogger(ExternalReferencesOperation.class); + private static final Logger log = Logger.getLogger(ExternalReferencesOperation.class.getName()); public String mapComponentNameToUniqueId(String componentInstanceName, GraphVertex serviceVertex) { return map(componentInstanceName, serviceVertex, true); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/InterfaceUtils.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/InterfaceUtils.java index 49f16946af..a350d7ea17 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/InterfaceUtils.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/InterfaceUtils.java @@ -15,15 +15,6 @@ */ package org.openecomp.sdc.be.model.jsontitan.utils; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Formatter; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; - import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.openecomp.sdc.be.datatypes.elements.InputDataDefinition; @@ -35,6 +26,9 @@ import org.openecomp.sdc.be.model.InterfaceDefinition; import org.openecomp.sdc.be.model.Operation; import org.openecomp.sdc.be.model.Resource; +import java.util.*; +import java.util.stream.Collectors; + public class InterfaceUtils { public static final String INTERFACE_TOSCA_RESOURCE_NAME = "org.openecomp.interfaces.node.lifecycle.%s"; @@ -66,8 +60,9 @@ public class InterfaceUtils { public static String createInterfaceToscaResourceName(String resourceName) { StringBuilder sb = new StringBuilder(); - Formatter formatter = new Formatter(sb); - return formatter.format(INTERFACE_TOSCA_RESOURCE_NAME, resourceName).toString(); + try (Formatter formatter = new Formatter(sb)){ + return formatter.format(INTERFACE_TOSCA_RESOURCE_NAME, resourceName).toString(); + } } public static Map<String, Operation> getInterfaceOperationsFromInterfaces( diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/ModelConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/ModelConverter.java index bbe607b58c..041d3f0d77 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/ModelConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/ModelConverter.java @@ -12,7 +12,7 @@ * * 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. + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.T * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END========================================================= @@ -20,66 +20,21 @@ package org.openecomp.sdc.be.model.jsontitan.utils; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.function.BiConsumer; -import java.util.function.Function; -import java.util.stream.Collectors; - +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang.BooleanUtils; import org.apache.commons.lang3.StringUtils; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; -import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition; -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.CompositionDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition; -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.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.PolicyDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.RelationshipInstDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.*; +import org.openecomp.sdc.be.datatypes.elements.MapCapabilityProperty; +import org.openecomp.sdc.be.datatypes.elements.MapListCapabilityDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; -import org.openecomp.sdc.be.model.AdditionalInformationDefinition; -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.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.InterfaceDefinition; -import org.openecomp.sdc.be.model.PolicyDefinition; -import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.RelationshipImpl; -import org.openecomp.sdc.be.model.RelationshipInfo; -import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; -import org.openecomp.sdc.be.model.RequirementDefinition; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.*; 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; @@ -89,72 +44,76 @@ import org.openecomp.sdc.be.resources.data.ComponentMetadataData; import org.openecomp.sdc.be.resources.data.ProductMetadataData; import org.openecomp.sdc.be.resources.data.ResourceMetadataData; import org.openecomp.sdc.be.resources.data.ServiceMetadataData; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ModelConverter { - public static final String CAP_PROP_DELIM = "#"; - private static Logger log = LoggerFactory.getLogger(ModelConverter.class.getName()); - - @SuppressWarnings("unchecked") - public static <T extends ToscaElement> T convertToToscaElement(Component component) { - if (isAtomicComponent(component)) { - return (T) convertToNodeType(component); - } - return (T) convertToTopologyTemplate(component); - } - - @SuppressWarnings("unchecked") - public static <T extends Component> T convertFromToscaElement(ToscaElement toscaElement) { - switch (toscaElement.getComponentType()) { - case RESOURCE: - return (T) convertToResource(toscaElement); - case SERVICE: - case PRODUCT: - return (T) convertToService(toscaElement); - default: - return null; - } - } - - public static boolean isAtomicComponent(Component component) { - ComponentTypeEnum componentType = component.getComponentType(); - if (!componentType.equals(ComponentTypeEnum.RESOURCE)) { - return false; - } - Resource resource = (Resource) component; - ResourceTypeEnum resType = resource.getResourceType(); - return isAtomicComponent(resType); - } - - public static boolean isAtomicComponent(ResourceTypeEnum resourceType) { - if (resourceType == null) { - return false; - } - return resourceType.isAtomicType(); - } +import org.openecomp.sdc.common.log.wrappers.Logger; - // ********************************************************** - public static VertexTypeEnum getVertexType(Component component) { - VertexTypeEnum vertexType; - if (isAtomicComponent(component)) { - vertexType = VertexTypeEnum.NODE_TYPE; - } else { - vertexType = VertexTypeEnum.TOPOLOGY_TEMPLATE; - } - return vertexType; - } +import java.util.*; +import java.util.Map.Entry; +import java.util.function.Function; +import java.util.stream.Collectors; - public static VertexTypeEnum getVertexType(String resourceTypeName) { - VertexTypeEnum vertexType = null; - ResourceTypeEnum resourceType = ResourceTypeEnum.getTypeByName(resourceTypeName); - if (isAtomicComponent(resourceType)) { - vertexType = VertexTypeEnum.NODE_TYPE; - } else { - vertexType = VertexTypeEnum.TOPOLOGY_TEMPLATE; - } - return vertexType; - } +public class ModelConverter { + public static final String CAP_PROP_DELIM = "#"; + private static final Logger log = Logger.getLogger(ModelConverter.class); + + @SuppressWarnings("unchecked") + public static <T extends ToscaElement> T convertToToscaElement(Component component) { + if (isAtomicComponent(component)) { + return (T) convertToNodeType(component); + } + return (T) convertToTopologyTemplate(component); + } + + @SuppressWarnings("unchecked") + public static <T extends Component> T convertFromToscaElement(ToscaElement toscaElement) { + switch (toscaElement.getComponentType()) { + case RESOURCE: + return (T) convertToResource(toscaElement); + case SERVICE: + case PRODUCT: + return (T) convertToService(toscaElement); + default: + return null; + } + } + + public static boolean isAtomicComponent(Component component) { + ComponentTypeEnum componentType = component.getComponentType(); + if (!componentType.equals(ComponentTypeEnum.RESOURCE)) { + return false; + } + Resource resource = (Resource) component; + ResourceTypeEnum resType = resource.getResourceType(); + return isAtomicComponent(resType); + } + + public static boolean isAtomicComponent(ResourceTypeEnum resourceType) { + if (resourceType == null) { + return false; + } + return resourceType.isAtomicType(); + } + + // ********************************************************** + public static VertexTypeEnum getVertexType(Component component) { + VertexTypeEnum vertexType; + if (isAtomicComponent(component)) { + vertexType = VertexTypeEnum.NODE_TYPE; + } else { + vertexType = VertexTypeEnum.TOPOLOGY_TEMPLATE; + } + return vertexType; + } + + public static VertexTypeEnum getVertexType(String resourceTypeName) { + VertexTypeEnum vertexType = null; + ResourceTypeEnum resourceType = ResourceTypeEnum.getTypeByName(resourceTypeName); + if (isAtomicComponent(resourceType)) { + vertexType = VertexTypeEnum.NODE_TYPE; + } else { + vertexType = VertexTypeEnum.TOPOLOGY_TEMPLATE; + } + return vertexType; + } @@ -162,57 +121,58 @@ public class ModelConverter { Service service = new Service(); convertComponentFields(service, toscaElement); - convertServiceSpecificFields(toscaElement, service); - - TopologyTemplate topologyTemplate = (TopologyTemplate) toscaElement; + convertServiceSpecificFields(toscaElement, service); - convertComponentInstances(topologyTemplate, service); + TopologyTemplate topologyTemplate = (TopologyTemplate) toscaElement; - convertInputs(topologyTemplate, service); - - convertPolicies(topologyTemplate, service); + convertComponentInstances(topologyTemplate, service); - convertGroups(topologyTemplate, service); + convertInputs(topologyTemplate, service); - convertPolicies(topologyTemplate, service); + convertGroups(topologyTemplate, service); - convertGroups(topologyTemplate, service); + setCapabilitiesToComponentAndGroups(topologyTemplate, service); - convertPolicies(topologyTemplate, service); + convertPolicies(topologyTemplate, service); - convertRelations(topologyTemplate, service); + convertRelations(topologyTemplate, service); - convertArtifacts(topologyTemplate, service); + convertArtifacts(topologyTemplate, service); - convertServiceApiArtifacts(topologyTemplate, service); + convertServiceApiArtifacts(topologyTemplate, service); - convertServicePaths(topologyTemplate, service); + convertServicePaths(topologyTemplate, service); - return service; - } + return service; + } private static void convertServiceSpecificFields(ToscaElement toscaElement, Service service) { service.setProjectCode((String) toscaElement.getMetadataValue(JsonPresentationFields.PROJECT_CODE)); - service.setDistributionStatus(DistributionStatusEnum.findState((String) toscaElement.getMetadataValue(JsonPresentationFields.DISTRIBUTION_STATUS))); - service.setEcompGeneratedNaming((Boolean) toscaElement.getMetadataValueOrDefault(JsonPresentationFields.ECOMP_GENERATED_NAMING, true)); - service.setNamingPolicy((String) toscaElement.getMetadataValueOrDefault(JsonPresentationFields.NAMING_POLICY, StringUtils.EMPTY)); - service.setEnvironmentContext((String) toscaElement.getMetadataValue(JsonPresentationFields.ENVIRONMENT_CONTEXT)); - } - - private static Resource convertToResource(ToscaElement toscaElement) { - Resource resource = new Resource(); - convertComponentFields(resource, toscaElement); - - resource.setResourceType(toscaElement.getResourceType()); - if (toscaElement.getToscaType() == ToscaElementTypeEnum.NodeType) { - NodeType nodeType = (NodeType) toscaElement; - resource.setDerivedFrom(nodeType.getDerivedFrom()); - resource.setDerivedList(nodeType.getDerivedList()); - resource.setAbstract((Boolean) nodeType.getMetadataValue(JsonPresentationFields.IS_ABSTRACT)); - convertAttributes(nodeType, resource); - convertCapabilities(nodeType, resource); - convertRequirements(nodeType, resource); - convertInterfaces(nodeType, resource); + service.setDistributionStatus(DistributionStatusEnum + .findState((String) toscaElement.getMetadataValue(JsonPresentationFields.DISTRIBUTION_STATUS))); + service.setEcompGeneratedNaming( + (Boolean) toscaElement.getMetadataValueOrDefault(JsonPresentationFields.ECOMP_GENERATED_NAMING, true)); + service.setNamingPolicy((String) toscaElement.getMetadataValueOrDefault(JsonPresentationFields.NAMING_POLICY, + StringUtils.EMPTY)); + service.setEnvironmentContext( + (String) toscaElement.getMetadataValue(JsonPresentationFields.ENVIRONMENT_CONTEXT)); + service.setInstantiationType((String) toscaElement.getMetadataValueOrDefault(JsonPresentationFields.INSTANTIATION_TYPE, StringUtils.EMPTY)); + } + + private static Resource convertToResource(ToscaElement toscaElement) { + Resource resource = new Resource(); + convertComponentFields(resource, toscaElement); + + resource.setResourceType(toscaElement.getResourceType()); + if (toscaElement.getToscaType() == ToscaElementTypeEnum.NODE_TYPE) { + NodeType nodeType = (NodeType) toscaElement; + resource.setDerivedFrom(nodeType.getDerivedFrom()); + resource.setDerivedList(nodeType.getDerivedList()); + resource.setAbstract((Boolean) nodeType.getMetadataValue(JsonPresentationFields.IS_ABSTRACT)); + convertAttributes(nodeType, resource); + convertCapabilities(nodeType, resource); + convertRequirements(nodeType, resource); + convertInterfaces(nodeType, resource); } else { TopologyTemplate topologyTemplate = (TopologyTemplate) toscaElement; @@ -220,1145 +180,1233 @@ public class ModelConverter { resource.setCsarUUID((String) topologyTemplate.getMetadataValue(JsonPresentationFields.CSAR_UUID)); resource.setCsarVersion((String) topologyTemplate.getMetadataValue(JsonPresentationFields.CSAR_VERSION)); resource.setImportedToscaChecksum((String) topologyTemplate.getMetadataValue(JsonPresentationFields.IMPORTED_TOSCA_CHECKSUM)); - convertInterfaces(topologyTemplate, resource); - - } - convertComponentInstances(topologyTemplate, resource); - convertRelations(topologyTemplate, resource); - convertInputs(topologyTemplate, resource); - convertGroups(topologyTemplate, resource); - convertPolicies(topologyTemplate, resource); - } - convertArtifacts(toscaElement, resource); - convertAdditionalInformation(toscaElement, resource); - return resource; - } + } + convertComponentInstances(topologyTemplate, resource); + convertRelations(topologyTemplate, resource); + convertInputs(topologyTemplate, resource); + convertGroups(topologyTemplate, resource); + setCapabilitiesToComponentAndGroups(topologyTemplate, resource); + convertPolicies(topologyTemplate, resource); + } + convertArtifacts(toscaElement, resource); + convertAdditionalInformation(toscaElement, resource); - private static void convertInterfaces(TopologyTemplate toscaElement, Resource resource) { - Map<String, InterfaceDataDefinition> interfaces = toscaElement.getInterfaces(); - Map<String, InterfaceDefinition> copy; - if (interfaces != null) { - copy = interfaces.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new InterfaceDefinition(e.getValue()))); - } else { - copy = new HashMap<>(); - } - resource.setInterfaces(copy); - } - - private static void convertAttributes(NodeType nodeType, Resource resource) { - Map<String, PropertyDataDefinition> attributes = nodeType.getAttributes(); - if (attributes != null) { - List<PropertyDefinition> attrs = attributes.values().stream().map(dataDef -> ModelConverter.fromDataDefinition(resource.getUniqueId(), dataDef)).collect(Collectors.toList()); - resource.setAttributes(attrs); - } - } - - private static PropertyDefinition fromDataDefinition(String resourceId, PropertyDataDefinition dataDefinition) { - PropertyDefinition attributeDefinition = new PropertyDefinition(dataDefinition); - attributeDefinition.setParentUniqueId(resourceId); - return attributeDefinition; - } - - private static void convertInterfaces(NodeType nodeType, Resource resource) { - Map<String, InterfaceDataDefinition> interfaceArtifacts = nodeType.getInterfaceArtifacts(); - if (interfaceArtifacts != null) { - Map<String, InterfaceDefinition> interfaces = interfaceArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, en -> new InterfaceDefinition(en.getValue()))); - resource.setInterfaces(interfaces); - } - } + return resource; + } - /** - * Converts component instances of topology template to component instances of resource - * - * @param topologyTemplate - * @param component - */ - public static void convertComponentInstances(TopologyTemplate topologyTemplate, Component component) { + private static void convertAttributes(NodeType nodeType, Resource resource) { + Map<String, PropertyDataDefinition> attributes = nodeType.getAttributes(); + if (attributes != null) { + List<PropertyDefinition> attrs = attributes.values().stream().map(dataDef -> ModelConverter.fromDataDefinition(resource.getUniqueId(), dataDef)).collect(Collectors.toList()); + resource.setAttributes(attrs); + } + } - if (MapUtils.isNotEmpty(topologyTemplate.getComponentInstances())) { + private static PropertyDefinition fromDataDefinition(String resourceId, PropertyDataDefinition dataDefinition) { + PropertyDefinition attributeDefinition = new PropertyDefinition(dataDefinition); + attributeDefinition.setParentUniqueId(resourceId); + return attributeDefinition; + } - setComponentInstancesAttributesToComponent(topologyTemplate, component); + private static void convertInterfaces(NodeType nodeType, Resource resource) { + Map<String, InterfaceDataDefinition> interfaceArtifacts = nodeType.getInterfaceArtifacts(); + if (interfaceArtifacts != null) { + Map<String, InterfaceDefinition> interfaces = interfaceArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, en -> new InterfaceDefinition(en.getValue()))); + resource.setInterfaces(interfaces); + } + } - setComponentInstancesPropertiesToComponent(topologyTemplate, component); + /** + * Converts component instances of topology template to component instances of resource + * + * @param topologyTemplate + * @param component + */ + public static void convertComponentInstances(TopologyTemplate topologyTemplate, Component component) { + + if (MapUtils.isNotEmpty(topologyTemplate.getComponentInstances())) { - setComponentInstancesInputsToComponent(topologyTemplate, component); + setComponentInstancesAttributesToComponent(topologyTemplate, component); + + setComponentInstancesPropertiesToComponent(topologyTemplate, component); - setComponentInstancesToComponent(topologyTemplate, component); + setComponentInstancesInputsToComponent(topologyTemplate, component); + + setComponentInstancesToComponent(topologyTemplate, component); - setComponentInstancesCapabilitiesToComponentAndCI(topologyTemplate, component); + setComponentInstancesCapabilitiesToComponentAndCI(topologyTemplate, component); + + setComponentInstancesRequirementsToComponent(topologyTemplate, component); - setComponentInstancesRequirementsToComponent(topologyTemplate, component); - - setComponentInstancesArtifactsToComponent(topologyTemplate, component); - - } - } - - private static void setComponentInstancesArtifactsToComponent(TopologyTemplate topologyTemplate, Component component) { - Map<String, MapArtifactDataDefinition> instDeploymentArtifacts = topologyTemplate.getInstDeploymentArtifacts(); - Map<String, MapArtifactDataDefinition> instanceArtifacts = topologyTemplate.getInstanceArtifacts(); - - List<ComponentInstance> instances = component.getComponentInstances(); - if (instDeploymentArtifacts != null && instances != null) { - instDeploymentArtifacts.entrySet().forEach(e -> { - Optional<ComponentInstance> ci = instances.stream().filter(i -> i.getUniqueId().equals(e.getKey())).findFirst(); - if (ci.isPresent()) { - Map<String, ArtifactDataDefinition> mapToscaDataDefinition = e.getValue().getMapToscaDataDefinition(); - Map<String, ArtifactDefinition> deplArt = mapToscaDataDefinition.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, en -> new ArtifactDefinition(en.getValue()))); - - ci.get().setDeploymentArtifacts(deplArt); - } - }); - } - if (instanceArtifacts != null && instances != null) { - instanceArtifacts.entrySet().forEach(e -> { - Optional<ComponentInstance> ci = instances.stream().filter(i -> i.getUniqueId().equals(e.getKey())).findFirst(); - if (ci.isPresent()) { - Map<String, ArtifactDataDefinition> mapToscaDataDefinition = e.getValue().getMapToscaDataDefinition(); - Map<String, ArtifactDefinition> deplArt = mapToscaDataDefinition.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, en -> new ArtifactDefinition(en.getValue()))); - - ci.get().setArtifacts(deplArt); - } - }); - } - - } - - public static void convertComponentInstances(Component component, TopologyTemplate topologyTemplate) { - - if (!CollectionUtils.isEmpty(component.getComponentInstances())) { - - setComponentInstancesAttributesToTopologyTemplate(component, topologyTemplate); - - setComponentInstancesPropertiesToTopologyTemplate(component, topologyTemplate); - - setComponentInstancesInputsToTopologyTemplate(component, topologyTemplate); - - setComponentInstancesToTopologyTemplate(component, topologyTemplate); - - setComponentInstancesArtifactsToTopologyTemplate(component, topologyTemplate); - } - } - - public static void convertRelations(TopologyTemplate topologyTemplate, Component component) { - Map<String, RelationshipInstDataDefinition> relations = topologyTemplate.getRelations(); - List<RequirementCapabilityRelDef> componentRelations; - if (relations != null && !relations.isEmpty()) { - componentRelations = relations.values().stream().map(ModelConverter::convertRelation).collect(Collectors.toList()); - - } else { - componentRelations = new ArrayList<>(); - } - component.setComponentInstancesRelations(componentRelations); - - } - - public static RequirementCapabilityRelDef convertRelation(RelationshipInstDataDefinition relation) { - RequirementCapabilityRelDef requirementCapabilityRelDef = new RequirementCapabilityRelDef(); - requirementCapabilityRelDef.setFromNode(relation.getFromId()); - requirementCapabilityRelDef.setToNode(relation.getToId()); - RelationshipInfo relationshipPair = new RelationshipInfo(); - relationshipPair.setId(relation.getUniqueId()); - relationshipPair.setCapabilityOwnerId(relation.getCapabilityOwnerId()); - relationshipPair.setCapabilityUid(relation.getCapabilityId()); - relationshipPair.setCapability(relation.getCapability()); - relationshipPair.setRequirementOwnerId(relation.getRequirementOwnerId()); - relationshipPair.setRequirementUid(relation.getRequirementId()); - relationshipPair.setRequirement(relation.getRequirement()); - RelationshipImpl relationship = new RelationshipImpl(); - relationship.setType(relation.getType()); - relationshipPair.setRelationships(relationship); - CapabilityRequirementRelationship rel = new CapabilityRequirementRelationship(); - rel.setRelation(relationshipPair); - List<CapabilityRequirementRelationship> relationships = new ArrayList<>(); - relationships.add(rel); - requirementCapabilityRelDef.setRelationships(relationships); - return requirementCapabilityRelDef; - } - - public static List<RelationshipInstDataDefinition> convertRelationToToscaRelation(RequirementCapabilityRelDef relation) { - - List<RelationshipInstDataDefinition> relationsList = new ArrayList<>(); - - List<CapabilityRequirementRelationship> relationship = relation.getRelationships(); - relationship.forEach(p -> { - RelationshipInstDataDefinition requirementCapabilityRelDef = new RelationshipInstDataDefinition(); - requirementCapabilityRelDef.setFromId(relation.getFromNode()); - requirementCapabilityRelDef.setToId(relation.getToNode()); - requirementCapabilityRelDef.setUniqueId(p.getRelation().getId()); - requirementCapabilityRelDef.setCapabilityOwnerId(p.getRelation().getCapabilityOwnerId()); - requirementCapabilityRelDef.setCapabilityId(p.getRelation().getCapabilityUid()); - requirementCapabilityRelDef.setRequirementOwnerId(p.getRelation().getRequirementOwnerId()); - requirementCapabilityRelDef.setRequirementId(p.getRelation().getRequirementUid()); - requirementCapabilityRelDef.setRequirement(p.getRelation().getRequirement()); - requirementCapabilityRelDef.setType(p.getRelation().getRelationship().getType()); - requirementCapabilityRelDef.setCapability(p.getRelation().getCapability()); - - relationsList.add(requirementCapabilityRelDef); - }); - - return relationsList; - } - - private static void convertCapabilities(Component component, TopologyTemplate topologyTemplate) { - - if (component.getCapabilities() != null && component.getComponentInstances() != null) { - topologyTemplate.setCalculatedCapabilities(new HashMap<>()); - topologyTemplate.setCalculatedCapabilitiesProperties(new HashMap<>()); - for (ComponentInstance instance : component.getComponentInstances()) { - Map<String, List<CapabilityDefinition>> instCapabilities = instance.getCapabilities(); - if (MapUtils.isNotEmpty(instCapabilities)) { - if (topologyTemplate.getCalculatedCapabilities() == null) { - topologyTemplate.setCalculatedCapabilities(new HashMap<>()); - } - topologyTemplate.getCalculatedCapabilities().put(instance.getUniqueId(), convertToMapListCapabiltyDataDefinition(instCapabilities)); - if (topologyTemplate.getCalculatedCapabilitiesProperties() == null) { - topologyTemplate.setCalculatedCapabilitiesProperties(new HashMap<>()); - } - topologyTemplate.getCalculatedCapabilitiesProperties().put(instance.getUniqueId(), convertToMapOfMapCapabiltyProperties(instCapabilities, instance.getUniqueId())); - } - } - } - } - - public static MapCapabiltyProperty convertToMapOfMapCapabiltyProperties(Map<String, List<CapabilityDefinition>> instCapabilities, String instanceId) { - return convertToMapOfMapCapabiltyProperties(instCapabilities, instanceId, false); - } + setComponentInstancesArtifactsToComponent(topologyTemplate, component); - public static MapCapabiltyProperty convertToMapOfMapCapabiltyProperties(Map<String, List<CapabilityDefinition>> instCapabilities, String instanceId, boolean fromCsar) { + } + } - Map<String, MapPropertiesDataDefinition> toscaCapPropMap = new HashMap<>(); + private static void setComponentInstancesArtifactsToComponent(TopologyTemplate topologyTemplate, Component component) { + Map<String, MapArtifactDataDefinition> instDeploymentArtifacts = topologyTemplate.getInstDeploymentArtifacts(); + Map<String, MapArtifactDataDefinition> instanceArtifacts = topologyTemplate.getInstanceArtifacts(); - instCapabilities.forEach(new BiConsumer<String, List<CapabilityDefinition>>() { - @Override - public void accept(String s, List<CapabilityDefinition> caps) { + List<ComponentInstance> instances = component.getComponentInstances(); + if (instDeploymentArtifacts != null && instances != null) { + instDeploymentArtifacts.entrySet().forEach(e -> { + Optional<ComponentInstance> ci = instances.stream().filter(i -> i.getUniqueId().equals(e.getKey())).findFirst(); + if (ci.isPresent()) { + Map<String, ArtifactDataDefinition> mapToscaDataDefinition = e.getValue().getMapToscaDataDefinition(); + Map<String, ArtifactDefinition> deplArt = mapToscaDataDefinition.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, en -> new ArtifactDefinition(en.getValue()))); + + ci.get().setDeploymentArtifacts(deplArt); + } + }); + } + if (instanceArtifacts != null && instances != null) { + instanceArtifacts.entrySet().forEach(e -> { + Optional<ComponentInstance> ci = instances.stream().filter(i -> i.getUniqueId().equals(e.getKey())).findFirst(); + if (ci.isPresent()) { + Map<String, ArtifactDataDefinition> mapToscaDataDefinition = e.getValue().getMapToscaDataDefinition(); + Map<String, ArtifactDefinition> deplArt = mapToscaDataDefinition.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, en -> new ArtifactDefinition(en.getValue()))); - if (caps != null && !caps.isEmpty()) { - - MapPropertiesDataDefinition dataToCreate = new MapPropertiesDataDefinition(); - - for (CapabilityDefinition cap : caps) { - List<ComponentInstanceProperty> capPrps = cap.getProperties(); - if (capPrps != null) { - - for (ComponentInstanceProperty cip : capPrps) { - dataToCreate.put(cip.getName(), new PropertyDataDefinition(cip)); - } - // format key of capability properties : - // VF instance in service : instanceId#ownerId#type#capName - // VFC instance ion VF : instanceId#ownerId#type#capName -> instanceId=ownerId - - StringBuffer sb = new StringBuffer(instanceId); - sb.append(CAP_PROP_DELIM); - if (fromCsar) { - sb.append(instanceId); - } else { - sb.append(cap.getOwnerId()); - } - sb.append(CAP_PROP_DELIM).append(s).append(CAP_PROP_DELIM).append(cap.getName()); - toscaCapPropMap.put(sb.toString(), new MapPropertiesDataDefinition(dataToCreate)); - } - } - - } - - } - }); - return new MapCapabiltyProperty(toscaCapPropMap); - } - - private static MapListCapabiltyDataDefinition convertToMapListCapabiltyDataDefinition(Map<String, List<CapabilityDefinition>> instCapabilities) { - - Map<String, ListCapabilityDataDefinition> mapToscaDataDefinition = new HashMap<>(); - for (Entry<String, List<CapabilityDefinition>> instCapability : instCapabilities.entrySet()) { - mapToscaDataDefinition.put(instCapability.getKey(), new ListCapabilityDataDefinition(instCapability.getValue().stream().map(iCap -> new CapabilityDataDefinition(iCap)).collect(Collectors.toList()))); - } - - return new MapListCapabiltyDataDefinition(mapToscaDataDefinition); - } - - private static void convertRequirements(Component component, TopologyTemplate topologyTemplate) { - - if (component.getRequirements() != null && component.getComponentInstances() != null) { - topologyTemplate.setCalculatedRequirements(new HashMap<>()); - for (ComponentInstance instance : component.getComponentInstances()) { - Map<String, List<RequirementDefinition>> instRequirements = instance.getRequirements(); - if (MapUtils.isNotEmpty(instRequirements)) { - if (topologyTemplate.getCalculatedRequirements() == null) { - topologyTemplate.setCalculatedRequirements(new HashMap<>()); - } - topologyTemplate.getCalculatedRequirements().put(instance.getUniqueId(), convertToMapListRequirementDataDefinition(instRequirements)); - } - } - } - } - - private static MapListRequirementDataDefinition convertToMapListRequirementDataDefinition(Map<String, List<RequirementDefinition>> instRequirements) { - - Map<String, ListRequirementDataDefinition> mapToscaDataDefinition = new HashMap<>(); - for (Entry<String, List<RequirementDefinition>> instRequirement : instRequirements.entrySet()) { - mapToscaDataDefinition.put(instRequirement.getKey(), new ListRequirementDataDefinition(instRequirement.getValue().stream().map(iCap -> new RequirementDataDefinition(iCap)).collect(Collectors.toList()))); - } - - return new MapListRequirementDataDefinition(mapToscaDataDefinition); - } - - @SuppressWarnings("unchecked") - private static void convertComponentFields(Component component, ToscaElement toscaElement) { - component.setName(toscaElement.getName()); - component.setAllVersions(toscaElement.getAllVersions()); - component.setCategories(toscaElement.getCategories()); - component.setComponentType(toscaElement.getComponentType()); - component.setCreationDate(toscaElement.getCreationDate()); - component.setCreatorUserId(toscaElement.getCreatorUserId()); - component.setCreatorFullName(toscaElement.getCreatorFullName()); - component.setLastUpdateDate(toscaElement.getLastUpdateDate()); - component.setLastUpdaterFullName(toscaElement.getLastUpdaterFullName()); - component.setLastUpdaterUserId(toscaElement.getLastUpdaterUserId()); - component.setNormalizedName(toscaElement.getNormalizedName()); - - component.setLifecycleState(toscaElement.getLifecycleState()); - component.setVersion(toscaElement.getVersion()); - component.setHighestVersion(toscaElement.isHighestVersion()); - component.setUniqueId(toscaElement.getUniqueId()); - component.setSystemName((String) toscaElement.getMetadataValue(JsonPresentationFields.SYSTEM_NAME)); - component.setDerivedFromGenericType(toscaElement.getDerivedFromGenericType()); - component.setDerivedFromGenericVersion(toscaElement.getDerivedFromGenericVersion()); - - if (component.getComponentType() == ComponentTypeEnum.RESOURCE) { - Resource resource = (Resource) component; - resource.setAbstract((Boolean) toscaElement.getMetadataValue(JsonPresentationFields.IS_ABSTRACT)); - resource.setToscaResourceName((String) toscaElement.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME)); - resource.setVendorName((String) toscaElement.getMetadataValue(JsonPresentationFields.VENDOR_NAME)); - resource.setVendorRelease((String) toscaElement.getMetadataValue(JsonPresentationFields.VENDOR_RELEASE)); - // field isn't mandatory , but shouldn't be null(should be an empty string instead) - if (((String) toscaElement.getMetadataValue(JsonPresentationFields.RESOURCE_VENDOR_MODEL_NUMBER)) != null){ - resource.setResourceVendorModelNumber((String) toscaElement.getMetadataValue(JsonPresentationFields.RESOURCE_VENDOR_MODEL_NUMBER)); - } else { - resource.setResourceVendorModelNumber(""); - } - } else if (component.getComponentType() == ComponentTypeEnum.SERVICE) { - Service service = (Service) component; - if (((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_TYPE)) != null){ - service.setServiceType((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_TYPE)); - } else { - service.setServiceType(""); - } - if (((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_ROLE)) != null){ - service.setServiceRole((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_ROLE)); - } else { - service.setServiceRole(""); - } - } - component.setConformanceLevel((String) toscaElement.getMetadataValue(JsonPresentationFields.CONFORMANCE_LEVEL)); - component.setIcon((String) toscaElement.getMetadataValue(JsonPresentationFields.ICON)); - component.setDescription((String) toscaElement.getMetadataValue(JsonPresentationFields.DESCRIPTION)); - component.setTags((List<String>) toscaElement.getMetadataValue(JsonPresentationFields.TAGS)); - component.setInvariantUUID((String) toscaElement.getMetadataValue(JsonPresentationFields.INVARIANT_UUID)); - component.setContactId((String) toscaElement.getMetadataValue(JsonPresentationFields.CONTACT_ID)); - component.setUUID((String) toscaElement.getMetadataValue(JsonPresentationFields.UUID)); - component.setIsDeleted((Boolean) toscaElement.getMetadataValue(JsonPresentationFields.IS_DELETED)); - - Map<String, PropertyDataDefinition> properties = toscaElement.getProperties(); - if (properties != null && !properties.isEmpty()) { - List<PropertyDefinition> propertiesMap = properties.values().stream().map(x -> new PropertyDefinition(x)).collect(Collectors.toList()); - ((Resource) component).setProperties(propertiesMap); - } - - component.setToscaType(toscaElement.getToscaType().getValue()); - } - - private static NodeType convertToNodeType(Component component) { - Resource resource = (Resource) component; - NodeType nodeType = new NodeType(); - nodeType.setDerivedFrom(resource.getDerivedFrom()); - nodeType.setDerivedList(resource.getDerivedList()); - nodeType.setResourceType(resource.getResourceType()); - // nodeType.setCapabiltiesProperties(capabiltiesProperties); - convertCommonToscaData(component, nodeType); - convertAdditionalInformation(component, nodeType); - convertArtifacts(resource, nodeType); - convertCapabilities(resource, nodeType); - convertRequirements(resource, nodeType); - convertAttributes(resource, nodeType); - convertProperties(resource, nodeType); - convertInterfaces(resource, nodeType); - return nodeType; - } - - private static void convertProperties(Resource resource, NodeType nodeType) { - List<PropertyDefinition> properties = resource.getProperties(); - if (properties != null && !properties.isEmpty()) { - Map<String, PropertyDataDefinition> propertiesMap = properties.stream().collect(Collectors.toMap(x -> x.getName(), x -> new PropertyDataDefinition(x))); - nodeType.setProperties(propertiesMap); - } - } - - private static void convertInterfaces(Resource resource, NodeType nodeType) { - Map<String, InterfaceDefinition> interfaces = resource.getInterfaces(); - if (interfaces != null) { - Map<String, InterfaceDataDefinition> interfaceArtifacts = interfaces.entrySet().stream().collect(Collectors.toMap(x -> x.getKey(), x -> new InterfaceDataDefinition(x.getValue()))); - nodeType.setInterfaceArtifacts(interfaceArtifacts); - } - } - - private static void convertAdditionalInformation(Component component, ToscaElement toscaElement) { - List<AdditionalInformationDefinition> additionalInformation = component.getAdditionalInformation(); - if (additionalInformation != null) { - Map<String, AdditionalInfoParameterDataDefinition> addInfo = additionalInformation.stream().collect(Collectors.toMap(x -> x.getUniqueId(), x -> new AdditionalInfoParameterDataDefinition(x))); - toscaElement.setAdditionalInformation(addInfo); - } - } - - private static void convertAdditionalInformation(ToscaElement toscaElement, Component resource) { - Map<String, AdditionalInfoParameterDataDefinition> additionalInformation = toscaElement.getAdditionalInformation(); - if (additionalInformation != null) { - List<AdditionalInformationDefinition> addInfo = additionalInformation.values().stream().map(e -> { - return new AdditionalInformationDefinition(e); - }).collect(Collectors.toList()); - resource.setAdditionalInformation(addInfo); - } - } - - private static void convertArtifacts(ToscaElement toscaElement, Component component) { - Map<String, ArtifactDataDefinition> artifacts = toscaElement.getArtifacts(); - Map<String, ArtifactDefinition> copy; - if (artifacts != null) { - copy = artifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDefinition(e.getValue()))); - - } else { - copy = new HashMap<>(); - } - component.setArtifacts(copy); - - Map<String, ArtifactDataDefinition> toscaArtifacts = toscaElement.getToscaArtifacts(); - if (toscaArtifacts != null) { - copy = toscaArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDefinition(e.getValue()))); - - } else { - copy = new HashMap<>(); - } - component.setToscaArtifacts(copy); - - Map<String, ArtifactDataDefinition> deploymentArtifacts = toscaElement.getDeploymentArtifacts(); - if (deploymentArtifacts != null) { - copy = deploymentArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDefinition(e.getValue()))); - - } else { - copy = new HashMap<>(); - } - component.setDeploymentArtifacts(copy); - } - - private static void convertServiceApiArtifacts(TopologyTemplate topologyTemplate, Service service) { - Map<String, ArtifactDataDefinition> serviceApiArtifacts = topologyTemplate.getServiceApiArtifacts(); - Map<String, ArtifactDefinition> copy; - if (serviceApiArtifacts != null) { - copy = serviceApiArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDefinition(e.getValue()))); - - } else { - copy = new HashMap<>(); - } - service.setServiceApiArtifacts(copy); - } - private static void convertServicePaths(TopologyTemplate topologyTemplate, Service service) { - Map<String, ForwardingPathDataDefinition> servicePaths = topologyTemplate.getForwardingPaths(); - Map<String, ForwardingPathDataDefinition> copy; - if (servicePaths != null) { - copy = servicePaths.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ForwardingPathDataDefinition(e.getValue()))); - - } else { - copy = new HashMap<>(); - } - service.setForwardingPaths(copy); - } - - private static void convertArtifacts(Component component, ToscaElement toscaElement) { - Map<String, ArtifactDefinition> artifacts = component.getArtifacts(); - if (artifacts != null) { - Map<String, ArtifactDataDefinition> copy = artifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); - toscaElement.setArtifacts(copy); - } - - Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts(); - if (toscaArtifacts != null) { - Map<String, ArtifactDataDefinition> copy = toscaArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); - toscaElement.setToscaArtifacts(copy); - } - - Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts(); - if (deploymentArtifacts != null) { - Map<String, ArtifactDataDefinition> copy = deploymentArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); - toscaElement.setDeploymentArtifacts(copy); - } - } - - private static void convertServiceApiArtifacts(Service service, TopologyTemplate topologyTemplate) { - Map<String, ArtifactDefinition> serviceApiArtifacts = service.getServiceApiArtifacts(); - if (serviceApiArtifacts != null) { - Map<String, ArtifactDataDefinition> copy = serviceApiArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); - topologyTemplate.setServiceApiArtifacts(copy); - } - } - - private static void convertCapabilities(Component component, NodeType toscaElement) { - Map<String, List<CapabilityDefinition>> capabilities = component.getCapabilities(); - - Map<String, ListCapabilityDataDefinition> toscaCapMap = new HashMap<>(); - Map<String, MapPropertiesDataDefinition> toscaCapPropMap = new HashMap<>(); - - if (capabilities != null && !capabilities.isEmpty()) { - capabilities.forEach(new BiConsumer<String, List<CapabilityDefinition>>() { - @Override - public void accept(String s, List<CapabilityDefinition> caps) { + ci.get().setArtifacts(deplArt); + } + }); + } + + } + + public static void convertComponentInstances(Component component, TopologyTemplate topologyTemplate) { + + if (!CollectionUtils.isEmpty(component.getComponentInstances())) { + + setComponentInstancesAttributesToTopologyTemplate(component, topologyTemplate); + + setComponentInstancesPropertiesToTopologyTemplate(component, topologyTemplate); + + setComponentInstancesInputsToTopologyTemplate(component, topologyTemplate); + + setComponentInstancesToTopologyTemplate(component, topologyTemplate); + + setComponentInstancesArtifactsToTopologyTemplate(component, topologyTemplate); + } + } + + public static void convertRelations(TopologyTemplate topologyTemplate, Component component) { + Map<String, RelationshipInstDataDefinition> relations = topologyTemplate.getRelations(); + List<RequirementCapabilityRelDef> componentRelations; + if (relations != null && !relations.isEmpty()) { + componentRelations = relations.values().stream().map(ModelConverter::convertRelation).collect(Collectors.toList()); + + } else { + componentRelations = new ArrayList<>(); + } + component.setComponentInstancesRelations(componentRelations); + + } + + public static RequirementCapabilityRelDef convertRelation(RelationshipInstDataDefinition relation) { + RequirementCapabilityRelDef requirementCapabilityRelDef = new RequirementCapabilityRelDef(); + requirementCapabilityRelDef.setFromNode(relation.getFromId()); + requirementCapabilityRelDef.setToNode(relation.getToId()); + requirementCapabilityRelDef.setOriginUI(BooleanUtils.isTrue(relation.isOriginUI())); + + CapabilityRequirementRelationship rel = new CapabilityRequirementRelationship(); + RelationshipInfo relationshipPair = getRelationshipInfo(relation); + rel.setRelation(relationshipPair); + requirementCapabilityRelDef.setRelationships(Arrays.asList(rel)); + + return requirementCapabilityRelDef; + } + + /** + * @param relation + * @return + */ + private static RelationshipInfo getRelationshipInfo(RelationshipInstDataDefinition relation) { + RelationshipInfo relationshipPair = new RelationshipInfo(); + + relationshipPair.setId(relation.getUniqueId()); + + relationshipPair.setCapabilityOwnerId(relation.getCapabilityOwnerId()); + relationshipPair.setCapabilityUid(relation.getCapabilityId()); + relationshipPair.setCapability(relation.getCapability()); + + relationshipPair.setRequirementOwnerId(relation.getRequirementOwnerId()); + relationshipPair.setRequirementUid(relation.getRequirementId()); + relationshipPair.setRequirement(relation.getRequirement()); + + RelationshipImpl relationship = new RelationshipImpl(); + relationship.setType(relation.getType()); + relationshipPair.setRelationships(relationship); + + return relationshipPair; + } + + + public static List<RelationshipInstDataDefinition> convertRelationToToscaRelation(RequirementCapabilityRelDef relation) { + + List<RelationshipInstDataDefinition> relationsList = new ArrayList<>(); + + List<CapabilityRequirementRelationship> relationship = relation.getRelationships(); + relationship.forEach(p -> { + RelationshipInstDataDefinition requirementCapabilityRelDef = new RelationshipInstDataDefinition(); + requirementCapabilityRelDef.setFromId(relation.getFromNode()); + requirementCapabilityRelDef.setToId(relation.getToNode()); + requirementCapabilityRelDef.setUniqueId(p.getRelation().getId()); + requirementCapabilityRelDef.setCapabilityOwnerId(p.getRelation().getCapabilityOwnerId()); + requirementCapabilityRelDef.setCapabilityId(p.getRelation().getCapabilityUid()); + requirementCapabilityRelDef.setRequirementOwnerId(p.getRelation().getRequirementOwnerId()); + requirementCapabilityRelDef.setRequirementId(p.getRelation().getRequirementUid()); + requirementCapabilityRelDef.setRequirement(p.getRelation().getRequirement()); + requirementCapabilityRelDef.setType(p.getRelation().getRelationship().getType()); + requirementCapabilityRelDef.setCapability(p.getRelation().getCapability()); + + relationsList.add(requirementCapabilityRelDef); + }); + + return relationsList; + } + + private static void convertCapabilities(Component component, TopologyTemplate topologyTemplate) { + if(componentInstancesCapabilitiesExist(component) || groupsCapabilitiesExist(component)){ + topologyTemplate.setCalculatedCapabilities(new HashMap<>()); + topologyTemplate.setCalculatedCapabilitiesProperties(new HashMap<>()); + } + convertComponentInstancesCapabilities(component, topologyTemplate); + convertGroupsCapabilities(component, topologyTemplate); + } + + private static void convertGroupsCapabilities(Component component, TopologyTemplate topologyTemplate) { + if(groupsCapabilitiesExist(component)){ + component.getGroups() + .stream() + .filter(g -> MapUtils.isNotEmpty(g.getCapabilities())) + .forEach(g -> addCapabilities(topologyTemplate, g.getCapabilities(), g.getUniqueId())); + } + } + + private static void convertComponentInstancesCapabilities(Component component, TopologyTemplate topologyTemplate) { + if (componentInstancesCapabilitiesExist(component)) { + component.getComponentInstances() + .stream() + .filter(i -> MapUtils.isNotEmpty(i.getCapabilities())) + .forEach(i -> addCapabilities(topologyTemplate, i.getCapabilities(), i.getUniqueId())); + } + } + + private static void addCapabilities(TopologyTemplate topologyTemplate, Map<String, List<CapabilityDefinition>> capabilities, String ownerId) { + if (MapUtils.isNotEmpty(capabilities)) { + if (topologyTemplate.getCalculatedCapabilities() == null) { + topologyTemplate.setCalculatedCapabilities(new HashMap<>()); + } + topologyTemplate.getCalculatedCapabilities().put(ownerId, convertToMapListCapabiltyDataDefinition(capabilities)); + if (topologyTemplate.getCalculatedCapabilitiesProperties() == null) { + topologyTemplate.setCalculatedCapabilitiesProperties(new HashMap<>()); + } + topologyTemplate.getCalculatedCapabilitiesProperties().put(ownerId, convertToMapOfMapCapabiltyProperties(capabilities, ownerId)); + } + } + + private static boolean componentInstancesCapabilitiesExist(Component component) { + return component.getCapabilities() != null && component.getComponentInstances() != null + && component.getComponentInstances() + .stream() + .filter(ci->MapUtils.isNotEmpty(ci.getCapabilities())) + .findFirst() + .isPresent(); + } + private static boolean groupsCapabilitiesExist(Component component) { + return component.getCapabilities() != null && component.getGroups() != null + && component.getGroups() + .stream() + .filter(g->MapUtils.isNotEmpty(g.getCapabilities())) + .findFirst() + .isPresent(); + } + public static MapCapabilityProperty convertToMapOfMapCapabiltyProperties(Map<String, List<CapabilityDefinition>> instCapabilities, String ownerId) { + return convertToMapOfMapCapabiltyProperties(instCapabilities, ownerId, false); + } + + public static MapCapabilityProperty convertToMapOfMapCapabiltyProperties(Map<String, List<CapabilityDefinition>> capabilities, String ownerId, boolean fromCsar) { + + Map<String, MapPropertiesDataDefinition> toscaCapPropMap = new HashMap<>(); + if(MapUtils.isNotEmpty(capabilities)) + capabilities.forEach((s, caps)-> { if (caps != null && !caps.isEmpty()) { - List<CapabilityDataDefinition> capList = caps.stream().map(o -> { - return new CapabilityDataDefinition(o); - }).collect(Collectors.toList()); - ListCapabilityDataDefinition listCapabilityDataDefinition = new ListCapabilityDataDefinition(capList); - toscaCapMap.put(s, listCapabilityDataDefinition); + MapPropertiesDataDefinition dataToCreate = new MapPropertiesDataDefinition(); for (CapabilityDefinition cap : caps) { List<ComponentInstanceProperty> capPrps = cap.getProperties(); - if (capPrps != null && !capPrps.isEmpty()) { + if (capPrps != null) { - MapPropertiesDataDefinition dataToCreate = new MapPropertiesDataDefinition(); for (ComponentInstanceProperty cip : capPrps) { dataToCreate.put(cip.getName(), new PropertyDataDefinition(cip)); } - - toscaCapPropMap.put(s + CAP_PROP_DELIM + cap.getName(), dataToCreate); - } - } - - } - - } - }); - - toscaElement.setCapabilties(toscaCapMap); - toscaElement.setCapabiltiesProperties(toscaCapPropMap); - } - } - - private static void convertAttributes(Resource component, NodeType nodeType) { - List<PropertyDefinition> attributes = component.getAttributes(); - if (attributes != null) { - Map<String, PropertyDataDefinition> attrsByName = attributes.stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, Function.identity())); - nodeType.setAttributes(attrsByName); - } - } - - private static void convertRequirements(Resource component, NodeType nodeType) { - Map<String, List<RequirementDefinition>> requirements = component.getRequirements(); - - Map<String, ListRequirementDataDefinition> toscaReqMap = new HashMap<>(); - - if (requirements != null && !requirements.isEmpty()) { - requirements.forEach(new BiConsumer<String, List<RequirementDefinition>>() { - @Override - public void accept(String s, List<RequirementDefinition> reqs) { - - if (reqs != null && !reqs.isEmpty()) { - List<RequirementDataDefinition> reqList = reqs.stream().map(o -> { - return new RequirementDataDefinition(o); - }).collect(Collectors.toList()); - - ListRequirementDataDefinition listRequirementDataDefinition = new ListRequirementDataDefinition(reqList); - toscaReqMap.put(s, listRequirementDataDefinition); - } - } - }); - nodeType.setRequirements(toscaReqMap); - } - } - - private static void convertCapabilities(NodeType toscaElement, Component component) { - Map<String, ListCapabilityDataDefinition> toscaCapabilities = toscaElement.getCapabilties(); - Map<String, MapPropertiesDataDefinition> toscaCapPropMap = toscaElement.getCapabiltiesProperties(); - - Map<String, List<CapabilityDefinition>> compCap = new HashMap<>(); - if (toscaCapabilities == null || toscaCapabilities.isEmpty()) - return; - toscaCapabilities.forEach(new BiConsumer<String, ListCapabilityDataDefinition>() { - @Override - public void accept(String s, ListCapabilityDataDefinition cap) { - - if (cap != null) { - List<CapabilityDataDefinition> capDataList = cap.getListToscaDataDefinition(); - - if (capDataList != null && !capDataList.isEmpty()) { - List<CapabilityDefinition> capList = capDataList.stream().map(o -> { - - return new CapabilityDefinition(o); - }).collect(Collectors.toList()); - compCap.put(s, capList); - } - } - - } - }); - if (toscaCapPropMap != null && !toscaCapPropMap.isEmpty()) { - toscaCapPropMap.forEach(new BiConsumer<String, MapPropertiesDataDefinition>() { - @Override - public void accept(String s, MapPropertiesDataDefinition capProp) { - String[] result = s.split(CAP_PROP_DELIM); - if (capProp != null) { - Map<String, PropertyDataDefinition> capMap = capProp.getMapToscaDataDefinition(); - - if (capMap != null && !capMap.isEmpty()) { - // List<PropertyDataDefinition> list = map.values().stream().collect(Collectors.toList()); - List<ComponentInstanceProperty> capPropsList = capMap.values().stream().map(o -> { - - return new ComponentInstanceProperty(o); - }).collect(Collectors.toList()); - - List<CapabilityDefinition> cap = compCap.get(result[0]); - Optional<CapabilityDefinition> op = cap.stream().filter(c -> c.getName().equals(result[1])).findFirst(); - if (op.isPresent()) { - op.get().setProperties(capPropsList); + // format key of capability properties : + // VF instance in service : instanceId#ownerId#type#capName + // VFC instance ion VF : instanceId#ownerId#type#capName -> instanceId=ownerId + + StringBuilder sb = new StringBuilder(ownerId); + sb.append(CAP_PROP_DELIM); + if (fromCsar) { + sb.append(ownerId); + } else { + sb.append(cap.getOwnerId()); + } + sb.append(CAP_PROP_DELIM).append(s).append(CAP_PROP_DELIM).append(cap.getName()); + toscaCapPropMap.put(sb.toString(), new MapPropertiesDataDefinition(dataToCreate)); } } - - } - - } - }); - } - - component.setCapabilities(compCap); - - } - - private static void convertGroups(TopologyTemplate toscaElement, Component component) { - Map<String, GroupDataDefinition> toscaGroups = toscaElement.getGroups(); - List<GroupDefinition> groupDefinitions = null; - if (MapUtils.isNotEmpty(toscaGroups)) { - groupDefinitions = toscaGroups.values().stream().map(g -> new GroupDefinition(g)).collect(Collectors.toList()); - } - component.setGroups(groupDefinitions); - } - - private static void convertPolicies(TopologyTemplate toscaElement, Component component) { - Map<String, PolicyDataDefinition> policies = toscaElement.getPolicies(); - Map<String, PolicyDefinition> policyDefinitions = null; - if (MapUtils.isNotEmpty(policies)) { - policyDefinitions = policies.values().stream().map(p -> new PolicyDefinition(p)).collect(Collectors.toMap(p->p.getUniqueId(), p->p)); - } - component.setPolicies(policyDefinitions); - } - - private static void convertGroups(Component component, TopologyTemplate toscaElement) { - List<GroupDefinition> groupDefinitions = component.getGroups(); - Map<String, GroupDataDefinition> groups = new HashMap<>(); - - if (groupDefinitions != null && groups.isEmpty()) { - groups = groupDefinitions.stream().collect(Collectors.toMap(pr -> pr.getName(), pr -> new GroupDataDefinition(pr))); - } - toscaElement.setGroups(groups); - } - - private static void convertPolicies(Component component, TopologyTemplate toscaElement) { - Map<String, PolicyDefinition> policyDefinitions = component.getPolicies(); - Map<String, PolicyDataDefinition> policies = new HashMap<>(); - if (MapUtils.isNotEmpty(policyDefinitions)) { - policies = policyDefinitions.values().stream().collect((Collectors.toMap(p -> p.getUniqueId(), p -> new PolicyDataDefinition(p)))); - } - toscaElement.setPolicies(policies); - } - - private static void convertRequirements(NodeType toscaElement, Component component) { - Map<String, ListRequirementDataDefinition> toscaRequirements = toscaElement.getRequirements(); - - Map<String, List<RequirementDefinition>> compReqs = new HashMap<>(); - if (toscaRequirements == null || toscaRequirements.isEmpty()) - return; - toscaRequirements.forEach(new BiConsumer<String, ListRequirementDataDefinition>() { - @Override - public void accept(String s, ListRequirementDataDefinition req) { - - if (req != null) { - List<RequirementDataDefinition> reqDataList = req.getListToscaDataDefinition(); - - if (reqDataList != null && !reqDataList.isEmpty()) { - List<RequirementDefinition> reqList = reqDataList.stream().map(o -> { - - return new RequirementDefinition(o); - }).collect(Collectors.toList()); - compReqs.put(s, reqList); } } - } - }); - component.setRequirements(compReqs); - } - - private static TopologyTemplate convertToTopologyTemplate(Component component) { - TopologyTemplate topologyTemplate; - ComponentTypeEnum componentType = component.getComponentType(); - topologyTemplate = new TopologyTemplate(); - - if (componentType == ComponentTypeEnum.RESOURCE) { - Resource resource = (Resource) component; - topologyTemplate.setResourceType(resource.getResourceType()); - topologyTemplate.setMetadataValue(JsonPresentationFields.CSAR_UUID, resource.getCsarUUID()); - topologyTemplate.setMetadataValue(JsonPresentationFields.CSAR_VERSION, resource.getCsarVersion()); - topologyTemplate.setMetadataValue(JsonPresentationFields.IMPORTED_TOSCA_CHECKSUM, resource.getImportedToscaChecksum()); - convertInterfaces(resource, topologyTemplate); - } - if (componentType == ComponentTypeEnum.SERVICE) { - convertServiceSpecificEntities((Service) component, topologyTemplate); - } - convertCommonToscaData(component, topologyTemplate); - convertArtifacts(component, topologyTemplate); - - convertAdditionalInformation(component, topologyTemplate); - convertComponentInstances(component, topologyTemplate); - - convertInputs(component, topologyTemplate); - convertCapabilities(component, topologyTemplate); - convertGroups(component, topologyTemplate); - convertPolicies(component, topologyTemplate); - convertRequirements(component, topologyTemplate); - convertRelationsToComposition(component, topologyTemplate); - - return topologyTemplate; - } - - private static void convertInterfaces(Resource resource, TopologyTemplate topologyTemplate) { - Map<String, InterfaceDefinition> interfaces = resource.getInterfaces(); - if (interfaces != null && !interfaces.isEmpty()) { - Map<String, InterfaceDataDefinition> copy = interfaces.entrySet().stream() - .collect(Collectors.toMap(Map.Entry::getKey, e -> new InterfaceDataDefinition(e.getValue()))); - topologyTemplate.setInterfaces(copy); - } - } - - private static void convertServiceSpecificEntities(Service service, TopologyTemplate topologyTemplate) { - convertServiceMetaData(service, topologyTemplate); - convertServiceApiArtifacts(service, topologyTemplate); - convertServicePaths(service,topologyTemplate); - } - - private static void convertServicePaths(Service service, TopologyTemplate topologyTemplate) { - Map<String, ForwardingPathDataDefinition> servicePaths = service.getForwardingPaths(); - if (servicePaths != null && !servicePaths.isEmpty()) { - Map<String, ForwardingPathDataDefinition> copy = servicePaths.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ForwardingPathDataDefinition(e.getValue()))); - topologyTemplate.setForwardingPaths(copy); - } - } + ); + return new MapCapabilityProperty(toscaCapPropMap); + } + + private static MapListCapabilityDataDefinition convertToMapListCapabiltyDataDefinition(Map<String, List<CapabilityDefinition>> instCapabilities) { + + Map<String, ListCapabilityDataDefinition> mapToscaDataDefinition = new HashMap<>(); + for (Entry<String, List<CapabilityDefinition>> instCapability : instCapabilities.entrySet()) { + mapToscaDataDefinition.put(instCapability.getKey(), new ListCapabilityDataDefinition(instCapability.getValue().stream().map(CapabilityDataDefinition::new).collect(Collectors.toList()))); + } + + return new MapListCapabilityDataDefinition(mapToscaDataDefinition); + } + + private static void convertRequirements(Component component, TopologyTemplate topologyTemplate) { + + if (component.getRequirements() != null && component.getComponentInstances() != null) { + topologyTemplate.setCalculatedRequirements(new HashMap<>()); + for (ComponentInstance instance : component.getComponentInstances()) { + Map<String, List<RequirementDefinition>> instRequirements = instance.getRequirements(); + if (MapUtils.isNotEmpty(instRequirements)) { + if (topologyTemplate.getCalculatedRequirements() == null) { + topologyTemplate.setCalculatedRequirements(new HashMap<>()); + } + topologyTemplate.getCalculatedRequirements().put(instance.getUniqueId(), convertToMapListRequirementDataDefinition(instRequirements)); + } + } + } + } + + private static MapListRequirementDataDefinition convertToMapListRequirementDataDefinition(Map<String, List<RequirementDefinition>> instRequirements) { + + Map<String, ListRequirementDataDefinition> mapToscaDataDefinition = new HashMap<>(); + for (Entry<String, List<RequirementDefinition>> instRequirement : instRequirements.entrySet()) { + mapToscaDataDefinition.put(instRequirement.getKey(), new ListRequirementDataDefinition(instRequirement.getValue().stream().map(RequirementDataDefinition::new).collect(Collectors.toList()))); + } + + return new MapListRequirementDataDefinition(mapToscaDataDefinition); + } + + @SuppressWarnings("unchecked") + private static void convertComponentFields(Component component, ToscaElement toscaElement) { + component.setName(toscaElement.getName()); + component.setAllVersions(toscaElement.getAllVersions()); + component.setCategories(toscaElement.getCategories()); + component.setComponentType(toscaElement.getComponentType()); + component.setCreationDate(toscaElement.getCreationDate()); + component.setCreatorUserId(toscaElement.getCreatorUserId()); + component.setCreatorFullName(toscaElement.getCreatorFullName()); + component.setLastUpdateDate(toscaElement.getLastUpdateDate()); + component.setLastUpdaterFullName(toscaElement.getLastUpdaterFullName()); + component.setLastUpdaterUserId(toscaElement.getLastUpdaterUserId()); + component.setNormalizedName(toscaElement.getNormalizedName()); + + component.setLifecycleState(toscaElement.getLifecycleState()); + component.setVersion(toscaElement.getVersion()); + component.setHighestVersion(toscaElement.isHighestVersion()); + component.setUniqueId(toscaElement.getUniqueId()); + component.setSystemName((String) toscaElement.getMetadataValue(JsonPresentationFields.SYSTEM_NAME)); + component.setDerivedFromGenericType(toscaElement.getDerivedFromGenericType()); + component.setDerivedFromGenericVersion(toscaElement.getDerivedFromGenericVersion()); + + //archive + component.setArchived(toscaElement.isArchived() == null ? false : toscaElement.isArchived()); + + + //component.setArchiveTime(toscaElement.getArchiveTime() == null ? 0L : toscaElement.getArchiveTime()); + component.setArchiveTime(toscaElement.getArchiveTime()); + component.setVspArchived(toscaElement.isVspArchived() == null ? false : toscaElement.isVspArchived()); + + if (component.getComponentType() == ComponentTypeEnum.RESOURCE) { + Resource resource = (Resource) component; + resource.setAbstract((Boolean) toscaElement.getMetadataValue(JsonPresentationFields.IS_ABSTRACT)); + resource.setToscaResourceName((String) toscaElement.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME)); + resource.setVendorName((String) toscaElement.getMetadataValue(JsonPresentationFields.VENDOR_NAME)); + resource.setVendorRelease((String) toscaElement.getMetadataValue(JsonPresentationFields.VENDOR_RELEASE)); + // field isn't mandatory , but shouldn't be null(should be an empty string instead) + if (((String) toscaElement.getMetadataValue(JsonPresentationFields.RESOURCE_VENDOR_MODEL_NUMBER)) != null){ + resource.setResourceVendorModelNumber((String) toscaElement.getMetadataValue(JsonPresentationFields.RESOURCE_VENDOR_MODEL_NUMBER)); + } else { + resource.setResourceVendorModelNumber(""); + } + } else if (component.getComponentType() == ComponentTypeEnum.SERVICE) { + Service service = (Service) component; + if (((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_TYPE)) != null){ + service.setServiceType((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_TYPE)); + } else { + service.setServiceType(""); + } + if (((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_ROLE)) != null){ + service.setServiceRole((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_ROLE)); + } else { + service.setServiceRole(""); + } + } + component.setConformanceLevel((String) toscaElement.getMetadataValue(JsonPresentationFields.CONFORMANCE_LEVEL)); + component.setIcon((String) toscaElement.getMetadataValue(JsonPresentationFields.ICON)); + component.setDescription((String) toscaElement.getMetadataValue(JsonPresentationFields.DESCRIPTION)); + component.setTags((List<String>) toscaElement.getMetadataValue(JsonPresentationFields.TAGS)); + component.setInvariantUUID((String) toscaElement.getMetadataValue(JsonPresentationFields.INVARIANT_UUID)); + component.setContactId((String) toscaElement.getMetadataValue(JsonPresentationFields.CONTACT_ID)); + component.setUUID((String) toscaElement.getMetadataValue(JsonPresentationFields.UUID)); + component.setIsDeleted((Boolean) toscaElement.getMetadataValue(JsonPresentationFields.IS_DELETED)); + + + Map<String, PropertyDataDefinition> properties = toscaElement.getProperties(); + if (properties != null && !properties.isEmpty()) { + List<PropertyDefinition> propertiesMap = properties.values().stream().map(PropertyDefinition::new).collect(Collectors.toList()); + ((Resource) component).setProperties(propertiesMap); + } + + component.setToscaType(toscaElement.getToscaType().getValue()); + } + + private static NodeType convertToNodeType(Component component) { + Resource resource = (Resource) component; + NodeType nodeType = new NodeType(); + nodeType.setDerivedFrom(resource.getDerivedFrom()); + nodeType.setDerivedList(resource.getDerivedList()); + nodeType.setResourceType(resource.getResourceType()); + convertCommonToscaData(component, nodeType); + convertAdditionalInformation(component, nodeType); + convertArtifacts(resource, nodeType); + convertCapabilities(resource, nodeType); + convertRequirements(resource, nodeType); + convertAttributes(resource, nodeType); + convertProperties(resource, nodeType); + convertInterfaces(resource, nodeType); + return nodeType; + } + + private static void convertProperties(Resource resource, NodeType nodeType) { + List<PropertyDefinition> properties = resource.getProperties(); + if (properties != null && !properties.isEmpty()) { + Map<String, PropertyDataDefinition> propertiesMap = properties.stream().collect(Collectors.toMap(PropertyDefinition::getName, PropertyDataDefinition::new)); + nodeType.setProperties(propertiesMap); + } + } + + private static void convertInterfaces(Resource resource, NodeType nodeType) { + Map<String, InterfaceDefinition> interfaces = resource.getInterfaces(); + if (interfaces != null) { + Map<String, InterfaceDataDefinition> interfaceArtifacts = interfaces.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, x -> new InterfaceDataDefinition(x.getValue()))); + nodeType.setInterfaceArtifacts(interfaceArtifacts); + } + } + + private static void convertAdditionalInformation(Component component, ToscaElement toscaElement) { + List<AdditionalInformationDefinition> additionalInformation = component.getAdditionalInformation(); + if (additionalInformation != null) { + Map<String, AdditionalInfoParameterDataDefinition> addInfo = additionalInformation.stream().collect(Collectors.toMap(AdditionalInformationDefinition::getUniqueId, AdditionalInfoParameterDataDefinition::new)); + toscaElement.setAdditionalInformation(addInfo); + } + } + + private static void convertAdditionalInformation(ToscaElement toscaElement, Component resource) { + Map<String, AdditionalInfoParameterDataDefinition> additionalInformation = toscaElement.getAdditionalInformation(); + if (additionalInformation != null) { + List<AdditionalInformationDefinition> addInfo = additionalInformation.values().stream().map(AdditionalInformationDefinition::new).collect(Collectors.toList()); + resource.setAdditionalInformation(addInfo); + } + } + + private static void convertArtifacts(ToscaElement toscaElement, Component component) { + Map<String, ArtifactDataDefinition> artifacts = toscaElement.getArtifacts(); + Map<String, ArtifactDefinition> copy; + if (artifacts != null) { + copy = artifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDefinition(e.getValue()))); + + } else { + copy = new HashMap<>(); + } + component.setArtifacts(copy); + + Map<String, ArtifactDataDefinition> toscaArtifacts = toscaElement.getToscaArtifacts(); + if (toscaArtifacts != null) { + copy = toscaArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDefinition(e.getValue()))); + + } else { + copy = new HashMap<>(); + } + component.setToscaArtifacts(copy); + + Map<String, ArtifactDataDefinition> deploymentArtifacts = toscaElement.getDeploymentArtifacts(); + if (deploymentArtifacts != null) { + copy = deploymentArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDefinition(e.getValue()))); + + } else { + copy = new HashMap<>(); + } + component.setDeploymentArtifacts(copy); + } + + private static void convertServiceApiArtifacts(TopologyTemplate topologyTemplate, Service service) { + Map<String, ArtifactDataDefinition> serviceApiArtifacts = topologyTemplate.getServiceApiArtifacts(); + Map<String, ArtifactDefinition> copy; + if (serviceApiArtifacts != null) { + copy = serviceApiArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDefinition(e.getValue()))); + + } else { + copy = new HashMap<>(); + } + service.setServiceApiArtifacts(copy); + } + private static void convertServicePaths(TopologyTemplate topologyTemplate, Service service) { + Map<String, ForwardingPathDataDefinition> servicePaths = topologyTemplate.getForwardingPaths(); + Map<String, ForwardingPathDataDefinition> copy; + if (servicePaths != null) { + copy = servicePaths.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ForwardingPathDataDefinition(e.getValue()))); + + } else { + copy = new HashMap<>(); + } + service.setForwardingPaths(copy); + } + + private static void convertArtifacts(Component component, ToscaElement toscaElement) { + Map<String, ArtifactDefinition> artifacts = component.getArtifacts(); + if (artifacts != null) { + Map<String, ArtifactDataDefinition> copy = artifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); + toscaElement.setArtifacts(copy); + } + + Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts(); + if (toscaArtifacts != null) { + Map<String, ArtifactDataDefinition> copy = toscaArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); + toscaElement.setToscaArtifacts(copy); + } + + Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts(); + if (deploymentArtifacts != null) { + Map<String, ArtifactDataDefinition> copy = deploymentArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); + toscaElement.setDeploymentArtifacts(copy); + } + } + + private static void convertServiceApiArtifacts(Service service, TopologyTemplate topologyTemplate) { + Map<String, ArtifactDefinition> serviceApiArtifacts = service.getServiceApiArtifacts(); + if (serviceApiArtifacts != null) { + Map<String, ArtifactDataDefinition> copy = serviceApiArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); + topologyTemplate.setServiceApiArtifacts(copy); + } + } + + private static void convertCapabilities(Component component, NodeType toscaElement) { + Map<String, List<CapabilityDefinition>> capabilities = component.getCapabilities(); + + Map<String, ListCapabilityDataDefinition> toscaCapMap = new HashMap<>(); + Map<String, MapPropertiesDataDefinition> toscaCapPropMap = new HashMap<>(); + + if (capabilities != null && !capabilities.isEmpty()) { + capabilities.forEach((s, caps) -> { + + if (caps != null && !caps.isEmpty()) { + List<CapabilityDataDefinition> capList = caps.stream().map(CapabilityDataDefinition::new).collect(Collectors.toList()); + + ListCapabilityDataDefinition listCapabilityDataDefinition = new ListCapabilityDataDefinition(capList); + toscaCapMap.put(s, listCapabilityDataDefinition); + + for (CapabilityDefinition cap : caps) { + List<ComponentInstanceProperty> capPrps = cap.getProperties(); + if (capPrps != null && !capPrps.isEmpty()) { + + MapPropertiesDataDefinition dataToCreate = new MapPropertiesDataDefinition(); + for (ComponentInstanceProperty cip : capPrps) { + dataToCreate.put(cip.getName(), new PropertyDataDefinition(cip)); + } + + toscaCapPropMap.put(s + CAP_PROP_DELIM + cap.getName(), dataToCreate); + } + } + } + } + ); + + toscaElement.setCapabilties(toscaCapMap); + toscaElement.setCapabiltiesProperties(toscaCapPropMap); + } + } + + private static void convertAttributes(Resource component, NodeType nodeType) { + List<PropertyDefinition> attributes = component.getAttributes(); + if (attributes != null) { + Map<String, PropertyDataDefinition> attrsByName = attributes.stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, Function.identity())); + nodeType.setAttributes(attrsByName); + } + } + + private static void convertRequirements(Resource component, NodeType nodeType) { + Map<String, List<RequirementDefinition>> requirements = component.getRequirements(); + + Map<String, ListRequirementDataDefinition> toscaReqMap = new HashMap<>(); + + if (requirements != null && !requirements.isEmpty()) { + requirements.forEach((s, reqs)-> { + + if (reqs != null && !reqs.isEmpty()) { + List<RequirementDataDefinition> reqList = reqs.stream().map(RequirementDataDefinition::new).collect(Collectors.toList()); + + ListRequirementDataDefinition listRequirementDataDefinition = new ListRequirementDataDefinition(reqList); + toscaReqMap.put(s, listRequirementDataDefinition); + } + } + ); + nodeType.setRequirements(toscaReqMap); + } + } + + private static void convertCapabilities(NodeType toscaElement, Component component) { + Map<String, ListCapabilityDataDefinition> toscaCapabilities = toscaElement.getCapabilties(); + Map<String, MapPropertiesDataDefinition> toscaCapPropMap = toscaElement.getCapabiltiesProperties(); + + Map<String, List<CapabilityDefinition>> compCap = new HashMap<>(); + if (toscaCapabilities == null || toscaCapabilities.isEmpty()) + return; + toscaCapabilities.forEach((s, cap)-> { + + if (cap != null) { + List<CapabilityDataDefinition> capDataList = cap.getListToscaDataDefinition(); + + if (capDataList != null && !capDataList.isEmpty()) { + List<CapabilityDefinition> capList = capDataList.stream().map(CapabilityDefinition::new).collect(Collectors.toList()); + compCap.put(s, capList); + } + } + + } + ); + if (toscaCapPropMap != null && !toscaCapPropMap.isEmpty()) { + toscaCapPropMap.forEach((s, capProp)-> { + String[] result = s.split(CAP_PROP_DELIM); + if (capProp != null) { + Map<String, PropertyDataDefinition> capMap = capProp.getMapToscaDataDefinition(); + + if (capMap != null && !capMap.isEmpty()) { + List<ComponentInstanceProperty> capPropsList = capMap.values().stream().map(ComponentInstanceProperty::new).collect(Collectors.toList()); + + List<CapabilityDefinition> cap = compCap.get(result[0]); + Optional<CapabilityDefinition> op = cap.stream().filter(c -> c.getName().equals(result[1])).findFirst(); + if (op.isPresent()) { + op.get().setProperties(capPropsList); + } + } + } + } + ); + } + + component.setCapabilities(compCap); + + } + + private static void convertGroups(TopologyTemplate toscaElement, Component component) { + Map<String, GroupDataDefinition> toscaGroups = toscaElement.getGroups(); + List<GroupDefinition> groupDefinitions = null; + if (MapUtils.isNotEmpty(toscaGroups)) { + groupDefinitions = toscaGroups.values().stream().map(GroupDefinition::new).collect(Collectors.toList()); + } + component.setGroups(groupDefinitions); + } + + private static void convertPolicies(TopologyTemplate toscaElement, Component component) { + Map<String, PolicyDataDefinition> policies = toscaElement.getPolicies(); + Map<String, PolicyDefinition> policyDefinitions = null; + if (MapUtils.isNotEmpty(policies)) { + policyDefinitions = policies.values().stream().map(PolicyDefinition::new).collect(Collectors.toMap(PolicyDefinition::getUniqueId, Function.identity())); + } + component.setPolicies(policyDefinitions); + } + + private static void convertGroups(Component component, TopologyTemplate toscaElement) { + List<GroupDefinition> groupDefinitions = component.getGroups(); + Map<String, GroupDataDefinition> groups = new HashMap<>(); + + if (groupDefinitions != null && groups.isEmpty()) { + groups = groupDefinitions.stream().collect(Collectors.toMap(GroupDefinition::getName, GroupDefinition::new)); + } + toscaElement.setGroups(groups); + } + + private static void convertPolicies(Component component, TopologyTemplate toscaElement) { + Map<String, PolicyDefinition> policyDefinitions = component.getPolicies(); + Map<String, PolicyDataDefinition> policies = new HashMap<>(); + if (MapUtils.isNotEmpty(policyDefinitions)) { + policies = policyDefinitions.values().stream().collect((Collectors.toMap(PolicyDefinition::getUniqueId, PolicyDataDefinition::new))); + } + toscaElement.setPolicies(policies); + } + + private static void convertRequirements(NodeType toscaElement, Component component) { + Map<String, ListRequirementDataDefinition> toscaRequirements = toscaElement.getRequirements(); + + Map<String, List<RequirementDefinition>> compReqs = new HashMap<>(); + if (toscaRequirements == null || toscaRequirements.isEmpty()) + return; + toscaRequirements.forEach((s, req) -> { + + if (req != null) { + List<RequirementDataDefinition> reqDataList = req.getListToscaDataDefinition(); + + if (reqDataList != null && !reqDataList.isEmpty()) { + List<RequirementDefinition> reqList = reqDataList.stream().map(RequirementDefinition::new).collect(Collectors.toList()); + compReqs.put(s, reqList); + } + } + } + ); + component.setRequirements(compReqs); + } + + private static TopologyTemplate convertToTopologyTemplate(Component component) { + TopologyTemplate topologyTemplate; + ComponentTypeEnum componentType = component.getComponentType(); + topologyTemplate = new TopologyTemplate(); + + if (componentType == ComponentTypeEnum.RESOURCE) { + Resource resource = (Resource) component; + topologyTemplate.setResourceType(resource.getResourceType()); + topologyTemplate.setMetadataValue(JsonPresentationFields.CSAR_UUID, resource.getCsarUUID()); + topologyTemplate.setMetadataValue(JsonPresentationFields.CSAR_VERSION, resource.getCsarVersion()); + topologyTemplate.setMetadataValue(JsonPresentationFields.IMPORTED_TOSCA_CHECKSUM, resource.getImportedToscaChecksum()); + } + if (componentType == ComponentTypeEnum.SERVICE) { + convertServiceSpecificEntities((Service) component, topologyTemplate); + } + convertCommonToscaData(component, topologyTemplate); + convertArtifacts(component, topologyTemplate); + + convertAdditionalInformation(component, topologyTemplate); + convertComponentInstances(component, topologyTemplate); + + convertInputs(component, topologyTemplate); + convertCapabilities(component, topologyTemplate); + convertGroups(component, topologyTemplate); + convertPolicies(component, topologyTemplate); + convertRequirements(component, topologyTemplate); + convertRelationsToComposition(component, topologyTemplate); + + return topologyTemplate; + } + + private static void convertServiceSpecificEntities(Service service, TopologyTemplate topologyTemplate) { + convertServiceMetaData(service, topologyTemplate); + convertServiceApiArtifacts(service, topologyTemplate); + convertServicePaths(service,topologyTemplate); + } + + private static void convertServicePaths(Service service, TopologyTemplate topologyTemplate) { + Map<String, ForwardingPathDataDefinition> servicePaths = service.getForwardingPaths(); + if (servicePaths != null && !servicePaths.isEmpty()) { + Map<String, ForwardingPathDataDefinition> copy = servicePaths.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ForwardingPathDataDefinition(e.getValue()))); + topologyTemplate.setForwardingPaths(copy); + } + } private static void convertServiceMetaData(Service service, TopologyTemplate topologyTemplate) { if (service.getDistributionStatus() != null) { - topologyTemplate.setMetadataValue(JsonPresentationFields.DISTRIBUTION_STATUS, service.getDistributionStatus().name()); + topologyTemplate.setMetadataValue(JsonPresentationFields.DISTRIBUTION_STATUS, + service.getDistributionStatus().name()); } topologyTemplate.setMetadataValue(JsonPresentationFields.PROJECT_CODE, service.getProjectCode()); - topologyTemplate.setMetadataValue(JsonPresentationFields.ECOMP_GENERATED_NAMING, service.isEcompGeneratedNaming()); + topologyTemplate.setMetadataValue(JsonPresentationFields.ECOMP_GENERATED_NAMING, + service.isEcompGeneratedNaming()); topologyTemplate.setMetadataValue(JsonPresentationFields.NAMING_POLICY, service.getNamingPolicy()); topologyTemplate.setMetadataValue(JsonPresentationFields.ENVIRONMENT_CONTEXT, service.getEnvironmentContext()); - - } - - private static void convertRelationsToComposition(Component component, TopologyTemplate topologyTemplate) { - List<RequirementCapabilityRelDef> componentInstancesRelations = component.getComponentInstancesRelations(); - if (componentInstancesRelations != null) { - Map<String, CompositionDataDefinition> compositions = topologyTemplate.getCompositions(); - if (compositions == null) { - compositions = new HashMap<>(); - } - CompositionDataDefinition compositionDataDefinition = compositions.get(JsonConstantKeysEnum.COMPOSITION.getValue()); - if (compositionDataDefinition == null) { - compositionDataDefinition = new CompositionDataDefinition(); - compositions.put(JsonConstantKeysEnum.COMPOSITION.getValue(), compositionDataDefinition); - } - - Map<String, RelationshipInstDataDefinition> relations = componentInstancesRelations.stream().flatMap(x -> convertRelationToToscaRelation(x).stream()).filter(i -> i.getUniqueId() != null) - .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i)); - compositionDataDefinition.setRelations(relations); - } - } - - private static void convertInputs(Component component, TopologyTemplate topologyTemplate) { - List<InputDefinition> inputsList = component.getInputs(); - if (inputsList != null && !inputsList.isEmpty()) { - - Map<String, PropertyDataDefinition> inputsMap = inputsList.stream().map(i -> new PropertyDataDefinition(i)).collect(Collectors.toMap(i -> i.getName(), i -> i)); - topologyTemplate.setInputs(inputsMap); - } - - } - - private static void convertInputs(TopologyTemplate topologyTemplate, Component component) { - Map<String, PropertyDataDefinition> inputsMap = topologyTemplate.getInputs(); - if (inputsMap != null && !inputsMap.isEmpty()) { - List<InputDefinition> inputsList = inputsMap.values().stream().map(i -> new InputDefinition(i)).collect(Collectors.toList()); - component.setInputs(inputsList); - } - - } - - private static void convertCommonToscaData(Component component, ToscaElement toscaElement) { - toscaElement.setUUID(component.getUUID()); - toscaElement.setUniqueId(component.getUniqueId()); - toscaElement.setSystemName(component.getSystemName()); - toscaElement.setLifecycleState(component.getLifecycleState()); - toscaElement.setComponentType(component.getComponentType()); - toscaElement.setNormalizedName(component.getNormalizedName()); - toscaElement.setMetadataValue(JsonPresentationFields.NAME, component.getName()); - toscaElement.setCategories(component.getCategories()); - toscaElement.setCreatorUserId(component.getCreatorUserId()); - toscaElement.setCreationDate(component.getCreationDate()); - toscaElement.setCreatorFullName(component.getCreatorFullName()); - toscaElement.setHighestVersion(component.isHighestVersion()); - toscaElement.setLastUpdateDate(component.getLastUpdateDate()); - toscaElement.setLastUpdaterFullName(component.getLastUpdaterFullName()); - toscaElement.setLastUpdaterUserId(component.getLastUpdaterUserId()); - toscaElement.setDerivedFromGenericType(component.getDerivedFromGenericType()); - toscaElement.setDerivedFromGenericVersion(component.getDerivedFromGenericVersion()); - - toscaElement.setLifecycleState(component.getLifecycleState()); - toscaElement.setMetadataValue(JsonPresentationFields.VERSION, component.getVersion()); - if (component.getComponentType() == ComponentTypeEnum.RESOURCE) { - toscaElement.setMetadataValue(JsonPresentationFields.IS_ABSTRACT, ((Resource) component).isAbstract()); - toscaElement.setMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME, ((Resource) component).getToscaResourceName()); - toscaElement.setMetadataValue(JsonPresentationFields.VENDOR_NAME, ((Resource) component).getVendorName()); - toscaElement.setMetadataValue(JsonPresentationFields.VENDOR_RELEASE, ((Resource) component).getVendorRelease()); - // field isn't mandatory , but shouldn't be null(should be an empty string instead) - if (((Resource) component).getResourceVendorModelNumber() != null){ - toscaElement.setMetadataValue(JsonPresentationFields.RESOURCE_VENDOR_MODEL_NUMBER, ((Resource) component).getResourceVendorModelNumber()); - } else { - toscaElement.setMetadataValue(JsonPresentationFields.RESOURCE_VENDOR_MODEL_NUMBER, ""); - } - } else if (component.getComponentType() == ComponentTypeEnum.SERVICE) { - // field isn't mandatory , but shouldn't be null(should be an empty string instead) - if (((Service) component).getServiceType() != null){ - toscaElement.setMetadataValue(JsonPresentationFields.SERVICE_TYPE, ((Service) component).getServiceType()); - } else { - toscaElement.setMetadataValue(JsonPresentationFields.SERVICE_TYPE, ""); - } - if (((Service) component).getServiceRole() != null){ - toscaElement.setMetadataValue(JsonPresentationFields.SERVICE_ROLE, ((Service) component).getServiceRole()); - } else { - toscaElement.setMetadataValue(JsonPresentationFields.SERVICE_ROLE, ""); - } - } - toscaElement.setMetadataValue(JsonPresentationFields.CONFORMANCE_LEVEL, component.getConformanceLevel()); - toscaElement.setMetadataValue(JsonPresentationFields.IS_DELETED, component.getIsDeleted()); - toscaElement.setMetadataValue(JsonPresentationFields.ICON, component.getIcon()); - toscaElement.setMetadataValue(JsonPresentationFields.DESCRIPTION, component.getDescription()); - toscaElement.setMetadataValue(JsonPresentationFields.TAGS, component.getTags()); - toscaElement.setMetadataValue(JsonPresentationFields.INVARIANT_UUID, component.getInvariantUUID()); - toscaElement.setMetadataValue(JsonPresentationFields.CONTACT_ID, component.getContactId()); - } - - - - private static void setComponentInstancesToComponent(TopologyTemplate topologyTemplate, Component component) { - - List<ComponentInstance> componentInstances = new ArrayList<>(); - ComponentInstance currComponentInstance; - for (Map.Entry<String, ComponentInstanceDataDefinition> entry : topologyTemplate.getComponentInstances().entrySet()) { - String key = entry.getKey(); - currComponentInstance = new ComponentInstance(topologyTemplate.getComponentInstances().get(key)); - if (topologyTemplate.getInstGroups() != null && topologyTemplate.getInstGroups().containsKey(key)) { - List<GroupInstance> groupInstances = topologyTemplate.getInstGroups().get(key).getMapToscaDataDefinition().entrySet().stream().map(e -> new GroupInstance(e.getValue())).collect(Collectors.toList()); - currComponentInstance.setGroupInstances(groupInstances); + topologyTemplate.setMetadataValue(JsonPresentationFields.INSTANTIATION_TYPE, service.getInstantiationType()); + + } + + private static void convertRelationsToComposition(Component component, TopologyTemplate topologyTemplate) { + List<RequirementCapabilityRelDef> componentInstancesRelations = component.getComponentInstancesRelations(); + if (componentInstancesRelations != null) { + Map<String, CompositionDataDefinition> compositions = topologyTemplate.getCompositions(); + if (compositions == null) { + compositions = new HashMap<>(); + } + CompositionDataDefinition compositionDataDefinition = compositions.get(JsonConstantKeysEnum.COMPOSITION.getValue()); + if (compositionDataDefinition == null) { + compositionDataDefinition = new CompositionDataDefinition(); + compositions.put(JsonConstantKeysEnum.COMPOSITION.getValue(), compositionDataDefinition); + } + + Map<String, RelationshipInstDataDefinition> relations = componentInstancesRelations.stream().flatMap(x -> convertRelationToToscaRelation(x).stream()).filter(i -> i.getUniqueId() != null) + .collect(Collectors.toMap(RelationshipInstDataDefinition::getUniqueId, Function.identity())); + compositionDataDefinition.setRelations(relations); + } + } + + private static void convertInputs(Component component, TopologyTemplate topologyTemplate) { + List<InputDefinition> inputsList = component.getInputs(); + if (inputsList != null && !inputsList.isEmpty()) { + + Map<String, PropertyDataDefinition> inputsMap = inputsList.stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, Function.identity())); + topologyTemplate.setInputs(inputsMap); + } + + } + + private static void convertInputs(TopologyTemplate topologyTemplate, Component component) { + Map<String, PropertyDataDefinition> inputsMap = topologyTemplate.getInputs(); + if (inputsMap != null && !inputsMap.isEmpty()) { + List<InputDefinition> inputsList = inputsMap.values() + .stream() + .map(InputDefinition::new) + .collect(Collectors.toList()); + component.setInputs(inputsList); + } + + } + + private static void convertCommonToscaData(Component component, ToscaElement toscaElement) { + toscaElement.setUUID(component.getUUID()); + toscaElement.setUniqueId(component.getUniqueId()); + toscaElement.setSystemName(component.getSystemName()); + toscaElement.setLifecycleState(component.getLifecycleState()); + toscaElement.setComponentType(component.getComponentType()); + toscaElement.setNormalizedName(component.getNormalizedName()); + toscaElement.setMetadataValue(JsonPresentationFields.NAME, component.getName()); + toscaElement.setCategories(component.getCategories()); + toscaElement.setCreatorUserId(component.getCreatorUserId()); + toscaElement.setCreationDate(component.getCreationDate()); + toscaElement.setCreatorFullName(component.getCreatorFullName()); + toscaElement.setHighestVersion(component.isHighestVersion()); + toscaElement.setLastUpdateDate(component.getLastUpdateDate()); + toscaElement.setLastUpdaterFullName(component.getLastUpdaterFullName()); + toscaElement.setLastUpdaterUserId(component.getLastUpdaterUserId()); + toscaElement.setDerivedFromGenericType(component.getDerivedFromGenericType()); + toscaElement.setDerivedFromGenericVersion(component.getDerivedFromGenericVersion()); + + //Archive + toscaElement.setArchived(component.isArchived() == null ? false : component.isArchived()); + toscaElement.setArchiveTime(component.getArchiveTime() == null ? 0L : component.getArchiveTime()); + toscaElement.setVspArchived(component.isVspArchived() == null ? false : component.isVspArchived()); + + toscaElement.setLifecycleState(component.getLifecycleState()); + toscaElement.setMetadataValue(JsonPresentationFields.VERSION, component.getVersion()); + if (component.getComponentType() == ComponentTypeEnum.RESOURCE) { + toscaElement.setMetadataValue(JsonPresentationFields.IS_ABSTRACT, ((Resource) component).isAbstract()); + toscaElement.setMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME, ((Resource) component).getToscaResourceName()); + toscaElement.setMetadataValue(JsonPresentationFields.VENDOR_NAME, ((Resource) component).getVendorName()); + toscaElement.setMetadataValue(JsonPresentationFields.VENDOR_RELEASE, ((Resource) component).getVendorRelease()); + // field isn't mandatory , but shouldn't be null(should be an empty string instead) + if (((Resource) component).getResourceVendorModelNumber() != null){ + toscaElement.setMetadataValue(JsonPresentationFields.RESOURCE_VENDOR_MODEL_NUMBER, ((Resource) component).getResourceVendorModelNumber()); + } else { + toscaElement.setMetadataValue(JsonPresentationFields.RESOURCE_VENDOR_MODEL_NUMBER, ""); + } + } else if (component.getComponentType() == ComponentTypeEnum.SERVICE) { + // field isn't mandatory , but shouldn't be null(should be an empty string instead) + if (((Service) component).getServiceType() != null){ + toscaElement.setMetadataValue(JsonPresentationFields.SERVICE_TYPE, ((Service) component).getServiceType()); + } else { + toscaElement.setMetadataValue(JsonPresentationFields.SERVICE_TYPE, ""); + } + if (((Service) component).getServiceRole() != null){ + toscaElement.setMetadataValue(JsonPresentationFields.SERVICE_ROLE, ((Service) component).getServiceRole()); + } else { + toscaElement.setMetadataValue(JsonPresentationFields.SERVICE_ROLE, ""); + } + } + toscaElement.setMetadataValue(JsonPresentationFields.CONFORMANCE_LEVEL, component.getConformanceLevel()); + toscaElement.setMetadataValue(JsonPresentationFields.IS_DELETED, component.getIsDeleted()); + toscaElement.setMetadataValue(JsonPresentationFields.ICON, component.getIcon()); + toscaElement.setMetadataValue(JsonPresentationFields.DESCRIPTION, component.getDescription()); + toscaElement.setMetadataValue(JsonPresentationFields.TAGS, component.getTags()); + toscaElement.setMetadataValue(JsonPresentationFields.INVARIANT_UUID, component.getInvariantUUID()); + toscaElement.setMetadataValue(JsonPresentationFields.CONTACT_ID, component.getContactId()); + } + + + + private static void setComponentInstancesToComponent(TopologyTemplate topologyTemplate, Component component) { + + List<ComponentInstance> componentInstances = new ArrayList<>(); + ComponentInstance currComponentInstance; + for (Map.Entry<String, ComponentInstanceDataDefinition> entry : topologyTemplate.getComponentInstances().entrySet()) { + String key = entry.getKey(); + currComponentInstance = new ComponentInstance(topologyTemplate.getComponentInstances().get(key)); + if (topologyTemplate.getInstGroups() != null && topologyTemplate.getInstGroups().containsKey(key)) { + List<GroupInstance> groupInstances = topologyTemplate.getInstGroups().get(key).getMapToscaDataDefinition().entrySet().stream().map(e -> new GroupInstance(e.getValue())).collect(Collectors.toList()); + currComponentInstance.setGroupInstances(groupInstances); + } + componentInstances.add(currComponentInstance); + } + component.setComponentInstances(componentInstances); + } + + private static void setComponentInstancesInputsToComponent(TopologyTemplate topologyTemplate, Component component) { + if (topologyTemplate.getInstInputs() != null) { + Map<String, List<ComponentInstanceInput>> inputs = new HashMap<>(); + for (Entry<String, MapPropertiesDataDefinition> entry : topologyTemplate.getInstInputs().entrySet()) { + if (entry.getValue() != null && entry.getValue().getMapToscaDataDefinition() != null) { + String key = entry.getKey(); + List<ComponentInstanceInput> componentInstanceAttributes = entry.getValue().getMapToscaDataDefinition().entrySet().stream().map(e -> new ComponentInstanceInput(e.getValue())).collect(Collectors.toList()); + inputs.put(key, componentInstanceAttributes); + } + } + component.setComponentInstancesInputs(inputs); + } + } + + private static void setComponentInstancesPropertiesToComponent(TopologyTemplate topologyTemplate, Component component) { + if (topologyTemplate.getInstProperties() != null) { + Map<String, List<ComponentInstanceProperty>> properties = new HashMap<>(); + for (Entry<String, MapPropertiesDataDefinition> entry : topologyTemplate.getInstProperties().entrySet()) { + if (entry.getValue() != null && entry.getValue().getMapToscaDataDefinition() != null) { + String key = entry.getKey(); + List<ComponentInstanceProperty> componentInstanceAttributes = entry.getValue().getMapToscaDataDefinition().entrySet().stream().map(e -> new ComponentInstanceProperty(new PropertyDefinition(e.getValue()))) + .collect(Collectors.toList()); + properties.put(key, componentInstanceAttributes); + } + } + component.setComponentInstancesProperties(properties); + } + } + + private static void setComponentInstancesAttributesToComponent(TopologyTemplate topologyTemplate, Component component) { + if (topologyTemplate.getInstAttributes() != null) { + Map<String, List<ComponentInstanceProperty>> attributes = new HashMap<>(); + for (Map.Entry<String, MapPropertiesDataDefinition> entry : topologyTemplate.getInstAttributes().entrySet()) { + if (entry.getValue() != null && entry.getValue().getMapToscaDataDefinition() != null) { + String key = entry.getKey(); + List<ComponentInstanceProperty> componentInstanceAttributes = entry.getValue().getMapToscaDataDefinition().entrySet().stream().map(e -> new ComponentInstanceProperty(new ComponentInstanceProperty(e.getValue()))) + .collect(Collectors.toList()); + attributes.put(key, componentInstanceAttributes); + } + } + component.setComponentInstancesAttributes(attributes); + } + } + + private static void setComponentInstancesRequirementsToComponent(TopologyTemplate topologyTemplate, Component component) { + + if (topologyTemplate.getCalculatedRequirements() != null) { + // Requirements of component organized by capability + Map<String, List<RequirementDefinition>> instancesRequirements = new HashMap<>(); + + Map<String, ComponentInstance> instancesMap = new HashMap<>(); + for (ComponentInstance currInstance : component.getComponentInstances()) { + instancesMap.put(currInstance.getUniqueId(), currInstance); + } + for (Map.Entry<String, MapListRequirementDataDefinition> entry : topologyTemplate.getCalculatedRequirements().entrySet()) { + + String instanceId = entry.getKey(); + // Requirements of instance organized by capability + Map<String, ListRequirementDataDefinition> capsMapList = entry.getValue().getMapToscaDataDefinition(); + + if(capsMapList != null) { + for (Entry<String, ListRequirementDataDefinition> entryTypeList : capsMapList.entrySet()) { + String capabilityType = entryTypeList.getKey(); + List<RequirementDefinition> caps = entryTypeList.getValue().getListToscaDataDefinition().stream().map(RequirementDefinition::new).collect(Collectors.toList()); + if (instancesRequirements.containsKey(capabilityType)) { + instancesRequirements.get(capabilityType).addAll(caps); + } else { + instancesRequirements.put(capabilityType, caps); + } + if (MapUtils.isEmpty(instancesMap.get(instanceId).getRequirements())) { + instancesMap.get(instanceId).setRequirements(new HashMap<>()); + } + instancesMap.get(instanceId).getRequirements().put(capabilityType, new ArrayList<>(caps)); + } + } + } + component.setRequirements(instancesRequirements); + } + } + + private static void setComponentInstancesCapabilitiesToComponentAndCI(TopologyTemplate topologyTemplate, Component component) { + Map<String, MapCapabilityProperty> calculatedCapProperties = topologyTemplate.getCalculatedCapabilitiesProperties(); + + if (topologyTemplate.getCalculatedCapabilities() != null) { + // capabilities of component organized by type + Map<String, List<CapabilityDefinition>> instancesCapabilities = new HashMap<>(); + + Map<String, ComponentInstance> instancesMap = new HashMap<>(); + for (ComponentInstance currInstance : component.getComponentInstances()) { + instancesMap.put(currInstance.getUniqueId(), currInstance); + } + for (Map.Entry<String, MapListCapabilityDataDefinition> entry : topologyTemplate.getCalculatedCapabilities().entrySet()) { + + String instanceId = entry.getKey(); + // capabilities of instance organized by type + Map<String, ListCapabilityDataDefinition> capsMapList = entry.getValue().getMapToscaDataDefinition(); + + if(capsMapList != null) { + for (Entry<String, ListCapabilityDataDefinition> entryTypeList : capsMapList.entrySet()) { + String capabilityType = entryTypeList.getKey(); + List<CapabilityDefinition> caps = entryTypeList.getValue().getListToscaDataDefinition().stream().map(cap -> mergeInstCapabiltyWithProperty(cap, instanceId, calculatedCapProperties)).collect(Collectors.toList()); + if (instancesCapabilities.containsKey(capabilityType)) { + instancesCapabilities.get(capabilityType).addAll(caps); + } else { + instancesCapabilities.put(capabilityType, caps); + } + ComponentInstance instance = instancesMap.get(instanceId); + if (instance == null) { + log.error("instance is null for id {} entry {}", instanceId, entry.getValue().getToscaPresentationValue(JsonPresentationFields.NAME)); + } else { + if (MapUtils.isEmpty(instance.getCapabilities())) { + instance.setCapabilities(new HashMap<>()); + } + instance.getCapabilities().put(capabilityType, new ArrayList<>(caps)); + } + } + } + } + component.setCapabilities(instancesCapabilities); + } + } + + private static void setCapabilitiesToComponentAndGroups(TopologyTemplate topologyTemplate, Component component) { + + Map<String, MapCapabilityProperty> calculatedCapProperties = topologyTemplate.getCalculatedCapabilitiesProperties(); + + if (capabilitiesAndGroupsExist(topologyTemplate, component)) { + Map<String, GroupDefinition> groupsMap = component.getGroups().stream().collect(Collectors.toMap(GroupDefinition::getUniqueId,Function.identity())); + + for (Map.Entry<String, MapListCapabilityDataDefinition> entry : topologyTemplate.getCalculatedCapabilities().entrySet()) { + findSetCapabilitiesToComponentAndGroup(calculatedCapProperties, component, groupsMap, entry); } - componentInstances.add(currComponentInstance); } - component.setComponentInstances(componentInstances); } - private static void setComponentInstancesInputsToComponent(TopologyTemplate topologyTemplate, Component component) { - if (topologyTemplate.getInstInputs() != null) { - Map<String, List<ComponentInstanceInput>> inputs = new HashMap<>(); - for (Entry<String, MapPropertiesDataDefinition> entry : topologyTemplate.getInstInputs().entrySet()) { - if (entry.getValue() != null && entry.getValue().getMapToscaDataDefinition() != null) { - String key = entry.getKey(); - List<ComponentInstanceInput> componentInstanceAttributes = entry.getValue().getMapToscaDataDefinition().entrySet().stream().map(e -> new ComponentInstanceInput(e.getValue())).collect(Collectors.toList()); - inputs.put(key, componentInstanceAttributes); - } - } - component.setComponentInstancesInputs(inputs); - } - } - - private static void setComponentInstancesPropertiesToComponent(TopologyTemplate topologyTemplate, Component component) { - if (topologyTemplate.getInstProperties() != null) { - Map<String, List<ComponentInstanceProperty>> properties = new HashMap<>(); - for (Entry<String, MapPropertiesDataDefinition> entry : topologyTemplate.getInstProperties().entrySet()) { - if (entry.getValue() != null && entry.getValue().getMapToscaDataDefinition() != null) { - String key = entry.getKey(); - List<ComponentInstanceProperty> componentInstanceAttributes = entry.getValue().getMapToscaDataDefinition().entrySet().stream().map(e -> new ComponentInstanceProperty(new PropertyDefinition(e.getValue()))) - .collect(Collectors.toList()); - properties.put(key, componentInstanceAttributes); - } - } - component.setComponentInstancesProperties(properties); - } - } - - private static void setComponentInstancesAttributesToComponent(TopologyTemplate topologyTemplate, Component component) { - if (topologyTemplate.getInstAttributes() != null) { - Map<String, List<ComponentInstanceProperty>> attributes = new HashMap<>(); - for (Map.Entry<String, MapPropertiesDataDefinition> entry : topologyTemplate.getInstAttributes().entrySet()) { - if (entry.getValue() != null && entry.getValue().getMapToscaDataDefinition() != null) { - String key = entry.getKey(); - List<ComponentInstanceProperty> componentInstanceAttributes = entry.getValue().getMapToscaDataDefinition().entrySet().stream().map(e -> new ComponentInstanceProperty(new ComponentInstanceProperty(e.getValue()))) - .collect(Collectors.toList()); - attributes.put(key, componentInstanceAttributes); - } - } - component.setComponentInstancesAttributes(attributes); - } + private static boolean capabilitiesAndGroupsExist(TopologyTemplate topologyTemplate, Component component) { + return MapUtils.isNotEmpty(topologyTemplate.getCalculatedCapabilities()) && CollectionUtils.isNotEmpty(component.getGroups()); } - private static void setComponentInstancesRequirementsToComponent(TopologyTemplate topologyTemplate, Component component) { - - if (topologyTemplate.getCalculatedRequirements() != null) { - // Requirements of component organized by capability - Map<String, List<RequirementDefinition>> instancesRequirements = new HashMap<>(); + private static void findSetCapabilitiesToComponentAndGroup(Map<String, MapCapabilityProperty> calculatedCapProperties, Component component, Map<String, GroupDefinition> groupsMap, Map.Entry<String, MapListCapabilityDataDefinition> entry) { - Map<String, ComponentInstance> instancesMap = new HashMap<>(); - for (ComponentInstance currInstance : component.getComponentInstances()) { - instancesMap.put(currInstance.getUniqueId(), currInstance); - } - for (Map.Entry<String, MapListRequirementDataDefinition> entry : topologyTemplate.getCalculatedRequirements().entrySet()) { - - String instanceId = entry.getKey(); - // Requirements of instance organized by capability - Map<String, ListRequirementDataDefinition> capsMapList = entry.getValue().getMapToscaDataDefinition(); - - for (Entry<String, ListRequirementDataDefinition> entryTypeList : capsMapList.entrySet()) { - String capabilityType = entryTypeList.getKey(); - List<RequirementDefinition> caps = entryTypeList.getValue().getListToscaDataDefinition().stream().map(cap -> new RequirementDefinition(cap)).collect(Collectors.toList()); - if (instancesRequirements.containsKey(capabilityType)) { - instancesRequirements.get(capabilityType).addAll(caps); - } else { - instancesRequirements.put(capabilityType, caps); - } - if (MapUtils.isEmpty(instancesMap.get(instanceId).getRequirements())) { - instancesMap.get(instanceId).setRequirements(new HashMap<>()); - } - instancesMap.get(instanceId).getRequirements().put(capabilityType, new ArrayList<>(caps)); - } - } - component.setRequirements(instancesRequirements); + String uniqueId = entry.getKey(); + if(groupsMap.containsKey(uniqueId)){ + setCapabilitiesToComponentAndGroup(calculatedCapProperties, component, entry, groupsMap.get(uniqueId)); + } else { + log.warn("The group with uniqueId {} was not found", uniqueId); } } - private static void setComponentInstancesCapabilitiesToComponentAndCI(TopologyTemplate topologyTemplate, Component component) { - Map<String, MapCapabiltyProperty> calculatedCapProperties = topologyTemplate.getCalculatedCapabilitiesProperties(); + private static void setCapabilitiesToComponentAndGroup(Map<String, MapCapabilityProperty> calculatedCapProperties, Component component, Map.Entry<String, MapListCapabilityDataDefinition> entry, GroupDefinition group) { - if (topologyTemplate.getCalculatedCapabilities() != null) { - // capabilities of component organized by type - Map<String, List<CapabilityDefinition>> instancesCapabilities = new HashMap<>(); - - Map<String, ComponentInstance> instancesMap = new HashMap<>(); - for (ComponentInstance currInstance : component.getComponentInstances()) { - instancesMap.put(currInstance.getUniqueId(), currInstance); - } - for (Map.Entry<String, MapListCapabiltyDataDefinition> entry : topologyTemplate.getCalculatedCapabilities().entrySet()) { - - String instanceId = entry.getKey(); - // capabilities of instance organized by type - Map<String, ListCapabilityDataDefinition> capsMapList = entry.getValue().getMapToscaDataDefinition(); - - for (Entry<String, ListCapabilityDataDefinition> entryTypeList : capsMapList.entrySet()) { - String capabilityType = entryTypeList.getKey(); - List<CapabilityDefinition> caps = entryTypeList.getValue().getListToscaDataDefinition().stream().map(cap -> mergeInstCapabiltyWithProperty(cap, instanceId, calculatedCapProperties)).collect(Collectors.toList()); - if (instancesCapabilities.containsKey(capabilityType)) { - instancesCapabilities.get(capabilityType).addAll(caps); - } else { - instancesCapabilities.put(capabilityType, caps); - } - ComponentInstance instance = instancesMap.get(instanceId); - if (instance == null) { - log.error("instance is null for id {} entry {}", instanceId, entry.getValue().getToscaPresentationValue(JsonPresentationFields.NAME)); - } else { - if (MapUtils.isEmpty(instance.getCapabilities())) { - instance.setCapabilities(new HashMap<>()); - } - instance.getCapabilities().put(capabilityType, new ArrayList<>(caps)); - } - } + for (Entry<String, ListCapabilityDataDefinition> entryTypeList : entry.getValue().getMapToscaDataDefinition().entrySet()) { + String capabilityType = entryTypeList.getKey(); + List<CapabilityDefinition> caps = entryTypeList.getValue().getListToscaDataDefinition().stream().map(cap -> mergeInstCapabiltyWithProperty(cap, group.getUniqueId(), calculatedCapProperties)).collect(Collectors.toList()); + if (component.getCapabilities().containsKey(capabilityType)) { + component.getCapabilities().get(capabilityType).addAll(caps); + } else { + component.getCapabilities().put(capabilityType, caps); } - component.setCapabilities(instancesCapabilities); + group.getCapabilities().put(capabilityType, Lists.newArrayList(caps)); } } - private static CapabilityDefinition mergeInstCapabiltyWithProperty(CapabilityDataDefinition cap, String instance, Map<String, MapCapabiltyProperty> calculatedCapProperties) { - CapabilityDefinition capability = new CapabilityDefinition(cap); - if (calculatedCapProperties != null) { - MapCapabiltyProperty mapOfMapPropertiesDataDefinition = calculatedCapProperties.get(instance); - if (mapOfMapPropertiesDataDefinition != null && mapOfMapPropertiesDataDefinition.getMapToscaDataDefinition() != null) { - - Map<String, MapPropertiesDataDefinition> toscaCapPropMap = mapOfMapPropertiesDataDefinition.getMapToscaDataDefinition(); - toscaCapPropMap.forEach(new BiConsumer<String, MapPropertiesDataDefinition>() { - @Override - public void accept(String s, MapPropertiesDataDefinition capProp) { - // format key of capability properties : - // VF instance in service : instanceId#ownerId#type#capName - // VFC instance ion VF : instanceId#type#capName -> instanceId=ownerId - String[] result = s.split(CAP_PROP_DELIM); - if (result.length < 4) { - log.debug("wrong key format for capabilty, key {}", capProp); - return; - } - int instanceIndex = 0; - int ownerIndex = 1; - int typeIndex = result.length - 2; - int nameIndex = result.length - 1; - if (capProp != null) { - if (result[typeIndex].equals(cap.getType()) && result[nameIndex].equals(cap.getName()) && cap.getOwnerId().equals(result[ownerIndex]) && instance.equals(result[instanceIndex])) { - - Map<String, PropertyDataDefinition> capMap = capProp.getMapToscaDataDefinition(); - - if (capMap != null && !capMap.isEmpty()) { - // List<PropertyDataDefinition> list = map.values().stream().collect(Collectors.toList()); - List<ComponentInstanceProperty> capPropsList = capMap.values().stream().map(o -> { - - return new ComponentInstanceProperty(o); - }).collect(Collectors.toList()); - - capability.setProperties(capPropsList); - } - } - } - } - }); + private static CapabilityDefinition mergeInstCapabiltyWithProperty(CapabilityDataDefinition cap, String ownerId, Map<String, MapCapabilityProperty> calculatedCapProperties) { + CapabilityDefinition capability = new CapabilityDefinition(cap); + if (calculatedCapProperties != null) { + MapCapabilityProperty mapOfMapPropertiesDataDefinition = calculatedCapProperties.get(ownerId); + if (mapOfMapPropertiesDataDefinition != null && mapOfMapPropertiesDataDefinition.getMapToscaDataDefinition() != null) { + Map<String, MapPropertiesDataDefinition> toscaCapPropMap = mapOfMapPropertiesDataDefinition.getMapToscaDataDefinition(); + toscaCapPropMap.forEach(( keyPath, capProp)-> findConvertSetProperties(cap, ownerId, capability, keyPath, capProp)); } } return capability; } - private static void setComponentInstancesToTopologyTemplate(Component component, TopologyTemplate topologyTemplate) { - - Map<String, ComponentInstanceDataDefinition> componentInstances = new HashMap<>(); - ComponentInstanceDataDefinition convertedInstance; - if (component.getComponentInstances() != null) { - for (ComponentInstance instance : component.getComponentInstances()) { - convertedInstance = new ComponentInstanceDataDefinition(instance); - if (instance.getGroupInstances() != null) { - MapGroupsDataDefinition groupsMap = new MapGroupsDataDefinition(); - - groupsMap.setMapToscaDataDefinition(instance.getGroupInstances().stream().map(e -> new GroupInstanceDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e))); - if (topologyTemplate.getInstGroups() == null) { - topologyTemplate.setInstGroups(new HashMap<>()); - } - topologyTemplate.getInstGroups().put(instance.getUniqueId(), groupsMap); - } - componentInstances.put(instance.getUniqueId(), convertedInstance); - } - } - topologyTemplate.setComponentInstances(componentInstances); - - } - - private static void setComponentInstancesInputsToTopologyTemplate(Component component, TopologyTemplate topologyTemplate) { - - if (component.getComponentInstancesInputs() != null) { - topologyTemplate.setInstInputs(new HashMap<>()); - MapPropertiesDataDefinition inputsMap; - for (Entry<String, List<ComponentInstanceInput>> entry : component.getComponentInstancesInputs().entrySet()) { - inputsMap = new MapPropertiesDataDefinition(); - - inputsMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e))); - - topologyTemplate.getInstInputs().put(entry.getKey(), inputsMap); - } - } - } - - private static void setComponentInstancesPropertiesToTopologyTemplate(Component component, TopologyTemplate topologyTemplate) { - - if (component.getComponentInstancesProperties() != null) { - topologyTemplate.setInstProperties(new HashMap<>()); - MapPropertiesDataDefinition propertiesMap; - for (Entry<String, List<ComponentInstanceProperty>> entry : component.getComponentInstancesProperties().entrySet()) { - propertiesMap = new MapPropertiesDataDefinition(); - - propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e))); - - topologyTemplate.getInstProperties().put(entry.getKey(), propertiesMap); - } - } - } - - private static void setComponentInstancesArtifactsToTopologyTemplate(Component component, TopologyTemplate topologyTemplate) { - - List<ComponentInstance> componentInstances = component.getComponentInstances(); - if (componentInstances != null) { - topologyTemplate.setInstanceArtifacts(new HashMap<>()); - topologyTemplate.setInstDeploymentArtifacts(new HashMap<>()); - - for (ComponentInstance ci : componentInstances) { - Map<String, ArtifactDefinition> artifacts = ci.getArtifacts(); - if (artifacts != null) { - Map<String, ArtifactDataDefinition> mapToscaDataDefinitionArtifact = artifacts.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), e -> new ArtifactDataDefinition(e.getValue()))); - MapArtifactDataDefinition insArtifact = new MapArtifactDataDefinition(mapToscaDataDefinitionArtifact); - topologyTemplate.getInstanceArtifacts().put(ci.getUniqueId(), insArtifact); - } - - Map<String, ArtifactDefinition> deplArtifacts = ci.getDeploymentArtifacts(); - if (deplArtifacts != null) { - Map<String, ArtifactDataDefinition> mapToscaDataDefinitionDepArtifact = deplArtifacts.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), e -> new ArtifactDataDefinition(e.getValue()))); - MapArtifactDataDefinition insDepArtifact = new MapArtifactDataDefinition(mapToscaDataDefinitionDepArtifact); - topologyTemplate.getInstDeploymentArtifacts().put(ci.getUniqueId(), insDepArtifact); - } - } - } - } - - private static void setComponentInstancesAttributesToTopologyTemplate(Component component, TopologyTemplate topologyTemplate) { - - if (component.getComponentInstancesAttributes() != null) { - topologyTemplate.setInstAttributes(new HashMap<>()); - MapPropertiesDataDefinition attributesMap; - for (Entry<String, List<ComponentInstanceProperty>> entry : component.getComponentInstancesAttributes().entrySet()) { - attributesMap = new MapPropertiesDataDefinition(); - - attributesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e))); - - topologyTemplate.getInstAttributes().put(entry.getKey(), attributesMap); - } - } - } - - public static ComponentMetadataData convertToComponentMetadata(GraphVertex vertex) { - ComponentMetadataData metadata = null; - switch (vertex.getType()) { - case SERVICE: - metadata = new ServiceMetadataData(vertex.getMetadataJson()); - break; - case RESOURCE: - metadata = new ResourceMetadataData(vertex.getMetadataJson()); - break; - case PRODUCT: - metadata = new ProductMetadataData(vertex.getMetadataJson()); - break; - default: - break; - } - if (metadata != null) { - metadata.getMetadataDataDefinition().setUniqueId(vertex.getUniqueId()); - metadata.getMetadataDataDefinition().setLastUpdateDate((Long) vertex.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE)); - metadata.getMetadataDataDefinition().setUUID((String) vertex.getJsonMetadataField(JsonPresentationFields.UUID)); - metadata.getMetadataDataDefinition().setState((String) vertex.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)); + private static void findConvertSetProperties(CapabilityDataDefinition cap, String primaryPathKey, CapabilityDefinition capability, String path, MapPropertiesDataDefinition capProp) { + // format key of capability properties : + // VF instance in service : instanceId#ownerId#type#capName + // VFC instance in VF : instanceId#type#capName -> instanceId=ownerId + // Group in service : groupName#ownerId#type#capName + // Group in VF : groupName#type#capName -> groupName=ownerId + String[] result = path.split(CAP_PROP_DELIM); + if (result.length < 4) { + log.debug("wrong key format for capabilty, key {}", capProp); + return; } - return metadata; - } - - public static List<GroupDefinition> convertToGroupDefinitions(Map<String, GroupDataDefinition> groups) { + if (relatedPropertiesExist(cap, primaryPathKey, capProp, result)) { + capability.setProperties(capProp.getMapToscaDataDefinition().values().stream().map(ComponentInstanceProperty::new).collect(Collectors.toList())); + } + } - List<GroupDefinition> groupDefinitions = null; - if (MapUtils.isNotEmpty(groups)) { - groupDefinitions = groups.values().stream().map(g -> new GroupDefinition(g)).collect(Collectors.toList()); - } - return groupDefinitions; - } + private static boolean relatedPropertiesExist(CapabilityDataDefinition cap, String primaryPathKey, MapPropertiesDataDefinition capProp, String[] result) { + return capProp != null && MapUtils.isNotEmpty(capProp.getMapToscaDataDefinition()) && areRelatedProperties(cap, primaryPathKey, result); + } + + private static boolean areRelatedProperties(CapabilityDataDefinition cap, String primaryPathKey, String[] result) { + int primaryKeyIndex = 0; + int ownerIndex = 1; + int typeIndex = result.length - 2; + int nameIndex = result.length - 1; + return result[typeIndex].equals(cap.getType()) && result[nameIndex].equals(cap.getName()) && cap.getOwnerId().equals(result[ownerIndex]) && primaryPathKey.equals(result[primaryKeyIndex]); + } + + private static void setComponentInstancesToTopologyTemplate(Component component, TopologyTemplate topologyTemplate) { + + Map<String, ComponentInstanceDataDefinition> componentInstances = new HashMap<>(); + ComponentInstanceDataDefinition convertedInstance; + if (component.getComponentInstances() != null) { + for (ComponentInstance instance : component.getComponentInstances()) { + convertedInstance = new ComponentInstanceDataDefinition(instance); + if (instance.getGroupInstances() != null) { + MapGroupsDataDefinition groupsMap = new MapGroupsDataDefinition(); + + groupsMap.setMapToscaDataDefinition(instance.getGroupInstances().stream().map(GroupInstanceDataDefinition::new).collect(Collectors.toMap(GroupInstanceDataDefinition::getName, Function.identity()))); + if (topologyTemplate.getInstGroups() == null) { + topologyTemplate.setInstGroups(new HashMap<>()); + } + topologyTemplate.getInstGroups().put(instance.getUniqueId(), groupsMap); + } + componentInstances.put(instance.getUniqueId(), convertedInstance); + } + } + topologyTemplate.setComponentInstances(componentInstances); + + } + + private static void setComponentInstancesInputsToTopologyTemplate(Component component, TopologyTemplate topologyTemplate) { + + if (component.getComponentInstancesInputs() != null) { + topologyTemplate.setInstInputs(new HashMap<>()); + MapPropertiesDataDefinition inputsMap; + for (Entry<String, List<ComponentInstanceInput>> entry : component.getComponentInstancesInputs().entrySet()) { + inputsMap = new MapPropertiesDataDefinition(); + + inputsMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, Function.identity()))); + + topologyTemplate.getInstInputs().put(entry.getKey(), inputsMap); + } + } + } + + private static void setComponentInstancesPropertiesToTopologyTemplate(Component component, TopologyTemplate topologyTemplate) { + + if (component.getComponentInstancesProperties() != null) { + topologyTemplate.setInstProperties(new HashMap<>()); + MapPropertiesDataDefinition propertiesMap; + for (Entry<String, List<ComponentInstanceProperty>> entry : component.getComponentInstancesProperties().entrySet()) { + propertiesMap = new MapPropertiesDataDefinition(); + + propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, Function.identity()))); + + topologyTemplate.getInstProperties().put(entry.getKey(), propertiesMap); + } + } + } + + private static void setComponentInstancesArtifactsToTopologyTemplate(Component component, TopologyTemplate topologyTemplate) { + + List<ComponentInstance> componentInstances = component.getComponentInstances(); + if (componentInstances != null) { + topologyTemplate.setInstanceArtifacts(new HashMap<>()); + topologyTemplate.setInstDeploymentArtifacts(new HashMap<>()); + + for (ComponentInstance ci : componentInstances) { + Map<String, ArtifactDefinition> artifacts = ci.getArtifacts(); + if (artifacts != null) { + Map<String, ArtifactDataDefinition> mapToscaDataDefinitionArtifact = artifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); + MapArtifactDataDefinition insArtifact = new MapArtifactDataDefinition(mapToscaDataDefinitionArtifact); + topologyTemplate.getInstanceArtifacts().put(ci.getUniqueId(), insArtifact); + } + + Map<String, ArtifactDefinition> deplArtifacts = ci.getDeploymentArtifacts(); + if (deplArtifacts != null) { + Map<String, ArtifactDataDefinition> mapToscaDataDefinitionDepArtifact = deplArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); + MapArtifactDataDefinition insDepArtifact = new MapArtifactDataDefinition(mapToscaDataDefinitionDepArtifact); + topologyTemplate.getInstDeploymentArtifacts().put(ci.getUniqueId(), insDepArtifact); + } + } + } + } + + private static void setComponentInstancesAttributesToTopologyTemplate(Component component, TopologyTemplate topologyTemplate) { + + if (component.getComponentInstancesAttributes() != null) { + topologyTemplate.setInstAttributes(new HashMap<>()); + MapPropertiesDataDefinition attributesMap; + for (Entry<String, List<ComponentInstanceProperty>> entry : component.getComponentInstancesAttributes().entrySet()) { + attributesMap = new MapPropertiesDataDefinition(); + + attributesMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, Function.identity()))); + + topologyTemplate.getInstAttributes().put(entry.getKey(), attributesMap); + } + } + } + + public static ComponentMetadataData convertToComponentMetadata(GraphVertex vertex) { + ComponentMetadataData metadata = null; + switch (vertex.getType()) { + case SERVICE: + metadata = new ServiceMetadataData(vertex.getMetadataJson()); + break; + case RESOURCE: + metadata = new ResourceMetadataData(vertex.getMetadataJson()); + break; + case PRODUCT: + metadata = new ProductMetadataData(vertex.getMetadataJson()); + break; + default: + break; + } + if (metadata != null) { + metadata.getMetadataDataDefinition().setUniqueId(vertex.getUniqueId()); + metadata.getMetadataDataDefinition().setLastUpdateDate((Long) vertex.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE)); + metadata.getMetadataDataDefinition().setUUID((String) vertex.getJsonMetadataField(JsonPresentationFields.UUID)); + metadata.getMetadataDataDefinition().setState((String) vertex.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)); + } + return metadata; + } + + public static List<GroupDefinition> convertToGroupDefinitions(Map<String, GroupDataDefinition> groups) { + + List<GroupDefinition> groupDefinitions = null; + if (MapUtils.isNotEmpty(groups)) { + groupDefinitions = groups.values().stream().map(GroupDefinition::new).collect(Collectors.toList()); + } + return groupDefinitions; + } + + public static Map<String, MapCapabilityProperty> extractCapabilityProperteisFromInstances(List<ComponentInstance> instances, boolean fromCsar) { + return instances + .stream() + .collect(Collectors.toMap(ComponentInstanceDataDefinition::getUniqueId, + ci -> convertToMapOfMapCapabiltyProperties(ci.getCapabilities(), ci.getUniqueId(), fromCsar))); + } + + public static Map<String, MapCapabilityProperty> extractCapabilityPropertiesFromGroups(List<GroupDefinition> groups, boolean fromCsar) { + if(CollectionUtils.isNotEmpty(groups)) + return groups + .stream() + .collect(Collectors.toMap(GroupDefinition::getUniqueId, + g -> convertToMapOfMapCapabiltyProperties(g.getCapabilities(), g.getUniqueId(), fromCsar))); + return Maps.newHashMap(); + } + + public static Map<String, MapListCapabilityDataDefinition> extractCapabilitiesFromGroups(final List<GroupDefinition> groupDefinitions) { + Map<String, MapListCapabilityDataDefinition> calculatedCapabilities = Maps.newHashMap(); + for(GroupDefinition groupDefinition :groupDefinitions){ + calculatedCapabilities.put(groupDefinition.getUniqueId(), new MapListCapabilityDataDefinition(buildMapOfListsOfCapabilities(groupDefinition))); + } + return calculatedCapabilities; + } + + public static Map<String, ListCapabilityDataDefinition> buildMapOfListsOfCapabilities(GroupDefinition groupDefinition) { + return groupDefinition.getCapabilities().entrySet() + .stream() + .collect(Collectors.toMap(Map.Entry::getKey, e-> new ListCapabilityDataDefinition(e.getValue() + .stream() + .map(CapabilityDataDefinition::new) + .collect(Collectors.toList())))); + } } |