diff options
author | Michael Lando <ml636r@att.com> | 2017-06-09 03:19:04 +0300 |
---|---|---|
committer | Michael Lando <ml636r@att.com> | 2017-06-09 03:19:04 +0300 |
commit | ed64b5edff15e702493df21aa3230b81593e6133 (patch) | |
tree | a4cb01fdaccc34930a8db403a3097c0d1e40914b /catalog-model/src/main | |
parent | 280f8015d06af1f41a3ef12e8300801c7a5e0d54 (diff) |
[SDC-29] catalog 1707 rebase commit.
Change-Id: I43c3dc5cf44abf5da817649bc738938a3e8388c1
Signed-off-by: Michael Lando <ml636r@att.com>
Diffstat (limited to 'catalog-model/src/main')
140 files changed, 20278 insertions, 5703 deletions
diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/AdditionalInformationDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/AdditionalInformationDefinition.java index 9ad0718e71..b155e50d33 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/AdditionalInformationDefinition.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/AdditionalInformationDefinition.java @@ -24,6 +24,7 @@ import java.io.Serializable; import java.util.List; import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo; public class AdditionalInformationDefinition extends AdditionalInfoParameterDataDefinition implements Serializable { @@ -34,7 +35,6 @@ public class AdditionalInformationDefinition extends AdditionalInfoParameterData private String parentUniqueId; - private List<AdditionalInfoParameterInfo> parameters; public AdditionalInformationDefinition() { super(); @@ -44,15 +44,19 @@ public class AdditionalInformationDefinition extends AdditionalInfoParameterData List<AdditionalInfoParameterInfo> parameters) { super(p); this.parentUniqueId = parentUniqueId; - this.parameters = parameters; + setParameters(parameters); + } + public AdditionalInformationDefinition(AdditionalInfoParameterDataDefinition p){ + this.setUniqueId(p.getUniqueId()); + this.setCreationTime(p.getCreationTime()); + this.setModificationTime(p.getModificationTime()); + setParameters(p.getParameters()); } - public AdditionalInformationDefinition(AdditionalInformationDefinition pd) { this.setUniqueId(pd.getUniqueId()); this.setCreationTime(pd.getCreationTime()); this.setModificationTime(pd.getModificationTime()); this.parentUniqueId = pd.parentUniqueId; - this.parameters = pd.parameters; } public String getParentUniqueId() { @@ -63,17 +67,11 @@ public class AdditionalInformationDefinition extends AdditionalInfoParameterData this.parentUniqueId = parentUniqueId; } - public List<AdditionalInfoParameterInfo> getParameters() { - return parameters; - } - - public void setParameters(List<AdditionalInfoParameterInfo> parameters) { - this.parameters = parameters; - } + @Override public String toString() { - return "AdditionalInformationDefinition [parameters=" + parameters + ", parentUniqueId=" + parentUniqueId + " " + return "AdditionalInformationDefinition [ parentUniqueId=" + parentUniqueId + " " + super.toString() + "]"; } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ArtifactDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ArtifactDefinition.java index f822e67715..434422e57b 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ArtifactDefinition.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ArtifactDefinition.java @@ -22,8 +22,11 @@ package org.openecomp.sdc.be.model; import java.io.Serializable; import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.HeatParameterDataDefinition; public class ArtifactDefinition extends ArtifactDataDefinition implements Serializable { @@ -37,9 +40,6 @@ public class ArtifactDefinition extends ArtifactDataDefinition implements Serial */ private byte[] payloadData; - private List<HeatParameterDefinition> heatParameters; - - private String generatedFromId; public byte[] getPayloadData() { return payloadData; @@ -58,32 +58,45 @@ public class ArtifactDefinition extends ArtifactDataDefinition implements Serial public ArtifactDefinition() { super(); } + public ArtifactDefinition(Map<String, Object> art) { + super(art); + } public ArtifactDefinition(ArtifactDataDefinition a) { super(a); } + + public ArtifactDefinition(ArtifactDefinition a) { + super(a); + this.payloadData = a.payloadData; + + } public ArtifactDefinition(ArtifactDataDefinition a, String payloadData) { super(a); setPayloadData(payloadData); } - public List<HeatParameterDefinition> getHeatParameters() { - return heatParameters; + public List<HeatParameterDefinition> getListHeatParameters() { + List<HeatParameterDefinition> res = null; + List<HeatParameterDataDefinition> heatParameters = super.getHeatParameters(); + if(heatParameters != null){ + res = heatParameters.stream().map(hp -> new HeatParameterDefinition(hp)).collect(Collectors.toList()); + } + return res; } - public void setHeatParameters(List<HeatParameterDefinition> properties) { - this.heatParameters = properties; + public void setListHeatParameters(List<HeatParameterDefinition> properties) { + List<HeatParameterDataDefinition> res = null; + + if(properties != null){ + res = properties.stream().map(hp -> new HeatParameterDataDefinition(hp)).collect(Collectors.toList()); + } + super.setHeatParameters(res); } - public String getGeneratedFromId() { - return generatedFromId; - } - public void setGeneratedFromId(String generatedFromId) { - this.generatedFromId = generatedFromId; - } public boolean checkEsIdExist() { if ((getEsId() != null) && (!getEsId().trim().isEmpty())) { @@ -96,8 +109,7 @@ public class ArtifactDefinition extends ArtifactDataDefinition implements Serial public int hashCode() { final int prime = 31; int result = super.hashCode(); - result = prime * result + ((generatedFromId == null) ? 0 : generatedFromId.hashCode()); - result = prime * result + ((heatParameters == null) ? 0 : heatParameters.hashCode()); + result = prime * result + ((payloadData == null) ? 0 : payloadData.hashCode()); return result; } @@ -111,23 +123,8 @@ public class ArtifactDefinition extends ArtifactDataDefinition implements Serial if (getClass() != obj.getClass()) return false; ArtifactDefinition other = (ArtifactDefinition) obj; - if (generatedFromId == null) { - if (other.generatedFromId != null) - return false; - } else if (!generatedFromId.equals(other.generatedFromId)) - return false; - if (heatParameters == null) { - if (other.heatParameters != null) - return false; - } else if (heatParameters.size() != other.heatParameters.size()) - return false; - else { - for (HeatParameterDefinition heatParam : heatParameters) { - if (!other.heatParameters.contains(heatParam)) { - return false; - } - } - } + + if (payloadData == null) { if (other.payloadData != null) return false; diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/CapabilityDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/CapabilityDefinition.java index 61ba356aa1..548f72df9c 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/CapabilityDefinition.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/CapabilityDefinition.java @@ -24,28 +24,20 @@ import java.io.Serializable; import java.util.ArrayList; import java.util.List; +import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; +import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; + /** * Specifies the capabilities that the Node Type exposes. */ -public class CapabilityDefinition implements Serializable { +public class CapabilityDefinition extends CapabilityDataDefinition implements Serializable { /** * */ private static final long serialVersionUID = -3871825415338268030L; - private String uniqueId; - - private String description; - - private String name; - - /** Identifies the type of the capability. */ - private String type; - - private List<String> validSourceTypes; - - private List<String> capabilitySources; + /** * The properties field contains all properties defined for * CapabilityDefinition @@ -53,138 +45,32 @@ public class CapabilityDefinition implements Serializable { private List<ComponentInstanceProperty> properties; // specifies the resource instance holding this requirement - private String ownerId; - private String ownerName; - private String minOccurrences; - private String maxOccurrences; + public CapabilityDefinition() { super(); } + + public CapabilityDefinition(CapabilityDataDefinition cap) { + super(cap); + } public CapabilityDefinition(CapabilityDefinition other) { - this.uniqueId = other.uniqueId; - this.description = other.description; - this.name = other.name; - this.type = other.type; - if (other.validSourceTypes != null) { - this.validSourceTypes = new ArrayList<>(other.validSourceTypes); - } - if (other.capabilitySources != null) { - this.capabilitySources = new ArrayList<>(other.capabilitySources); - } + super((CapabilityDefinition)other); + if (other.properties != null) { this.properties = new ArrayList<>(other.properties); } - this.ownerId = other.ownerId; - this.ownerName = other.ownerName; - this.minOccurrences = other.minOccurrences; - this.maxOccurrences = other.maxOccurrences; - } - - public String getUniqueId() { - return uniqueId; - } - - public void setUniqueId(String uniqueId) { - this.uniqueId = uniqueId; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public List<String> getValidSourceTypes() { - return validSourceTypes; - } - - public void setValidSourceTypes(List<String> validSourceTypes) { - this.validSourceTypes = validSourceTypes; - } - - public List<String> getCapabilitySources() { - return capabilitySources; - } - - public List<ComponentInstanceProperty> getProperties() { - return properties; - } - - public void setProperties(List<ComponentInstanceProperty> properties) { - this.properties = properties; - } - - public void setCapabilitySources(List<String> capabilitySources) { - this.capabilitySources = capabilitySources; - } - - public String getOwnerId() { - return ownerId; + } - public void setOwnerId(String ownerId) { - this.ownerId = ownerId; - } - - public String getOwnerName() { - return ownerName; - } - - public void setOwnerName(String ownerName) { - this.ownerName = ownerName; - } - - public String getMinOccurrences() { - return minOccurrences; - } - - public void setMinOccurrences(String minOccurrences) { - this.minOccurrences = minOccurrences; - } - - public String getMaxOccurrences() { - return maxOccurrences; - } - public void setMaxOccurrences(String maxOccurrences) { - this.maxOccurrences = maxOccurrences; - } @Override public int hashCode() { final int prime = 31; - int result = 1; - result = prime * result + ((capabilitySources == null) ? 0 : capabilitySources.hashCode()); - result = prime * result + ((description == null) ? 0 : description.hashCode()); - result = prime * result + ((maxOccurrences == null) ? 0 : maxOccurrences.hashCode()); - result = prime * result + ((minOccurrences == null) ? 0 : minOccurrences.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((ownerId == null) ? 0 : ownerId.hashCode()); - result = prime * result + ((ownerName == null) ? 0 : ownerName.hashCode()); + int result = super.hashCode(); result = prime * result + ((properties == null) ? 0 : properties.hashCode()); - result = prime * result + ((type == null) ? 0 : type.hashCode()); - result = prime * result + ((uniqueId == null) ? 0 : uniqueId.hashCode()); - result = prime * result + ((validSourceTypes == null) ? 0 : validSourceTypes.hashCode()); return result; } @@ -192,75 +78,34 @@ public class CapabilityDefinition implements Serializable { public boolean equals(Object obj) { if (this == obj) return true; - if (obj == null) + if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; CapabilityDefinition other = (CapabilityDefinition) obj; - if (capabilitySources == null) { - if (other.capabilitySources != null) - return false; - } else if (!capabilitySources.equals(other.capabilitySources)) - return false; - if (description == null) { - if (other.description != null) - return false; - } else if (!description.equals(other.description)) - return false; - if (maxOccurrences == null) { - if (other.maxOccurrences != null) - return false; - } else if (!maxOccurrences.equals(other.maxOccurrences)) - return false; - if (minOccurrences == null) { - if (other.minOccurrences != null) - return false; - } else if (!minOccurrences.equals(other.minOccurrences)) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (ownerId == null) { - if (other.ownerId != null) - return false; - } else if (!ownerId.equals(other.ownerId)) - return false; - if (ownerName == null) { - if (other.ownerName != null) - return false; - } else if (!ownerName.equals(other.ownerName)) - return false; if (properties == null) { if (other.properties != null) return false; } else if (!properties.equals(other.properties)) return false; - if (type == null) { - if (other.type != null) - return false; - } else if (!type.equals(other.type)) - return false; - if (uniqueId == null) { - if (other.uniqueId != null) - return false; - } else if (!uniqueId.equals(other.uniqueId)) - return false; - if (validSourceTypes == null) { - if (other.validSourceTypes != null) - return false; - } else if (!validSourceTypes.equals(other.validSourceTypes)) - return false; return true; } @Override public String toString() { - return "CapabilityDefinition [uniqueId=" + uniqueId + ", description=" + description + ", name=" + name - + ", type=" + type + ", validSourceTypes=" + validSourceTypes + ", capabilitySources=" - + capabilitySources + ", properties=" + properties + ", ownerId=" + ownerId + ", ownerName=" + ownerName - + ", minOccurrences=" + minOccurrences + ", maxOccurrences=" + maxOccurrences + "]"; + return "CapabilityDefinition [properties=" + properties + "]"; + } + + public List<ComponentInstanceProperty> getProperties() { + return properties; } + public void setProperties(List<ComponentInstanceProperty> properties) { + this.properties = properties; + } + + + + + } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Component.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Component.java index 57a70de388..6ccb49a4b3 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Component.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Component.java @@ -27,6 +27,7 @@ import java.util.Map; import java.util.Objects; import org.codehaus.jackson.annotate.JsonIgnore; +import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.category.SubCategoryDefinition; @@ -45,14 +46,6 @@ public abstract class Component implements Serializable { private List<CategoryDefinition> categories; - // User - private String creatorUserId; - private String creatorFullName; - private String lastUpdaterUserId; - private String lastUpdaterFullName; - - protected ComponentTypeEnum componentType; - private List<ComponentInstance> componentInstances; private List<RequirementCapabilityRelDef> componentInstancesRelations; @@ -70,7 +63,28 @@ public abstract class Component implements Serializable { private List<InputDefinition> inputs; private List<GroupDefinition> groups; + + private String derivedFromGenericType; + private String derivedFromGenericVersion; + private String toscaType; + protected List<AdditionalInformationDefinition> additionalInformation; + + public String getDerivedFromGenericVersion() { + return derivedFromGenericVersion; + } + public void setDerivedFromGenericVersion(String derivedFromGenericVersion) { + this.derivedFromGenericVersion = derivedFromGenericVersion; + } + + public String getDerivedFromGenericType() { + return derivedFromGenericType; + } + + public void setDerivedFromGenericType(String derivedFromGenericType) { + this.derivedFromGenericType = derivedFromGenericType; + } + public Component(ComponentMetadataDefinition componentMetadataDefinition) { this.componentMetadataDefinition = componentMetadataDefinition; } @@ -136,6 +150,10 @@ public abstract class Component implements Serializable { componentMetadataDefinition.getMetadataDataDefinition().setTags(tags); } + public void setConformanceLevel(String conformanceLevel) { + componentMetadataDefinition.getMetadataDataDefinition().setConformanceLevel(conformanceLevel); + } + public void setIcon(String icon) { componentMetadataDefinition.getMetadataDataDefinition().setIcon(icon); } @@ -145,35 +163,35 @@ public abstract class Component implements Serializable { } public String getCreatorUserId() { - return creatorUserId; + return this.componentMetadataDefinition.getMetadataDataDefinition().getCreatorUserId(); } public void setCreatorUserId(String creatorUserId) { - this.creatorUserId = creatorUserId; + this.componentMetadataDefinition.getMetadataDataDefinition().setCreatorUserId(creatorUserId); } public String getCreatorFullName() { - return creatorFullName; + return this.componentMetadataDefinition.getMetadataDataDefinition().getCreatorFullName(); } public void setCreatorFullName(String creatorFullName) { - this.creatorFullName = creatorFullName; + this.componentMetadataDefinition.getMetadataDataDefinition().setCreatorFullName(creatorFullName); } public String getLastUpdaterUserId() { - return lastUpdaterUserId; + return this.componentMetadataDefinition.getMetadataDataDefinition().getLastUpdaterUserId(); } public void setLastUpdaterUserId(String lastUpdaterUserId) { - this.lastUpdaterUserId = lastUpdaterUserId; + this.componentMetadataDefinition.getMetadataDataDefinition().setLastUpdaterUserId(lastUpdaterUserId); } public String getLastUpdaterFullName() { - return lastUpdaterFullName; + return this.componentMetadataDefinition.getMetadataDataDefinition().getLastUpdaterFullName(); } public void setLastUpdaterFullName(String lastUpdaterFullName) { - this.lastUpdaterFullName = lastUpdaterFullName; + this.componentMetadataDefinition.getMetadataDataDefinition().setLastUpdaterFullName(lastUpdaterFullName); } public String getName() { @@ -212,6 +230,10 @@ public abstract class Component implements Serializable { return componentMetadataDefinition.getMetadataDataDefinition().getTags(); } + public String getConformanceLevel() { + return componentMetadataDefinition.getMetadataDataDefinition().getConformanceLevel(); + } + public String getIcon() { return componentMetadataDefinition.getMetadataDataDefinition().getIcon(); } @@ -283,11 +305,11 @@ public abstract class Component implements Serializable { } public ComponentTypeEnum getComponentType() { - return componentType; + return this.componentMetadataDefinition.getMetadataDataDefinition().getComponentType(); } public void setComponentType(ComponentTypeEnum componentType) { - this.componentType = componentType; + this.componentMetadataDefinition.getMetadataDataDefinition().setComponentType(componentType); } public Map<String, List<CapabilityDefinition>> getCapabilities() { @@ -394,11 +416,11 @@ public abstract class Component implements Serializable { result = prime * result + ((artifacts == null) ? 0 : artifacts.hashCode()); result = prime * result + ((categories == null) ? 0 : categories.hashCode()); result = prime * result + ((componentMetadataDefinition == null) ? 0 : componentMetadataDefinition.hashCode()); - result = prime * result + ((creatorUserId == null) ? 0 : creatorUserId.hashCode()); - result = prime * result + ((creatorFullName == null) ? 0 : creatorFullName.hashCode()); +// result = prime * result + ((creatorUserId == null) ? 0 : creatorUserId.hashCode()); +// result = prime * result + ((creatorFullName == null) ? 0 : creatorFullName.hashCode()); result = prime * result + ((deploymentArtifacts == null) ? 0 : deploymentArtifacts.hashCode()); - result = prime * result + ((lastUpdaterUserId == null) ? 0 : lastUpdaterUserId.hashCode()); - result = prime * result + ((lastUpdaterFullName == null) ? 0 : lastUpdaterFullName.hashCode()); +// result = prime * result + ((lastUpdaterUserId == null) ? 0 : lastUpdaterUserId.hashCode()); +// result = prime * result + ((lastUpdaterFullName == null) ? 0 : lastUpdaterFullName.hashCode()); result = prime * result + ((capabilities == null) ? 0 : capabilities.hashCode()); result = prime * result + ((requirements == null) ? 0 : requirements.hashCode()); result = prime * result + ((componentInstances == null) ? 0 : componentInstances.hashCode()); @@ -409,6 +431,8 @@ public abstract class Component implements Serializable { result = prime * result + ((componentInstancesInputs == null) ? 0 : componentInstancesInputs.hashCode()); result = prime * result + ((componentInstancesRelations == null) ? 0 : componentInstancesRelations.hashCode()); result = prime * result + ((groups == null) ? 0 : groups.hashCode()); + result = prime * result + ((derivedFromGenericType == null) ? 0 : derivedFromGenericType.hashCode()); + result = prime * result + ((derivedFromGenericVersion == null) ? 0 : derivedFromGenericVersion.hashCode()); return result; } @@ -436,31 +460,31 @@ public abstract class Component implements Serializable { return false; } else if (!componentMetadataDefinition.equals(other.componentMetadataDefinition)) return false; - if (creatorUserId == null) { - if (other.creatorUserId != null) - return false; - } else if (!creatorUserId.equals(other.creatorUserId)) - return false; - if (creatorFullName == null) { - if (other.creatorFullName != null) - return false; - } else if (!creatorFullName.equals(other.creatorFullName)) - return false; +// if (creatorUserId == null) { +// if (other.creatorUserId != null) +// return false; +// } else if (!creatorUserId.equals(other.creatorUserId)) +// return false; +// if (creatorFullName == null) { +// if (other.creatorFullName != null) +// return false; +// } else if (!creatorFullName.equals(other.creatorFullName)) +// return false; if (deploymentArtifacts == null) { if (other.deploymentArtifacts != null) return false; } else if (!deploymentArtifacts.equals(other.deploymentArtifacts)) return false; - if (lastUpdaterUserId == null) { - if (other.lastUpdaterUserId != null) - return false; - } else if (!lastUpdaterUserId.equals(other.lastUpdaterUserId)) - return false; - if (lastUpdaterFullName == null) { - if (other.lastUpdaterFullName != null) - return false; - } else if (!lastUpdaterFullName.equals(other.lastUpdaterFullName)) - return false; +// if (lastUpdaterUserId == null) { +// if (other.lastUpdaterUserId != null) +// return false; +// } else if (!lastUpdaterUserId.equals(other.lastUpdaterUserId)) +// return false; +// if (lastUpdaterFullName == null) { +// if (other.lastUpdaterFullName != null) +// return false; +// } else if (!lastUpdaterFullName.equals(other.lastUpdaterFullName)) +// return false; if (componentInstances == null) { if (other.componentInstances != null) return false; @@ -498,6 +522,16 @@ public abstract class Component implements Serializable { return false; } else if (!groups.equals(other.groups)) return false; + if (derivedFromGenericType == null) { + if (other.derivedFromGenericType != null) + return false; + } else if (!derivedFromGenericType.equals(other.derivedFromGenericType)) + return false; + if (derivedFromGenericVersion == null) { + if (other.derivedFromGenericVersion != null) + return false; + } else if (!derivedFromGenericVersion.equals(other.derivedFromGenericVersion)) + return false; return true; } @@ -595,4 +629,49 @@ public abstract class Component implements Serializable { public void setSpecificComponetTypeArtifacts(Map<String, ArtifactDefinition> specificComponentTypeArtifacts) { // Implement where needed } + + public void setMetadataDefinition(ComponentMetadataDefinition metadataDefinition) { + this.componentMetadataDefinition = metadataDefinition; + } + + public String fetchGenericTypeToscaNameFromConfig(){ + // Implement where needed + return ConfigurationManager.getConfigurationManager().getConfiguration().getGenericAssetNodeTypes().get(this.assetType()); + } + + public String assetType(){ + // Implement where needed + return this.getComponentType().getValue(); + } + + public boolean shouldGenerateInputs(){ + // Implement where needed + return true; + } + + public boolean deriveFromGeneric(){ + // Implement where needed + return true; + } + + public void setDerivedFromGenericInfo(Resource genericType){ + derivedFromGenericType = genericType.getToscaResourceName(); + derivedFromGenericVersion = genericType.getVersion(); + } + + public String getToscaType() { + return toscaType; + } + + public void setToscaType(String toscaType) { + this.toscaType = toscaType; + } + public List<AdditionalInformationDefinition> getAdditionalInformation() { + return additionalInformation; + } + + public void setAdditionalInformation(List<AdditionalInformationDefinition> additionalInformation) { + this.additionalInformation = additionalInformation; + } + } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstInputsMap.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstInputsMap.java index ce9ac67ced..9d016c0799 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstInputsMap.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstInputsMap.java @@ -20,12 +20,19 @@ package org.openecomp.sdc.be.model; +import java.io.Serializable; import java.util.List; import java.util.Map; -public class ComponentInstInputsMap { +public class ComponentInstInputsMap implements Serializable{ + /** + * + */ + private static final long serialVersionUID = 1136631343963488131L; + Map<String, List<InputDefinition>> componentInstanceInputsMap; + Map<String, List<ComponentInstancePropInput>> componentInstanceProperties; public Map<String, List<InputDefinition>> getComponentInstanceInputsMap() { return componentInstanceInputsMap; @@ -34,4 +41,12 @@ public class ComponentInstInputsMap { public void setComponentInstanceInputsMap(Map<String, List<InputDefinition>> componentInstanceInputsMap) { this.componentInstanceInputsMap = componentInstanceInputsMap; } + + public Map<String, List<ComponentInstancePropInput>> getComponentInstanceProperties() { + return componentInstanceProperties; + } + + public void setComponentInstancePropInput(Map<String, List<ComponentInstancePropInput>> componentInstanceProperties) { + this.componentInstanceProperties = componentInstanceProperties; + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstance.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstance.java index baaf89bcfc..0b7e523813 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstance.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstance.java @@ -33,14 +33,11 @@ public class ComponentInstance extends ComponentInstanceDataDefinition implement */ private static final long serialVersionUID = 6721465693884621223L; - private String icon; - - private String componentName; - private String componentVersion; - private String toscaComponentName; private Map<String, List<CapabilityDefinition>> capabilities; private Map<String, List<RequirementDefinition>> requirements; private Map<String, ArtifactDefinition> deploymentArtifacts; + private Map<String, ArtifactDefinition> artifacts; + private List<GroupInstance> groupInstances; public ComponentInstance() { super(); @@ -50,38 +47,6 @@ public class ComponentInstance extends ComponentInstanceDataDefinition implement super(r); } - public String getIcon() { - return icon; - } - - public void setIcon(String icon) { - this.icon = icon; - } - - public String getComponentName() { - return componentName; - } - - public void setComponentName(String resourceName) { - this.componentName = resourceName; - } - - public String getComponentVersion() { - return componentVersion; - } - - public String getToscaComponentName() { - return toscaComponentName; - } - - public void setToscaComponentName(String toscaComponentName) { - this.toscaComponentName = toscaComponentName; - } - - public void setComponentVersion(String resourceVersion) { - this.componentVersion = resourceVersion; - } - public Map<String, List<CapabilityDefinition>> getCapabilities() { return capabilities; } @@ -105,5 +70,21 @@ public class ComponentInstance extends ComponentInstanceDataDefinition implement public void setDeploymentArtifacts(Map<String, ArtifactDefinition> deploymentArtifacts) { this.deploymentArtifacts = deploymentArtifacts; } + + public Map<String, ArtifactDefinition> getArtifacts() { + return artifacts; + } + public void setArtifacts(Map<String, ArtifactDefinition> artifacts) { + this.artifacts = artifacts; + } + + public List<GroupInstance> getGroupInstances() { + return groupInstances; + } + + public void setGroupInstances(List<GroupInstance> groupInstances) { + this.groupInstances = groupInstances; + } + } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceAttribute.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceAttribute.java index 12233e733c..4e55152526 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceAttribute.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceAttribute.java @@ -49,6 +49,10 @@ public class ComponentInstanceAttribute extends AttributeDefinition setParentUniqueId(pd.getParentUniqueId()); } + public ComponentInstanceAttribute(AttributeDefinition attributeDefinition) { + super(attributeDefinition); + } + public String getValueUniqueUid() { return valueUniqueUid; } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceInput.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceInput.java index 1334fa8c06..ca53db69d9 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceInput.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceInput.java @@ -28,6 +28,11 @@ import org.openecomp.sdc.be.datatypes.elements.PropertyRule; public class ComponentInstanceInput extends InputDefinition implements IComponentInstanceConnectedElement { /** + * + */ + private static final long serialVersionUID = -3937554584759816724L; + + /** * Value of property */ private String value; @@ -64,6 +69,13 @@ public class ComponentInstanceInput extends InputDefinition implements IComponen this.valueUniqueUid = valueUniqueUid; } + public ComponentInstanceInput(PropertyDataDefinition propertyDefinition) { + super(propertyDefinition); + if(propertyDefinition.getGetInputValues() != null && !propertyDefinition.getGetInputValues().isEmpty()){ + this.inputId = propertyDefinition.getGetInputValues().get(0).getInputId(); + } + } + public String getComponentInstanceName() { return componentInstanceName; } @@ -104,13 +116,13 @@ public class ComponentInstanceInput extends InputDefinition implements IComponen this.valueUniqueUid = valueUniqueUid; } - public boolean isDefinition() { + /*public boolean isDefinition() { return definition; } public void setDefinition(boolean definition) { this.definition = definition; - } + }*/ public List<String> getPath() { return path; diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/AdditionalInfoParameterInfo.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstancePropInput.java index 674681081c..9f5e3e9eea 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/AdditionalInfoParameterInfo.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstancePropInput.java @@ -21,62 +21,45 @@ package org.openecomp.sdc.be.model; import java.io.Serializable; +import java.util.Map; -public class AdditionalInfoParameterInfo implements Serializable { - +public class ComponentInstancePropInput extends ComponentInstanceProperty implements Serializable{ /** * */ - private static final long serialVersionUID = 2066876282722907709L; - - String uniqueId; - String key; - String value; - - public AdditionalInfoParameterInfo() { - super(); - } - - public AdditionalInfoParameterInfo(String key, String value) { - super(); - this.key = key; - this.value = value; - } - - public AdditionalInfoParameterInfo(String uniqueId, String key, String value) { + private static final long serialVersionUID = -7991205190252140617L; + + + private String propertiesName; + private PropertyDefinition input; + + public ComponentInstancePropInput() { super(); - this.uniqueId = uniqueId; - this.key = key; - this.value = value; } - - public String getUniqueId() { - return uniqueId; + + public ComponentInstancePropInput(ComponentInstanceProperty p) { + super(p); } - - public void setUniqueId(String uniqueId) { - this.uniqueId = uniqueId; + + public String getPropertiesName() { + return propertiesName; } - - public String getKey() { - return key; + public void setPropertiesName(String propertiesName) { + this.propertiesName = propertiesName; } - - public void setKey(String key) { - this.key = key; + public PropertyDefinition getInput() { + return input; } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - @Override - public String toString() { - return "AdditionalInfoParameterInfo [uniqueId=" + uniqueId + ", key=" + key + ", value=" + value + "]"; + public void setInput(PropertyDefinition input) { + this.input = input; + } + + public String[] getParsedPropNames(){ + String[] tokens = null; + if(propertiesName != null && !propertiesName.isEmpty()){ + tokens = propertiesName.split("#"); + } + return tokens; } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceProperty.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceProperty.java index a804170c75..17eb045630 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceProperty.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceProperty.java @@ -23,10 +23,11 @@ package org.openecomp.sdc.be.model; import java.io.Serializable; import java.util.List; + +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyRule; -public class ComponentInstanceProperty extends PropertyDefinition - implements IComponentInstanceConnectedElement, Serializable { +public class ComponentInstanceProperty extends PropertyDefinition implements IComponentInstanceConnectedElement, Serializable { /** * @@ -36,7 +37,7 @@ public class ComponentInstanceProperty extends PropertyDefinition /** * Value of property */ - private String value; + /** * The unique id of the property value on graph @@ -47,26 +48,47 @@ public class ComponentInstanceProperty extends PropertyDefinition private List<PropertyRule> rules = null; - private List<GetInputValueInfo> getInputValues; + + + private String componentInstanceName; + + private String componentInstanceId; + + public String getComponentInstanceName() { + return componentInstanceName; + } + + public void setComponentInstanceName(String componentInstanceName) { + this.componentInstanceName = componentInstanceName; + } + + public String getComponentInstanceId() { + return componentInstanceId; + } + + public void setComponentInstanceId(String componentInstanceId) { + this.componentInstanceId = componentInstanceId; + } public ComponentInstanceProperty() { super(); } + public ComponentInstanceProperty(PropertyDataDefinition pd) { + super(pd); + } + + public ComponentInstanceProperty(PropertyDefinition pd) { + super(pd); + } public ComponentInstanceProperty(PropertyDefinition pd, String value, String valueUniqueUid) { super(pd); - this.value = value; + this.setValue(value); this.valueUniqueUid = valueUniqueUid; } - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } + public String getValueUniqueUid() { return valueUniqueUid; @@ -76,13 +98,6 @@ public class ComponentInstanceProperty extends PropertyDefinition this.valueUniqueUid = valueUniqueUid; } - public boolean isDefinition() { - return definition; - } - - public void setDefinition(boolean definition) { - this.definition = definition; - } public List<String> getPath() { return path; @@ -100,18 +115,10 @@ public class ComponentInstanceProperty extends PropertyDefinition this.rules = rules; } - public List<GetInputValueInfo> getGetInputValues() { - return getInputValues; - } - - public void setGetInputValues(List<GetInputValueInfo> getInputValues) { - this.getInputValues = getInputValues; - } - + @Override public String toString() { - return "ComponentInstanceProperty [ " + super.toString() + " , value=" + value + ", valueUniqueUid = " - + valueUniqueUid + " , rules=" + rules + " , path=" + path + " ]"; + return "ComponentInstanceProperty [ " + super.toString() + " , value=" + getValue() + ", valueUniqueUid = " + valueUniqueUid + " , rules=" + rules + " , path=" + path + " ]"; } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentParametersView.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentParametersView.java index 0227de5b50..4078a47f86 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentParametersView.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentParametersView.java @@ -20,6 +20,10 @@ package org.openecomp.sdc.be.model; +import java.util.List; + +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.datatypes.enums.ComponentFieldsEnum; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; public class ComponentParametersView { @@ -41,6 +45,99 @@ public class ComponentParametersView { boolean ignoreComponentInstancesAttributesFrom = false; boolean ignoreInputs = false; boolean ignoreComponentInstancesInputs = false; + boolean ignoreCapabiltyProperties = true; + + public ComponentParametersView() { + } + + public ComponentParametersView(boolean setAllToIgnore) { + this(); + if(setAllToIgnore){ + this.disableAll(); + } + } + + public ComponentParametersView(List<String> filters) { + this(true); + + for(String fieldName: filters) { + switch (ComponentFieldsEnum.findByValue(fieldName)) { + case PROPERTIES: + this.setIgnoreProperties(false); + break; + case INPUTS: + this.setIgnoreInputs(false);; + break; + case USERS: + this.setIgnoreUsers(false); + break; + case CATEGORIES: + this.setIgnoreCategories(false); + break; + case METADATA: + this.setIgnoreUsers(false); + this.setIgnoreCategories(false); + this.setIgnoreAllVersions(false); + this.setIgnoreDerivedFrom(false); + break; + case GROUPS: + this.setIgnoreGroups(false); + break; + case COMPONENT_INSTANCES: + this.setIgnoreComponentInstances(false); + this.setIgnoreCapabilities(false); + this.setIgnoreRequirements(false); + break; + case COMPONENT_INSTANCES_PROPERTIES: + this.setIgnoreComponentInstances(false); //we need this in order to get the calculate capabilities requirements + this.setIgnoreComponentInstancesProperties(false); + break; + case CAPABILITIES: + this.setIgnoreComponentInstances(false);//we need this in order to get the calculate capabilities requirements + this.setIgnoreCapabilities(false); + break; + case REQUIREMENTS: + this.setIgnoreComponentInstances(false); + this.setIgnoreRequirements(false); + break; + case ALL_VERSIONS: + this.setIgnoreAllVersions(false); + break; + case ADDITIONAL_INFORMATION: + this.setIgnoreAdditionalInformation(false); + break; + case ARTIFACTS: + case DEPLOYMENT_ARTIFACTS: + case TOSCA_ARTIFACTS: + case SERVICE_API_ARTIFACTS: + this.setIgnoreArtifacts(false); + break; + case INTERFACES: + this.setIgnoreInterfaces(false); + break; + case DERIVED_FROM: + this.setIgnoreDerivedFrom(false); + break; + case ATTRIBUTES: + this.setIgnoreAttributesFrom(false); + break; + case COMPONENT_INSTANCES_ATTRIBUTES: + this.setIgnoreComponentInstances(false); + this.setIgnoreComponentInstancesAttributesFrom(false); + break; + case COMPONENT_INSTANCE_INPUTS: + this.setIgnoreComponentInstances(false); + this.setIgnoreComponentInstancesInputs(false); + break; + case INSTANCE_CAPABILTY_PROPERTIES: + this.setIgnoreCapabiltyProperties(false); + break; + default: + break; + } + + } + } /////////////////////////////////////////////////////////////// // When adding new member, please update the filter method. @@ -152,7 +249,6 @@ public class ComponentParametersView { if (ignoreComponentInstancesInputs) { component.setComponentInstancesInputs(null); } - return component; } @@ -175,6 +271,7 @@ public class ComponentParametersView { ignoreInputs = true; ignoreComponentInstancesAttributesFrom = true; ignoreComponentInstancesInputs = true; + ignoreCapabiltyProperties = true; } public boolean isIgnoreGroups() { @@ -278,7 +375,7 @@ public class ComponentParametersView { } public void setIgnoreAttributesFrom(boolean ignoreAttributesFrom) { - this.ignoreAttributesFrom = ignoreDerivedFrom; + this.ignoreAttributesFrom = ignoreAttributesFrom; } public boolean isIgnoreComponentInstancesAttributesFrom() { @@ -313,4 +410,21 @@ public class ComponentParametersView { this.ignoreInputs = ignoreInputs; } + public boolean isIgnoreCapabiltyProperties() { + return ignoreCapabiltyProperties; + } + + public void setIgnoreCapabiltyProperties(boolean ignoreCapabiltyProperties) { + this.ignoreCapabiltyProperties = ignoreCapabiltyProperties; + } + + public JsonParseFlagEnum detectParseFlag() { + JsonParseFlagEnum parseFlag; + if(isIgnoreComponentInstances()){ + parseFlag = JsonParseFlagEnum.ParseMetadata; + } else { + parseFlag = JsonParseFlagEnum.ParseAll; + } + return parseFlag; + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/DerivedNodeTypeResolver.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/DerivedNodeTypeResolver.java new file mode 100644 index 0000000000..fff3e81d7a --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/DerivedNodeTypeResolver.java @@ -0,0 +1,15 @@ +package org.openecomp.sdc.be.model; + +import fj.data.Either; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.model.jsontitan.datamodel.NodeType; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; + +import java.util.List; + +public interface DerivedNodeTypeResolver { + + Either<List<GraphVertex>, TitanOperationStatus> findDerivedResources(String parentResource); + +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/DistributionStatusEnum.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/DistributionStatusEnum.java index 89b5bfff31..139cd70a3c 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/DistributionStatusEnum.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/DistributionStatusEnum.java @@ -21,10 +21,7 @@ package org.openecomp.sdc.be.model; public enum DistributionStatusEnum { - DISTRIBUTION_NOT_APPROVED("Distribution not approved"), - DISTRIBUTION_APPROVED("Distribution approved"), - DISTRIBUTED("Distributed"), - DISTRIBUTION_REJECTED("Distribution rejected"); + DISTRIBUTION_NOT_APPROVED("Distribution not approved"), DISTRIBUTION_APPROVED("Distribution approved"), DISTRIBUTED("Distributed"), DISTRIBUTION_REJECTED("Distribution rejected"); private String value; @@ -39,8 +36,7 @@ public enum DistributionStatusEnum { public static DistributionStatusEnum findState(String state) { for (DistributionStatusEnum distributionStatus : DistributionStatusEnum.values()) { - if (distributionStatus.name().equalsIgnoreCase(state) - || distributionStatus.getValue().equalsIgnoreCase(state)) { + if (distributionStatus.name().equalsIgnoreCase(state) || distributionStatus.getValue().equalsIgnoreCase(state)) { return distributionStatus; } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupDefinition.java index 5520e89032..167fa2f0a1 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupDefinition.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupDefinition.java @@ -21,36 +21,26 @@ package org.openecomp.sdc.be.model; import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashMap; import java.util.List; -import java.util.Map; import java.util.stream.Collectors; import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; public class GroupDefinition extends GroupDataDefinition implements Serializable { - /** * */ private static final long serialVersionUID = -852613634651112247L; - // map of componentInstances <name: uniqueId> - private Map<String, String> members; - // properties (properties should be defined in the group type, the // properties here are actually the value for the properties) - private List<GroupProperty> properties; + - // artifacts - list of artifact uid. All artifacts in the group must already - // be uploaded to the VF - private List<String> artifacts; - private List<String> artifactsUuid; // The unique id of the type of this group - private String typeUid; + public GroupDefinition() { super(); @@ -68,66 +58,26 @@ public class GroupDefinition extends GroupDataDefinition implements Serializable this.setInvariantUUID(other.getInvariantUUID()); this.setGroupUUID(other.getGroupUUID()); this.setDescription(other.getDescription()); - if (other.members != null) { - this.members = new HashMap<String, String>(other.getMembers()); - } - if (other.properties != null) { - this.properties = other.properties.stream().map(p -> new GroupProperty(p)).collect(Collectors.toList()); - } - if (other.artifacts != null) { - this.artifacts = new ArrayList<String>(other.getArtifacts()); - } - - if (other.artifactsUuid != null) { - this.artifactsUuid = new ArrayList<String>(other.getArtifactsUuid()); - } - this.setTypeUid(other.typeUid); - } - - public Map<String, String> getMembers() { - return members; + this.setTypeUid(other.getTypeUid()); + this.setProperties(other.getProperties()); + } - public void setMembers(Map<String, String> members) { - this.members = members; - } - - public List<GroupProperty> getProperties() { + public List<GroupProperty> convertToGroupProperties() { + List<GroupProperty> properties = null; + List<PropertyDataDefinition> propList = super.getProperties(); + if(propList != null && !propList .isEmpty()){ + properties = propList.stream().map(pr -> new GroupProperty(pr)).collect(Collectors.toList()); + } return properties; } - public void setProperties(List<GroupProperty> properties) { - this.properties = properties; - } - - public List<String> getArtifacts() { - return artifacts; - } - - public void setArtifacts(List<String> artifacts) { - this.artifacts = artifacts; - } - - public String getTypeUid() { - return typeUid; - } - - public void setTypeUid(String typeUid) { - this.typeUid = typeUid; - } - - public List<String> getArtifactsUuid() { - return artifactsUuid; - } - - public void setArtifactsUuid(List<String> artifactsUuid) { - this.artifactsUuid = artifactsUuid; - } - - @Override - public String toString() { - return "GroupDefinition [" + super.toString() + "members=" + members + ", properties=" + properties - + ", artifacts=" + artifacts + ", artifactsUUID=" + artifactsUuid + ", typeUid=" + typeUid + "]"; + public void convertFromGroupProperties(List<GroupProperty> properties) { + if(properties != null && !properties .isEmpty()){ + List<PropertyDataDefinition> propList = properties.stream().map(pr -> new PropertyDataDefinition(pr)).collect(Collectors.toList()); + super.setProperties(propList); + } + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupInstance.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupInstance.java new file mode 100644 index 0000000000..f0e08b85fd --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupInstance.java @@ -0,0 +1,57 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model; + +import java.io.Serializable; +import java.util.List; +import java.util.stream.Collectors; +import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; + +public class GroupInstance extends GroupInstanceDataDefinition implements Serializable { + + private static final long serialVersionUID = -2066335818115254401L; + + public GroupInstance() { + super(); + } + + public GroupInstance(GroupInstanceDataDefinition r) { + super(r); + } + + public List<GroupInstanceProperty> convertToGroupInstancesProperties() { + List<GroupInstanceProperty> groupInstancesProperties = null; + List<PropertyDataDefinition> propertiesList = super.getProperties(); + if(propertiesList != null && !propertiesList .isEmpty()){ + groupInstancesProperties = propertiesList.stream().map(p -> new GroupInstanceProperty(p)).collect(Collectors.toList()); + } + return groupInstancesProperties; + } + + public void convertFromGroupInstancesProperties(List<GroupInstanceProperty> groupInstancesProperties) { + if(groupInstancesProperties != null && !groupInstancesProperties .isEmpty()){ + List<PropertyDataDefinition> propList = groupInstancesProperties.stream().map(p -> new PropertyDataDefinition(p)).collect(Collectors.toList()); + super.setProperties(propList); + } + } + +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/GetInputValueInfo.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupInstanceProperty.java index bb53e13251..e1e51729e0 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/GetInputValueInfo.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupInstanceProperty.java @@ -20,52 +20,43 @@ package org.openecomp.sdc.be.model; -public class GetInputValueInfo { - String propName; - String inputName; - Integer indexValue; - GetInputValueInfo getInputIndex; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; - boolean isList = false; - - public String getPropName() { - return propName; - } - - public void setPropName(String propName) { - this.propName = propName; +public class GroupInstanceProperty extends GroupProperty { + + /** + * + */ + private static final long serialVersionUID = 1L; + private String parentValue; + + public GroupInstanceProperty() { + super(); } - public String getInputName() { - return inputName; + public GroupInstanceProperty(GroupProperty gp, String parentValue) { + super(gp); + this.parentValue = parentValue; } - public void setInputName(String inputName) { - this.inputName = inputName; + public GroupInstanceProperty(GroupInstanceProperty other) { + super(other); + if (other != null) { + this.parentValue = other.getParentValue(); + } } - - public Integer getIndexValue() { - return indexValue; - } - - public void setIndexValue(Integer indexValue) { - this.indexValue = indexValue; + + public GroupInstanceProperty(PropertyDataDefinition propertyDataDefinition) { + super(propertyDataDefinition); } - public GetInputValueInfo getGetInputIndex() { - return getInputIndex; + public String getParentValue() { + return parentValue; } - public void setGetInputIndex(GetInputValueInfo getInputIndex) { - this.getInputIndex = getInputIndex; + public void setParentValue(String parentValue) { + this.parentValue = parentValue; } - - public boolean isList() { - return isList; - } - - public void setList(boolean isList) { - this.isList = isList; - } - + + } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupProperty.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupProperty.java index cf0afde8e3..d8589d51b9 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupProperty.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/GroupProperty.java @@ -20,12 +20,15 @@ package org.openecomp.sdc.be.model; +import org.apache.commons.lang.StringUtils; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; + public class GroupProperty extends PropertyDefinition { /** * current value */ - private String value; +// private String value; /** * The unique is of Group property on graph. If it is null, then the @@ -40,24 +43,19 @@ public class GroupProperty extends PropertyDefinition { public GroupProperty(PropertyDefinition pd, String value, String valueUniqueUid) { super(pd); - this.value = value; + setValue(value); this.valueUniqueUid = valueUniqueUid; } public GroupProperty(GroupProperty other) { super(other); if (other != null) { - this.value = other.getValue(); + setValue(other.getValue()); this.valueUniqueUid = other.getValueUniqueUid(); } } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; + public GroupProperty(PropertyDataDefinition other) { + super(other); } public String getValueUniqueUid() { @@ -70,7 +68,7 @@ public class GroupProperty extends PropertyDefinition { @Override public String toString() { - return "GroupProperty [ " + super.toString() + " , value=" + value + ", valueUniqueUid = " + valueUniqueUid + return "GroupProperty [ " + super.toString() + ", valueUniqueUid = " + valueUniqueUid + " ]"; } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/InputDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/InputDefinition.java index 3090d7232e..2359d635a3 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/InputDefinition.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/InputDefinition.java @@ -25,57 +25,33 @@ import java.util.List; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; public class InputDefinition extends PropertyDefinition { - String label; - Boolean hidden; - Boolean immutable; - List<ComponentInstanceInput> inputsValue; + /** + * + */ + private static final long serialVersionUID = -6920076037265309468L; + + List<ComponentInstanceInput> inputs; List<ComponentInstanceProperty> properties; public InputDefinition() { super(); - // TODO Auto-generated constructor stub } public InputDefinition(PropertyDataDefinition p) { super(p); - // TODO Auto-generated constructor stub } public InputDefinition(PropertyDefinition pd) { super(pd); - // TODO Auto-generated constructor stub - } - - public Boolean isHidden() { - return hidden; - } - - public void setHidden(Boolean hidden) { - this.hidden = hidden; - } - - public Boolean isImmutable() { - return immutable; - } - - public void setImmutable(Boolean immutable) { - this.immutable = immutable; - } - - public String getLabel() { - return label; - } - - public void setLabel(String label) { - this.label = label; } - public List<ComponentInstanceInput> getInputsValue() { - return inputsValue; + + public List<ComponentInstanceInput> getInputs() { + return inputs; } - public void setInputsValue(List<ComponentInstanceInput> inputsValue) { - this.inputsValue = inputsValue; + public void setInputs(List<ComponentInstanceInput> inputs) { + this.inputs = inputs; } public List<ComponentInstanceProperty> getProperties() { diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/InterfaceDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/InterfaceDefinition.java index 51ad31199a..8897d6ed4e 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/InterfaceDefinition.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/InterfaceDefinition.java @@ -23,8 +23,12 @@ package org.openecomp.sdc.be.model; import java.io.Serializable; import java.util.HashMap; import java.util.Map; +import java.util.stream.Collectors; +import org.codehaus.jackson.annotate.JsonIgnore; +import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition; import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition; /** * Definition of the operations that can be performed on (instances of) a Node @@ -39,28 +43,21 @@ public class InterfaceDefinition extends InterfaceDataDefinition implements IOpe */ private static final long serialVersionUID = 8220887972866354746L; - /** - * Defines an operation available to manage particular aspects of the Node - * Type. - */ - private Map<String, Operation> operations = new HashMap<String, Operation>(); + private boolean definition; public InterfaceDefinition() { super(); - // TODO Auto-generated constructor stub } public InterfaceDefinition(String type, String description, Map<String, Operation> operations) { super(type, description); - this.operations = operations; - + setOperationsMap(operations); } public InterfaceDefinition(InterfaceDataDefinition p) { super(p); - // TODO Auto-generated constructor stub } @Override @@ -72,18 +69,20 @@ public class InterfaceDefinition extends InterfaceDataDefinition implements IOpe public void setDefinition(boolean definition) { this.definition = definition; } - - public Map<String, Operation> getOperations() { - return operations; + @JsonIgnore + public Map<String, Operation> getOperationsMap() { + Map<String, Operation> convertedOperation = getOperations().entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), e -> new Operation(e.getValue()))); + return convertedOperation; } - - public void setOperations(Map<String, Operation> operations) { - this.operations = operations; + @JsonIgnore + public void setOperationsMap(Map<String, Operation> operations) { + Map<String, OperationDataDefinition> convertedOperation = operations.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), e -> new OperationDataDefinition(e.getValue()))); + setOperations(convertedOperation); } @Override public String toString() { - return "InterfaceDefinition [operations=" + operations + ", definition=" + definition + "]"; + return "InterfaceDefinition [definition=" + definition + "]"; } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Operation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Operation.java index a793c68528..4347cd45fc 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Operation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Operation.java @@ -23,8 +23,8 @@ package org.openecomp.sdc.be.model; import java.util.Map; import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.InputsValueDataDefinition; import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; /** * Defines an operation available to manage particular aspects of the Node Type. @@ -33,15 +33,7 @@ import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition; */ public class Operation extends OperationDataDefinition implements IOperationParameter { - /** Implementation artifact for the interface. */ - private ArtifactDefinition implementation; - /** - * This OPTIONAL property contains a list of one or more input parameter - * definitions. - */ - // @JsonDeserialize(contentUsing = OperationParameterDeserializer.class) - private Map<String, PropertyValueDefinition> inputs; private boolean definition; @@ -56,23 +48,21 @@ public class Operation extends OperationDataDefinition implements IOperationPara */ public Operation() { super(); - // TODO Auto-generated constructor stub } public Operation(OperationDataDefinition p) { super(p); - // TODO Auto-generated constructor stub } public Operation(ArtifactDataDefinition implementation, String description, - Map<String, InputsValueDataDefinition> inputs) { + Map<String, PropertyDataDefinition> inputs) { super(description); - + setImplementation(implementation); + setInputs(inputs); } @Override public boolean isDefinition() { - // TODO Auto-generated method stub return false; } @@ -80,26 +70,15 @@ public class Operation extends OperationDataDefinition implements IOperationPara this.definition = definition; } - public ArtifactDefinition getImplementation() { - return implementation; - } - - public void setImplementation(ArtifactDefinition implementation) { - this.implementation = implementation; - } - - public Map<String, PropertyValueDefinition> getInputs() { - return inputs; - } - - public void setInputs(Map<String, PropertyValueDefinition> inputs) { - this.inputs = inputs; - } - @Override public String toString() { - return "Operation [implementation=" + implementation + ", inputs=" + inputs + ", definition=" + definition - + "]"; + return "Operation [definition=" + definition + "]"; } + public ArtifactDefinition getImplementationArtifact(){ + if ( getImplementation() != null ){ + return new ArtifactDefinition(getImplementation()); + } + return null; + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Product.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Product.java index 04223857b7..12e6eaf018 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Product.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Product.java @@ -29,12 +29,12 @@ public class Product extends Component { public Product() { super(new ProductMetadataDefinition()); - componentType = ComponentTypeEnum.PRODUCT; + this.getComponentMetadataDefinition().getMetadataDataDefinition().setComponentType(ComponentTypeEnum.PRODUCT); } public Product(ProductMetadataDefinition productMetadataDefinition) { super(productMetadataDefinition); - componentType = ComponentTypeEnum.PRODUCT; + this.getComponentMetadataDefinition().getMetadataDataDefinition().setComponentType(ComponentTypeEnum.PRODUCT); } public String getFullName() { diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyDefinition.java index 7974e863ac..b315d5c7fd 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyDefinition.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyDefinition.java @@ -22,36 +22,93 @@ package org.openecomp.sdc.be.model; import java.io.Serializable; import java.util.List; - import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; -//import javax.validation.Valid; -//import javax.validation.constraints.NotNull; -// -// -//import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -//import com.fasterxml.jackson.annotation.JsonProperty; -//import com.fasterxml.jackson.databind.annotation.JsonDeserialize; public class PropertyDefinition extends PropertyDataDefinition implements IOperationParameter, IComplexDefaultValue, Serializable { + + /**The enumeration presents the list of property names with specific behavior + * @author rbetzer + * + */ + public enum PropertyNames { + + MIN_INSTANCES("min_vf_module_instances", GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL), + MAX_INSTANCES("max_vf_module_instances", GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL), + INITIAL_COUNT("initial_count", GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL), + VF_MODULE_LABEL("vf_module_label", GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_RESOURCE_LEVEL), + VF_MODULE_DESCRIPTION("vf_module_description", GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_RESOURCE_LEVEL), + NETWORK_ROLE("network_role", GroupInstancePropertyValueUpdateBehavior.NOT_RELEVANT), + AVAILABILTY_ZONE_COUNT("availability_zone_count", GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL), + VFC_LIST("vfc_list", GroupInstancePropertyValueUpdateBehavior.UPDATABLE_ON_SERVICE_LEVEL); + + private String propertyName; + private GroupInstancePropertyValueUpdateBehavior updateBehavior; + + private PropertyNames(String propertyName,GroupInstancePropertyValueUpdateBehavior updateBehavior){ + this.propertyName = propertyName; + this.updateBehavior = updateBehavior; + } + + public String getPropertyName() { + return propertyName; + } + + public GroupInstancePropertyValueUpdateBehavior getUpdateBehavior() { + return updateBehavior; + } + /** + * finds PropertyNames according received string name + * @param name + * @return + */ + public static PropertyNames findName(String name){ + for (PropertyNames e : PropertyNames.values()) { + if (e.getPropertyName().equals(name)) { + return e; + } + } + return null; + } + } /** - * + * The enumeration presents the list of highest levels for which update property value is allowed + * @author nsheshukov + * */ + public enum GroupInstancePropertyValueUpdateBehavior{ + NOT_RELEVANT("NOT_RELEVANT", -1), + UPDATABLE_ON_RESOURCE_LEVEL("UPDATABLE_ON_VF_LEVEL", 0), + UPDATABLE_ON_SERVICE_LEVEL("UPDATABLE_ON_SERVICE_LEVEL", 1); + + String levelName; + int levelNumber; + + private GroupInstancePropertyValueUpdateBehavior(String name, int levelNumber){ + this.levelName = name; + this.levelNumber = levelNumber; + } + + public String getLevelName() { + return levelName; + } + + public int getLevelNumber() { + return levelNumber; + } + } + private static final long serialVersionUID = 188403656600317269L; private List<PropertyConstraint> constraints; // private Schema schema; private String status; - private String name; - /** - * The resource id which this property belongs to - */ - private String parentUniqueId; + public PropertyDefinition() { super(); } @@ -61,16 +118,10 @@ public class PropertyDefinition extends PropertyDataDefinition } public PropertyDefinition(PropertyDefinition pd) { - this.setUniqueId(pd.getUniqueId()); - this.setConstraints(pd.getConstraints()); - // this.setSchema(pd.schema); - this.setDefaultValue(pd.getDefaultValue()); - this.setDescription(pd.getDescription()); - this.setName(pd.getName()); - this.setSchema(pd.getSchema()); - this.setParentUniqueId(pd.getParentUniqueId()); - this.setRequired(pd.isRequired()); - this.setType(pd.getType()); + super(pd); + this.setConstraints(pd.getConstraints()); + status = pd.status; + } public List<PropertyConstraint> getConstraints() { @@ -81,17 +132,11 @@ public class PropertyDefinition extends PropertyDataDefinition this.constraints = constraints; } - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } @Override public String toString() { - return super.toString() + " [name=" + name + ", parentUniqueId=" + parentUniqueId + ", constraints=" + return super.toString() + " [name=" + getName() + ", constraints=" + constraints + "]]"; } @@ -112,13 +157,7 @@ public class PropertyDefinition extends PropertyDataDefinition this.status = status; } - public String getParentUniqueId() { - return parentUniqueId; - } - - public void setParentUniqueId(String parentUniqueId) { - this.parentUniqueId = parentUniqueId; - } + @Override public boolean isDefinition() { @@ -126,7 +165,7 @@ public class PropertyDefinition extends PropertyDataDefinition } public void setDefinition(boolean definition) { - this.definition = definition; + super.setDefinition(definition); } @Override @@ -134,8 +173,7 @@ public class PropertyDefinition extends PropertyDataDefinition final int prime = 31; int result = super.hashCode(); result = prime * result + ((constraints == null) ? 0 : constraints.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((parentUniqueId == null) ? 0 : parentUniqueId.hashCode()); + result = prime * result + ((getName() == null) ? 0 : getName().hashCode()); result = prime * result + ((status == null) ? 0 : status.hashCode()); return result; } @@ -154,15 +192,10 @@ public class PropertyDefinition extends PropertyDataDefinition return false; } else if (!constraints.equals(other.constraints)) return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (parentUniqueId == null) { - if (other.parentUniqueId != null) + if (getName() == null) { + if (other.getName() != null) return false; - } else if (!parentUniqueId.equals(other.parentUniqueId)) + } else if (!getName().equals(other.getName())) return false; if (status == null) { if (other.status != null) diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyValueDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyValueDefinition.java index 0c322420b3..0264262ab3 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyValueDefinition.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyValueDefinition.java @@ -27,7 +27,6 @@ public class PropertyValueDefinition extends InputsValueDataDefinition implement public PropertyValueDefinition() { super(); - // TODO Auto-generated constructor stub } public PropertyValueDefinition(String name, String value) { diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementAndRelationshipPair.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementAndRelationshipPair.java index 84ead66658..afb013d29a 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementAndRelationshipPair.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementAndRelationshipPair.java @@ -22,6 +22,8 @@ package org.openecomp.sdc.be.model; import java.io.Serializable; +import org.openecomp.sdc.be.datatypes.elements.RelationshipInstDataDefinition; + public class RequirementAndRelationshipPair implements Serializable { /** @@ -32,6 +34,7 @@ public class RequirementAndRelationshipPair implements Serializable { private String requirement; private String capabilityOwnerId; private String requirementOwnerId; + private String id; private RelationshipImpl relationship; @@ -113,10 +116,42 @@ public class RequirementAndRelationshipPair implements Serializable { this.requirementUid = requirementUid; } + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + @Override public String toString() { return "RequirementAndRelationshipPair [requirement=" + requirement + ", relationship=" + relationship + ", capability=" + capability + "]"; } + public boolean equalsTo( RelationshipInstDataDefinition savedRelation){ + if ( savedRelation == null ){ + return false; + } + if ( !savedRelation.getType().equals(this.getRelationship().getType()) ){ + return false; + } + if ( !savedRelation.getCapabilityOwnerId().equals(this.getCapabilityOwnerId()) ){ + return false; + } + if ( !savedRelation.getRequirementOwnerId().equals(this.getRequirementOwnerId()) ){ + return false; + } + if ( !savedRelation.getRequirementId().equals(this.getRequirementUid()) ){ + return false; + } + if ( !savedRelation.getCapabiltyId().equals(this.getCapabilityUid()) ){ + return false; + } + if ( !savedRelation.getRequirement().equals(this.getRequirement()) ){ + return false; + } + return true; + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementDefinition.java index 3d5741255a..a1a485d4ff 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementDefinition.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/RequirementDefinition.java @@ -22,220 +22,25 @@ package org.openecomp.sdc.be.model; import java.io.Serializable; +import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition; + /** * Specifies the requirements that the Node Type exposes. */ -public class RequirementDefinition implements Serializable { - - /** - * - */ - private static final long serialVersionUID = -8840549489409274532L; - - /** - * Unique id of the requirement - */ - private String uniqueId; - - private String name; - - /** - * specify the capability type - */ - private String capability; - - /** - * specify the node type(Optional by tosca) - */ - private String node; - - /** - * specify the relationship type(Optional by tosca) - */ - private String relationship; +public class RequirementDefinition extends RequirementDataDefinition implements Serializable { - // specifies the resource instance holding this requirement - private String ownerId; - private String ownerName; - - private String minOccurrences; - private String maxOccurrences; - - public RequirementDefinition() { + public RequirementDefinition(){ super(); } - + public RequirementDefinition(RequirementDefinition other) { - this.uniqueId = other.uniqueId; - this.name = other.name; - this.capability = other.capability; - this.node = other.node; - this.relationship = other.relationship; - this.ownerId = other.ownerId; - this.ownerName = other.ownerName; - this.minOccurrences = other.minOccurrences; - this.maxOccurrences = other.maxOccurrences; - - } - - public String getUniqueId() { - return uniqueId; - } - - public void setUniqueId(String uniqueId) { - this.uniqueId = uniqueId; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getCapability() { - return capability; - } - - public void setCapability(String capability) { - this.capability = capability; - } - - public String getNode() { - return node; - } - - public void setNode(String node) { - this.node = node; + super(other); } - - public String getRelationship() { - return relationship; - } - - public void setRelationship(String relationship) { - this.relationship = relationship; - } - - // public RequirementImplDef getRequirementImpl() { - // return requirementImpl; - // } - // - // public void setRequirementImpl(RequirementImplDef requirementImpl) { - // this.requirementImpl = requirementImpl; - // } - - public String getOwnerId() { - return ownerId; - } - - public void setOwnerId(String ownerId) { - this.ownerId = ownerId; - } - - public String getOwnerName() { - return ownerName; - } - - public void setOwnerName(String ownerName) { - this.ownerName = ownerName; - } - - public String getMinOccurrences() { - return minOccurrences; - } - - public void setMinOccurrences(String minOccurrences) { - this.minOccurrences = minOccurrences; - } - - public String getMaxOccurrences() { - return maxOccurrences; - } - - public void setMaxOccurrences(String maxOccurrences) { - this.maxOccurrences = maxOccurrences; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((capability == null) ? 0 : capability.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((node == null) ? 0 : node.hashCode()); - result = prime * result + ((ownerId == null) ? 0 : ownerId.hashCode()); - result = prime * result + ((ownerName == null) ? 0 : ownerName.hashCode()); - result = prime * result + ((relationship == null) ? 0 : relationship.hashCode()); - result = prime * result + ((uniqueId == null) ? 0 : uniqueId.hashCode()); - result = prime * result + ((minOccurrences == null) ? 0 : minOccurrences.hashCode()); - result = prime * result + ((maxOccurrences == null) ? 0 : maxOccurrences.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - RequirementDefinition other = (RequirementDefinition) obj; - if (capability == null) { - if (other.capability != null) - return false; - } else if (!capability.equals(other.capability)) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (node == null) { - if (other.node != null) - return false; - } else if (!node.equals(other.node)) - return false; - if (ownerId == null) { - if (other.ownerId != null) - return false; - } else if (!ownerId.equals(other.ownerId)) - return false; - if (ownerName == null) { - if (other.ownerName != null) - return false; - } else if (!ownerName.equals(other.ownerName)) - return false; - if (relationship == null) { - if (other.relationship != null) - return false; - } else if (!relationship.equals(other.relationship)) - return false; - if (uniqueId == null) { - if (other.uniqueId != null) - return false; - } else if (!uniqueId.equals(other.uniqueId)) - return false; - if (minOccurrences == null) { - if (other.minOccurrences != null) - return false; - } else if (!minOccurrences.equals(other.minOccurrences)) - return false; - if (maxOccurrences == null) { - if (other.maxOccurrences != null) - return false; - } else if (!maxOccurrences.equals(other.maxOccurrences)) - return false; - return true; - } - - @Override - public String toString() { - return "RequirementDefinition [uniqueId=" + uniqueId + ", name=" + name + ", capability=" + capability - + ", node=" + node + ", relationship=" + relationship + ", ownerId=" + ownerId + ", ownerName=" - + ownerName + ", minOccurrences=" + minOccurrences + ", maxOccurrences=" + maxOccurrences + "]"; + + public RequirementDefinition(RequirementDataDefinition requirementDataDefinition) { + super(requirementDataDefinition); } + + private static final long serialVersionUID = -1899506746481882719L; } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Resource.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Resource.java index 6490fb4ef1..5e7983acea 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Resource.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Resource.java @@ -24,6 +24,7 @@ import java.io.Serializable; import java.util.List; import java.util.Map; +import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; @@ -33,15 +34,16 @@ public class Resource extends Component implements Serializable { * */ private static final long serialVersionUID = -6811540567661368482L; + public static final String ROOT_RESOURCE = "tosca.nodes.Root"; public Resource() { super(new ResourceMetadataDefinition()); - componentType = ComponentTypeEnum.RESOURCE; + this.getComponentMetadataDefinition().getMetadataDataDefinition().setComponentType(ComponentTypeEnum.RESOURCE); } public Resource(ComponentMetadataDefinition componentMetadataDefinition) { super(componentMetadataDefinition); - componentType = ComponentTypeEnum.RESOURCE; + this.getComponentMetadataDefinition().getMetadataDataDefinition().setComponentType(ComponentTypeEnum.RESOURCE); } private List<String> derivedFrom; @@ -57,7 +59,7 @@ public class Resource extends Component implements Serializable { private List<String> defaultCapabilities; - private List<AdditionalInformationDefinition> additionalInformation; +// private List<AdditionalInformationDefinition> additionalInformation; /** * Please note that more than one "derivedFrom" resource is not currently @@ -150,13 +152,6 @@ public class Resource extends Component implements Serializable { .setLicenseType(licenseType); } - public List<AdditionalInformationDefinition> getAdditionalInformation() { - return additionalInformation; - } - - public void setAdditionalInformation(List<AdditionalInformationDefinition> additionalInformation) { - this.additionalInformation = additionalInformation; - } @Override public int hashCode() { @@ -270,4 +265,29 @@ public class Resource extends Component implements Serializable { return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()) .getVendorRelease(); } + + @Override + public String fetchGenericTypeToscaNameFromConfig(){ + String result = super.fetchGenericTypeToscaNameFromConfig(); + if(null == result) + result = ConfigurationManager.getConfigurationManager().getConfiguration().getGenericAssetNodeTypes().get(ResourceTypeEnum.VFC.getValue()); + return result; + } + + @Override + public String assetType(){ + return this.getResourceType().name(); + } + + @Override + public boolean shouldGenerateInputs(){ + //TODO add complex VFC condition when supported + return ResourceTypeEnum.VF == this.getResourceType(); + } + + @Override + public boolean deriveFromGeneric(){ + return this.shouldGenerateInputs() || (derivedFrom != null && derivedFrom.contains(fetchGenericTypeToscaNameFromConfig())); + } + } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Service.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Service.java index e47333457f..37a42bd581 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Service.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Service.java @@ -20,26 +20,29 @@ package org.openecomp.sdc.be.model; -import java.util.List; import java.util.Map; - import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; public class Service extends Component { + + private static final long serialVersionUID = -8819935942700578059L; + public Service() { super(new ServiceMetadataDefinition()); - componentType = ComponentTypeEnum.SERVICE; + this.getComponentMetadataDefinition().getMetadataDataDefinition().setComponentType(ComponentTypeEnum.SERVICE); + this.setToscaType(ToscaElementTypeEnum.TopologyTemplate.getValue()); } public Service(ComponentMetadataDefinition serviceMetadataDefinition) { super(serviceMetadataDefinition); - componentType = ComponentTypeEnum.SERVICE; + this.getComponentMetadataDefinition().getMetadataDataDefinition().setComponentType(ComponentTypeEnum.SERVICE); + this.setToscaType(ToscaElementTypeEnum.TopologyTemplate.getValue()); } private Map<String, ArtifactDefinition> serviceApiArtifacts; - private List<AdditionalInformationDefinition> additionalInformation; public Map<String, ArtifactDefinition> getServiceApiArtifacts() { return serviceApiArtifacts; @@ -71,18 +74,27 @@ public class Service extends Component { getServiceMetadataDefinition().setDistributionStatus(distributionStatus.name()); } - private ServiceMetadataDataDefinition getServiceMetadataDefinition() { - return (ServiceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition(); + public void setEcompGeneratedNaming(Boolean ecompGeneratedNaming) { + getServiceMetadataDefinition().setEcompGeneratedNaming(ecompGeneratedNaming); + } + + public Boolean isEcompGeneratedNaming() { + return getServiceMetadataDefinition().isEcompGeneratedNaming(); + } + + public void setNamingPolicy(String namingPolicy) { + getServiceMetadataDefinition().setNamingPolicy(namingPolicy); } - public List<AdditionalInformationDefinition> getAdditionalInformation() { - return additionalInformation; + public String getNamingPolicy() { + return getServiceMetadataDefinition().getNamingPolicy(); } - public void setAdditionalInformation(List<AdditionalInformationDefinition> additionalInformation) { - this.additionalInformation = additionalInformation; + private ServiceMetadataDataDefinition getServiceMetadataDefinition() { + return (ServiceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition(); } + @Override public String toString() { return "Service [componentMetadataDefinition=" + getComponentMetadataDefinition() diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/TargetCapabilityRelDef.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/TargetCapabilityRelDef.java index 2e92ca5df3..f30ef353b1 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/TargetCapabilityRelDef.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/TargetCapabilityRelDef.java @@ -30,6 +30,7 @@ public class TargetCapabilityRelDef implements Serializable { */ private static final long serialVersionUID = -7571489368200736413L; + private String uid; private String toNode; // private List<ImmutablePair<String, RelationshipImpl>> relationships; @@ -66,6 +67,14 @@ public class TargetCapabilityRelDef implements Serializable { return relationships; } + public String getUid() { + return uid; + } + + public void setUid(String uid) { + this.uid = uid; + } + public void setRelationships(List<RequirementAndRelationshipPair> relationships) { this.relationships = relationships; } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadPropInfo.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadPropInfo.java index 60a58c9aed..5640f5582c 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadPropInfo.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/UploadPropInfo.java @@ -23,6 +23,9 @@ package org.openecomp.sdc.be.model; import java.util.List; import java.util.Map; +import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; + + public class UploadPropInfo extends UploadInfo { private Object value; @@ -31,13 +34,13 @@ public class UploadPropInfo extends UploadInfo { private boolean password; - private List<GetInputValueInfo> get_input; + private List<GetInputValueDataDefinition> get_input; - public List<GetInputValueInfo> getGet_input() { + public List<GetInputValueDataDefinition> getGet_input() { return get_input; } - public void setGet_input(List<GetInputValueInfo> get_input) { + public void setGet_input(List<GetInputValueDataDefinition> get_input) { this.get_input = get_input; } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ApplicationDataTypeCache.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ApplicationDataTypeCache.java index 31664c929b..4c8d239704 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ApplicationDataTypeCache.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ApplicationDataTypeCache.java @@ -25,7 +25,6 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; -import java.util.TreeMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; @@ -41,10 +40,10 @@ import javax.annotation.Resource; import org.apache.commons.lang3.concurrent.BasicThreadFactory; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.config.BeEcompErrorManager; -import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; import org.openecomp.sdc.be.config.Configuration.ApplicationL1CacheConfig; import org.openecomp.sdc.be.config.Configuration.ApplicationL1CacheInfo; +import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; @@ -93,7 +92,7 @@ public class ApplicationDataTypeCache implements ApplicationCache<DataTypeDefini if (firstRunDelay != null) { firstRunDelayInSec = firstRunDelay; } - log.trace("ApplicationDataTypesCache polling interval is " + pollingIntervalInSec + " seconds."); + log.trace("ApplicationDataTypesCache polling interval is {} seconds.", pollingIntervalInSec); if (scheduledPollingService != null) { log.debug("Start ApplicationDataTypeCache polling task. polling interval {} seconds", pollingIntervalInSec); @@ -210,7 +209,7 @@ public class ApplicationDataTypeCache implements ApplicationCache<DataTypeDefini log.trace("Start fetching all data types from db"); Either<List<DataTypeData>, TitanOperationStatus> allDataTypeNodes = propertyOperation.getAllDataTypeNodes(); Long end = System.currentTimeMillis(); - log.trace("Finish fetching all data types from db. Took " + (end - start) + " Milliseconds"); + log.trace("Finish fetching all data types from db. Took {} Milliseconds", (end - start)); if (allDataTypeNodes.isRight()) { TitanOperationStatus status = allDataTypeNodes.right().value(); if (status != TitanOperationStatus.OK) { diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ComponentCache.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ComponentCache.java index 6732adbdb1..cb85deeb2d 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ComponentCache.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/ComponentCache.java @@ -56,6 +56,7 @@ import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.Product; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.*; import org.openecomp.sdc.be.resources.data.ComponentCacheData; @@ -63,6 +64,7 @@ import org.openecomp.sdc.common.util.SerializationUtils; import org.openecomp.sdc.common.util.ZipUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; import fj.data.Either; @@ -73,15 +75,9 @@ public class ComponentCache { @javax.annotation.Resource ComponentCassandraDao componentCassandraDao; - - @javax.annotation.Resource - ResourceOperation resourceOperation; - - @javax.annotation.Resource - ServiceOperation serviceOperation; - - @javax.annotation.Resource - ProductOperation productOperation; + + @Autowired + ToscaOperationFacade toscaOperationFacade; private Map<ComponentTypeEnum, Map<String, Component>> catalogInMemoryCache = new HashMap<>(); private final ReentrantReadWriteLock rwCatalogLock = new ReentrantReadWriteLock(); @@ -626,13 +622,7 @@ public class ComponentCache { return false; } - ComponentOperation componentOperation = getComponentOperation(nodeTypeEnum); - - if (componentOperation == null) { - return false; - } - - Either<Component, StorageOperationStatus> either = componentOperation.getComponent(componentUid, false); + Either<Component, StorageOperationStatus> either = toscaOperationFacade.getToscaElement(componentUid); if (either.isLeft()) { Component component = either.left().value(); result = saveComponent(componentUid, lastModificationTime, nodeTypeEnum, component); @@ -675,8 +665,7 @@ public class ComponentCache { logger.debug("Failed to prepare component {} of type {} for cache", componentUid, nodeTypeEnum.name().toLowerCase()); if (logger.isTraceEnabled()) { - logger.trace("Failed to prepare component " + componentUid + " of type " - + nodeTypeEnum.name().toLowerCase() + " for cache"); + logger.trace("Failed to prepare component {} of type {} for cache",componentUid,nodeTypeEnum.name().toLowerCase()); } } } else { @@ -704,24 +693,6 @@ public class ComponentCache { } - private ComponentOperation getComponentOperation(NodeTypeEnum nodeTypeEnum) { - ComponentOperation componentOperation = null; - switch (nodeTypeEnum) { - case Resource: - componentOperation = resourceOperation; - break; - case Service: - componentOperation = serviceOperation; - break; - case Product: - componentOperation = productOperation; - break; - default: - break; - } - return componentOperation; - } - /** * get components from cache of a given list ou unique ids. * diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/DaoInfo.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/DaoInfo.java index bc63b34fec..c7bcc54d3d 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/DaoInfo.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/DaoInfo.java @@ -20,34 +20,19 @@ package org.openecomp.sdc.be.model.cache; -import org.openecomp.sdc.be.model.operations.api.IProductOperation; -import org.openecomp.sdc.be.model.operations.api.IResourceOperation; -import org.openecomp.sdc.be.model.operations.api.IServiceOperation; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; public class DaoInfo { - private IResourceOperation iResourceOperation; - private IServiceOperation iServiceOperation; - private IProductOperation iProductOperation; + private ToscaOperationFacade toscaOperationFacade; private ComponentCache ComponentCache; - public DaoInfo(IResourceOperation iResourceOperation, IServiceOperation iServiceOperation, - IProductOperation iProductOperation, org.openecomp.sdc.be.model.cache.ComponentCache componentCache) { - this.iResourceOperation = iResourceOperation; - this.iServiceOperation = iServiceOperation; - this.iProductOperation = iProductOperation; + public DaoInfo(ToscaOperationFacade toscaOperationFacade, org.openecomp.sdc.be.model.cache.ComponentCache componentCache) { + this.toscaOperationFacade = toscaOperationFacade; ComponentCache = componentCache; } - public IResourceOperation getResourceOperation() { - return iResourceOperation; - } - - public IServiceOperation getServiceOperation() { - return iServiceOperation; - } - - public IProductOperation getProductOperation() { - return iProductOperation; + public ToscaOperationFacade getToscaOperationFacade() { + return toscaOperationFacade; } public org.openecomp.sdc.be.model.cache.ComponentCache getComponentCache() { diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/CheckAndUpdateJob.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/CheckAndUpdateJob.java index 93249c914a..dfc39042bd 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/CheckAndUpdateJob.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/CheckAndUpdateJob.java @@ -80,7 +80,7 @@ public class CheckAndUpdateJob extends Job { } catch (Exception e) { log.debug("an exception was encountered during CheckAndUpdateJob", e); } finally { - daoInfo.getResourceOperation().getTitanGenericDao().commit(); + daoInfo.getToscaOperationFacade().commit(); } return false; } @@ -109,8 +109,7 @@ public class CheckAndUpdateJob extends Job { } else { // update cache // get component from grath - Either<Component, StorageOperationStatus> componentRes = getOperationByType(nodeTypeEnum) - .getComponent(componentId, true); + Either<Component, StorageOperationStatus> componentRes = daoInfo.getToscaOperationFacade().getToscaElement(componentId); if (componentRes.isRight()) { log.debug("failed to get full component:{} from graph status:{}", componentId, componentRes.right().value()); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/Job.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/Job.java index 4deda8642f..c1fb2e0a7f 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/Job.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/Job.java @@ -55,28 +55,9 @@ public abstract class Job<E> { public abstract E doWork(); - protected IComponentOperation getOperationByType(NodeTypeEnum nodeTypeEnum) { - IComponentOperation operation = null; - switch (nodeTypeEnum) { - case Product: - operation = daoInfo.getProductOperation(); - break; - case Service: - operation = daoInfo.getServiceOperation(); - break; - case Resource: - operation = daoInfo.getResourceOperation(); - break; - default: - log.error("unexpected NodeType received no matching operation found."); - } - return operation; - } - protected Either<ComponentMetadataData, StorageOperationStatus> getComponentMetaData(String componentId, NodeTypeEnum nodeTypeEnum) { - Either<ComponentMetadataData, StorageOperationStatus> metaDataRes = getOperationByType(nodeTypeEnum) - .getComponentByLabelAndId(componentId, nodeTypeEnum, ComponentMetadataData.class); + Either<ComponentMetadataData, StorageOperationStatus> metaDataRes = daoInfo.getToscaOperationFacade().getComponentMetadata(componentId); if (metaDataRes.isRight()) { // in case we cant find the component on graph exit if (StorageOperationStatus.NOT_FOUND.equals(metaDataRes.right().value())) { diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/OverrideJob.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/OverrideJob.java index e9da68ea59..47edae8968 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/OverrideJob.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/OverrideJob.java @@ -47,8 +47,7 @@ public class OverrideJob extends Job { log.trace("override component in cache, componentId:{} of nodeTypeEnum:{} with timestamp:{}.", componentId, nodeTypeEnum, timestamp); // get component from grath - Either<Component, StorageOperationStatus> componentRes = getOperationByType(nodeTypeEnum) - .getComponent(componentId, false); + Either<Component, StorageOperationStatus> componentRes = daoInfo.getToscaOperationFacade().getToscaElement(componentId); if (componentRes.isRight()) { log.debug("failed to get full component:{} from graph status:{}", componentId, componentRes.right().value()); @@ -66,7 +65,7 @@ public class OverrideJob extends Job { } catch (Exception e) { log.debug("an exception was encountered during OverrideJob", e); } finally { - this.daoInfo.getResourceOperation().getTitanGenericDao().commit(); + this.daoInfo.getToscaOperationFacade().commit(); } return false; diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/StoreJob.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/StoreJob.java index 410a56a90e..c282e5dca5 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/StoreJob.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/cache/jobs/StoreJob.java @@ -42,14 +42,12 @@ public class StoreJob extends Job { public Object doWork() { try { log.trace("starting work on job."); - log.trace("store component in cache, componentId:{} of nodeTypeEnum:{} with timestamp:{}.", componentId, - nodeTypeEnum, timestamp); + log.trace("store component in cache, componentId:{} of nodeTypeEnum:{} with timestamp:{}.", componentId, nodeTypeEnum, timestamp); if (!this.daoInfo.getComponentCache().setComponent(component, nodeTypeEnum)) { log.debug("failed to store componentId:{} nodeTypeEnum:", componentId, nodeTypeEnum); return false; } - log.debug("cache successfully updated for componentId:{} nodeTypeEnum:{} timestemp:{}.", componentId, - nodeTypeEnum, timestamp); + log.debug("cache successfully updated for componentId:{} nodeTypeEnum:{} timestemp:{}.", componentId, nodeTypeEnum, timestamp); return true; } catch (Exception e) { diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/heat/HeatParameterType.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/heat/HeatParameterType.java index 7de0aa561d..5fbeb4f808 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/heat/HeatParameterType.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/heat/HeatParameterType.java @@ -44,7 +44,8 @@ public enum HeatParameterType { JSON("json", HeatStringValidator.getInstance(), HeatJsonConverter.getInstance()), - COMMA_DELIMITED_LIST("comma_delimited_list", HeatCommaDelimitedListValidator.getInstance(), HeatCommaDelimitedListConverter.getInstance()); + COMMA_DELIMITED_LIST("comma_delimited_list", HeatCommaDelimitedListValidator.getInstance(), + HeatCommaDelimitedListConverter.getInstance()); private String type; private PropertyTypeValidator validator; 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 new file mode 100644 index 0000000000..7c6c207f74 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/NodeType.java @@ -0,0 +1,88 @@ +package org.openecomp.sdc.be.model.jsontitan.datamodel; + +import java.util.List; +import java.util.Map; + +import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition; +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; + +public class NodeType extends ToscaElement{ + + public NodeType() { + super(ToscaElementTypeEnum.NodeType); + } + + private List<String> derivedFrom; + private List<String> derivedList; + + private Map<String, AttributeDataDefinition> 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, AttributeDataDefinition> getAttributes() { + return attributes; + } + + public void setAttributes(Map<String, AttributeDataDefinition> 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 new file mode 100644 index 0000000000..74c4c30aa5 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/TopologyTemplate.java @@ -0,0 +1,199 @@ +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.GroupDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapAttributesDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapCapabiltyProperty; +import org.openecomp.sdc.be.datatypes.elements.MapGroupsDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapListCapabiltyDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapListRequirementDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.RelationshipInstDataDefinition; +import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; +import org.openecomp.sdc.be.model.jsontitan.enums.JsonConstantKeysEnum; + +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, MapAttributesDataDefinition> instAttributes; + private Map<String, MapPropertiesDataDefinition> instProperties; + private Map<String, GroupDataDefinition> groups; + private Map<String, MapGroupsDataDefinition> instGroups; + private Map<String, ArtifactDataDefinition> serviceApiArtifacts; + private Map<String, CompositionDataDefinition> compositions; + + 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; + + + 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, MapAttributesDataDefinition> getInstAttributes() { + return instAttributes; + } + public void setInstAttributes(Map<String, MapAttributesDataDefinition> 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, 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; + } + /** + * 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 inctances 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; + } +} 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 new file mode 100644 index 0000000000..72cf89f13c --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/ToscaElement.java @@ -0,0 +1,277 @@ +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; +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.LifecycleStateEnum; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.jsontitan.operations.NodeTypeOperation; +import org.slf4j.MDC; + +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()); + } + } + +} 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 new file mode 100644 index 0000000000..7a8f76e511 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/datamodel/ToscaElementTypeEnum.java @@ -0,0 +1,29 @@ +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; + } + } + + 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 new file mode 100644 index 0000000000..12ff27fa70 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/enums/JsonConstantKeysEnum.java @@ -0,0 +1,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; + } +} 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 new file mode 100644 index 0000000000..55853479d2 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ArtifactsOperations.java @@ -0,0 +1,623 @@ +package org.openecomp.sdc.be.model.jsontitan.operations; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.stream.Collectors; + +import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang3.tuple.ImmutableTriple; +import org.apache.commons.lang3.tuple.Triple; +import org.apache.tinkerpop.gremlin.structure.Direction; +import org.openecomp.sdc.be.config.BeEcompErrorManager; +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.ArtifactDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.HeatParameterDefinition; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; +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.slf4j.MDC; + +import fj.data.Either; + +@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) { + + Either<ArtifactDataDefinition, StorageOperationStatus> status = updateArtifactOnGraph(parentId, artifactInfo, type, artifactInfo.getUniqueId(), instanceId); + 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> updateArifactOnResource(ArtifactDefinition artifactInfo, String id, String artifactId, NodeTypeEnum type, String instanceId) { + + Either<ArtifactDataDefinition, StorageOperationStatus> status = updateArtifactOnGraph(id, artifactInfo, type, artifactId, instanceId); + 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) { + result = Either.right(StorageOperationStatus.NOT_FOUND); + return result; + } + + ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(null, foundArtifact); + return Either.left(artifactDefResult); + + } + + 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); + } + + 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) { + if (oldVesrion == null || oldVesrion.isEmpty()) + oldVesrion = "0"; + + String currentChecksum = artifactData.getArtifactChecksum(); + 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().equals(artifactId)).collect(Collectors.toList()); + if (envList != null && !envList.isEmpty()) { + envList.forEach(a -> { + a.setGeneratedFromId(newArtifactId); + updateArifactOnResource(a, id, a.getUniqueId(), type, instanceId); + + }); + + } + return Either.left(artifactEnvInfo); + } + + public Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvPlaceholder(ArtifactDefinition artifactInfo, String parentId, NodeTypeEnum type) { + return updateArifactOnResource(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) { + + Map<String, ArtifactDefinition> artMap = null; + Map<String, ArtifactDataDefinition> artifactDataMap = null; + + if (edgeLabelEnum != EdgeLabelEnum.INSTANCE_ARTIFACTS) { + Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> resultEither = getDataFromGraph(parentId, edgeLabelEnum); + if (resultEither.isRight()) { + log.debug("failed to fetch {} for tosca element with id {}, error {}", edgeLabelEnum, parentId, resultEither.right().value()); + return Either.right(resultEither.right().value()); + } + artifactDataMap = resultEither.left().value(); + }else{ + Either<Map<String, MapArtifactDataDefinition>, TitanOperationStatus> resultEither = getDataFromGraph(parentId, edgeLabelEnum); + if (resultEither.isRight()) { + log.debug("failed to fetch {} for tosca element with id {}, error {}", edgeLabelEnum, parentId, resultEither.right().value()); + return Either.right(resultEither.right().value()); + } + Map<String, MapArtifactDataDefinition> mapArtifacts = resultEither.left().value(); + MapArtifactDataDefinition artifactPerInstance = mapArtifacts.get(instanceId); + if ( artifactPerInstance != null ){ + artifactDataMap = artifactPerInstance.getMapToscaDataDefinition(); + } + } + if (artifactDataMap != null && !artifactDataMap.isEmpty()) { + artMap = artifactDataMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> convertArtifactDataToArtifactDefinition(null, e.getValue()))); + }else{ + artMap = new HashMap<>(); + } + return Either.left(artMap); + + } + + 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) { + 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.buildPropertyUniqueId(instanceId, artifactToUpdate.getArtifactLabel()); + } + artifactToUpdate.setUniqueId(uniqueId); + + } else + artifactToUpdate.setUniqueId(artifactId); + + Map<String, ArtifactDataDefinition> artifacts = 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.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE)); + } + } + } else { + Either<Map<String, MapArtifactDataDefinition>, TitanOperationStatus> artifactsEither = this.getDataFromGraph(componentId, edgeLabelEnum); + if (artifactsEither.isLeft()) { + Map<String, MapArtifactDataDefinition> artifactInst = artifactsEither.left().value(); + if (isNeedToClone) { + 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(); + if (isNeedToClone) + artifactToUpdate.setDuplicated(Boolean.FALSE); + else { + if (artifactToUpdate.getDuplicated()) { + String id = type != NodeTypeEnum.ResourceInstance ? componentId : instanceId; + String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(id, artifactToUpdate.getArtifactLabel()); + artifactToUpdate.setUniqueId(uniqueId); + artifactToUpdate.setDuplicated(Boolean.TRUE); + } + } + } + updateUUID(artifactToUpdate, oldChecksum, oldVersion); + + 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; + if (edgeLabelEnum != EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS && edgeLabelEnum != EdgeLabelEnum.INSTANCE_ARTIFACTS) { + status = updateToscaDataOfToscaElement(componentId, edgeLabelEnum, vertexTypeEnum, artifactToUpdate, JsonPresentationFields.ARTIFACT_LABEL); + } else { + List<String> pathKeys = new ArrayList<>(); + pathKeys.add(instanceId); + List<ArtifactDataDefinition> toscaDataList = new ArrayList<>(); + toscaDataList.add(artifactToUpdate); + 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)); + } + + private boolean validateParentType(NodeTypeEnum type) { + boolean isValid = false; + switch (type) { + case Resource: + case InterfaceOperation: + case Service: + case ResourceInstance: + isValid = true; + break; + default: + log.debug("Not supported node type for artifact relation : {} ", type); + } + return isValid; + } + + 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; + } +} 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 new file mode 100644 index 0000000000..629d9ecdd4 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/BaseOperation.java @@ -0,0 +1,1316 @@ +package org.openecomp.sdc.be.model.jsontitan.operations; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +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.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.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.MapDataDefinition; +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.User; +import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; +import org.openecomp.sdc.common.jsongraph.util.CommonUtility; +import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; +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; + +/** + * public abstract class BaseOperation provides base operation functionality and common fields + * + */ +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; + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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 null; + } + + @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 vertexLabel + * @param uniqueKeys + * @param mapKeyField + * @return + */ + public StorageOperationStatus deleteToscaDataElements(String toscaElementUid, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<String> uniqueKeys, 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 = deleteToscaDataElements(getToscaElementRes.left().value(), edgeLabel, vertexLabel, uniqueKeys, mapKeyField); + } + 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 = (Map<String, ToscaDataDefinition>) getDeepElements(toscaDataVertexRes.left().value(), pathKeys); + for (String uniqueKey : uniqueKeys) { + result = removeToscaDataElement(toscaElement, edgeLabel, uniqueKey, toscaDataVertex, existingToscaDataMap); + if (result != StorageOperationStatus.OK) { + break; + } + } + } + if (result == null) { + result = StorageOperationStatus.OK; + } + 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, vertexLabel, uniqueKeys, mapKeyField); + } + + @SuppressWarnings("unchecked") + /** + * Deletes tosca data elements belonging to tosca element according label + * + * @param toscaElement + * @param edgeLabel + * @param vertexLabel + * @param uniqueKeys + * @param mapKeyField + * @return + */ + public StorageOperationStatus deleteToscaDataElements(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, List<String> uniqueKeys, JsonPresentationFields mapKeyField) { + + 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 = (Map<String, ToscaDataDefinition>) toscaDataVertex.getJson(); + for (String uniqueKey : uniqueKeys) { + result = removeToscaDataElement(toscaElement, edgeLabel, uniqueKey, toscaDataVertex, existingToscaDataMap); + if (result != StorageOperationStatus.OK) { + break; + } + } + } + if (result == null) { + result = StorageOperationStatus.OK; + } + return result; + } + + private <T extends ToscaDataDefinition> StorageOperationStatus removeToscaDataElement(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, String uniqueKey, GraphVertex toscaDataVertex, Map<String, T> existingToscaDataMap) { + + StorageOperationStatus result = StorageOperationStatus.OK; + if (!existingToscaDataMap.containsKey(uniqueKey)) { + result = StorageOperationStatus.NOT_FOUND; + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete tosca data element of the tosca element {} by label {}. Status is {}. ", toscaElement.getUniqueId(), edgeLabel, result); + } else { + existingToscaDataMap.remove(uniqueKey); + 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 <K extends ToscaDataDefinition> StorageOperationStatus handleToscaData(GraphVertex toscaElement, VertexTypeEnum vertexLabel, EdgeLabelEnum edgeLabel, GraphVertex toscaDataVertex, Map<String, K> mergedToscaDataMap) { + + StorageOperationStatus result = null; + 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; +// } + +} 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 new file mode 100644 index 0000000000..8fe70f02b1 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ByToscaNameDerivedNodeTypeResolver.java @@ -0,0 +1,35 @@ +package org.openecomp.sdc.be.model.jsontitan.operations; + +import fj.data.Either; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +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.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.model.DerivedNodeTypeResolver; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Component("derived-resource-resolver") +public class ByToscaNameDerivedNodeTypeResolver implements DerivedNodeTypeResolver { + + @Autowired + private TitanDao titanDao; + + @Override + public Either<List<GraphVertex>, TitanOperationStatus> findDerivedResources(String parentResource) { + Map<GraphPropertyEnum, Object> propertiesToMatch = new HashMap<GraphPropertyEnum, Object>(); + propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + + propertiesToMatch.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, parentResource); + propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + + return titanDao.getByCriteria(VertexTypeEnum.NODE_TYPE, propertiesToMatch, JsonParseFlagEnum.NoParse); + } +} 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 new file mode 100644 index 0000000000..898dec03a8 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/CategoryOperation.java @@ -0,0 +1,73 @@ +package org.openecomp.sdc.be.model.jsontitan.operations; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +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.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.util.ValidationUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import fj.data.Either; + +@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); + + 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/GroupsOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/GroupsOperation.java new file mode 100644 index 0000000000..97a5e11a13 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/GroupsOperation.java @@ -0,0 +1,309 @@ +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 org.apache.tinkerpop.shaded.minlog.Log; +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.MapPropertiesDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.GroupInstance; +import org.openecomp.sdc.be.model.GroupInstanceProperty; +import org.openecomp.sdc.be.model.GroupProperty; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; +import org.openecomp.sdc.be.model.operations.impl.LifecycleOperation; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.be.resources.data.GroupData; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.jsongraph.util.CommonUtility; +import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.carrotsearch.junitbenchmarks.annotation.LabelType; +import com.thinkaurelius.titan.diskstorage.Entry; + +import fj.data.Either; +import javassist.expr.NewArray; + +@org.springframework.stereotype.Component("groups-operation") +public class GroupsOperation extends BaseOperation { + + private static Logger logger = LoggerFactory.getLogger(GroupsOperation.class.getName()); + + public Either<List<GroupDefinition>, StorageOperationStatus> createGroups(Component component, User user, ComponentTypeEnum componentType, Map<String, 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 = topologyTemplateOperation.associateGroupsToComponent(getComponentVertex.left().value(), groups); + if (status != StorageOperationStatus.OK) { + result = Either.right(status); + } + } + /* if (result == null) { + status = topologyTemplateOperation.associateGroupsPropertiesToComponent(getComponentVertex.left().value(), groupsProperties); + if (status != StorageOperationStatus.OK) { + result = Either.right(status); + } + }*/ + if (result == null) { + result = Either.left(ModelConverter.convertToGroupDefinitions(groups)); + } + return result; + } + + public Either<List<GroupDefinition>, StorageOperationStatus> addGroups(Component component, User user, ComponentTypeEnum componentType, List<GroupDataDefinition> groups) { + // TODO Auto-generated method stub + 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); + } + } + + 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; + } + + public Either<List<GroupDefinition>, StorageOperationStatus> deleteGroups(Component component, User user, ComponentTypeEnum componentType, List<GroupDataDefinition> groups) { + // TODO Auto-generated method stub + 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, VertexTypeEnum.GROUPS, groupName, 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; + } + + public Either<List<GroupDefinition>, StorageOperationStatus> updateGroups(Component component, ComponentTypeEnum componentType, List<GroupDataDefinition> groups) { + // TODO Auto-generated method stub + 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; + } + + + 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; + StorageOperationStatus status = null; + + if (result == null) { + getComponentVertex = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata); + if (getComponentVertex.isRight()) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch component {}. Status is {} ", componentId); + 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 ){ + logger.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(logger, 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(LifecycleOperation.VERSION_DELIMETER_REGEXP); + Integer majorVersion = Integer.parseInt(versionParts[0]); + + majorVersion++; + + return String.valueOf(majorVersion); + + } + + public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstances(Component component, ComponentTypeEnum componentType, 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(logger, 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(logger, 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(logger, 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(logger, 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) { + logger.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/InstancesOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/InstancesOperation.java new file mode 100644 index 0000000000..b5154a7a0f --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/InstancesOperation.java @@ -0,0 +1,5 @@ +package org.openecomp.sdc.be.model.jsontitan.operations; + +public class InstancesOperation extends BaseOperation { + +} 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 new file mode 100644 index 0000000000..a20f85ad7b --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTemplateOperation.java @@ -0,0 +1,1740 @@ +package org.openecomp.sdc.be.model.jsontitan.operations; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; + +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.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.CompositionDataDefinition; +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.MapAttributesDataDefinition; +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.RelationshipInstDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstanceInput; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.DistributionStatusEnum; +import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.GroupInstance; +import org.openecomp.sdc.be.model.RelationshipImpl; +import org.openecomp.sdc.be.model.RequirementAndRelationshipPair; +import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +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; +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.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.common.api.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.util.ValidationUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import fj.data.Either; + +@org.springframework.stereotype.Component("node-template-operation") +public class NodeTemplateOperation extends BaseOperation { + 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 (result == null) { + result = Either.left(new ImmutablePair<>(addComponentInstanceRes.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())) { + 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) { + + 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); + 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 (relations != null) { + 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 (capResult.isRight()) { + return 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 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); + updateCalculatedCapabiltyAfterDeleteRelation(calculatedCapabilty, fullFilledCapabilty, relationToDelete.getToId(), relationToDelete); + } + if (relationToDelete.getToId().equals(ciToRemove)) { + updateCalculatedRequirementsAfterDeleteRelation(calculatedRequirement, fullfilledRequirement, relationToDelete.getFromId(), relationToDelete); + updateCalculatedCapabiltyAfterDeleteRelation(calculatedCapabilty, fullFilledCapabilty, ciToRemove, relationToDelete); + } + } + } + } + } + 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_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 fullfilled requirement 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 fullfilled requirement 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 artifacts for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status); + return status; + } + return StorageOperationStatus.OK; + } + + private 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; + } + + MapAttributesDataDefinition instAttributes = new MapAttributesDataDefinition(originNodeType.getAttributes()); + + status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.INST_ATTRIBUTES, VertexTypeEnum.INST_ATTRIBUTES, instAttributes, componentInstance.getUniqueId()); + + if (status != StorageOperationStatus.OK) { + return status; + } + status = addInstanceDeploymentArtifacts(originNodeType, componentInstance, updatedContainerVertex, user, envType); + if (status != StorageOperationStatus.OK) { + return status; + } + return addCalculatedCapReqFromNodeType(originNodeType, componentInstance, updatedContainerVertex); + + } + + private StorageOperationStatus addInstanceDeploymentArtifacts(ToscaElement originNodeType, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex, User user, String envType) { + Map<String, ArtifactDataDefinition> deploymentArtifacts = originNodeType.getDeploymentArtifacts(); + MapArtifactDataDefinition instArtifacts = prepareInstDeploymentArtifactPerInstance(deploymentArtifacts, componentInstance.getUniqueId(), user, envType); + if (instArtifacts != null) { + StorageOperationStatus calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, instArtifacts, + componentInstance.getUniqueId()); + + if (calculatedResult != StorageOperationStatus.OK) { + return calculatedResult; + } + } + return StorageOperationStatus.OK; + } + + 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()))) { + instDeploymentArtifacts.put(e.getKey(), artifact); + ArtifactDataDefinition artifactEnv = createArtifactPlaceHolderInfo(artifact, componentInstanceId, user, envType); + instDeploymentArtifacts.put(artifactEnv.getArtifactLabel(), artifactEnv); + } + }); + + MapArtifactDataDefinition instArtifacts = new MapArtifactDataDefinition(instDeploymentArtifacts); + 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(); + } + + 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(); + 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; + } + + public MapListRequirementDataDefinition prepareCalculatedRequirementForNodeType(Map<String, ListRequirementDataDefinition> requirements, ComponentInstanceDataDefinition componentInstance) { + if (requirements != null) { + MapListRequirementDataDefinition allCalculatedReq = new MapListRequirementDataDefinition(); + + requirements.entrySet().forEach(e -> { + List<RequirementDataDefinition> listCapabilities = e.getValue().getListToscaDataDefinition(); + listCapabilities.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, ComponentInstance 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(groupOptional.get(), componentInstance); + 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 GroupInstanceDataDefinition buildGroupInstanceDataDefinition(GroupDefinition group, ComponentInstance componentInstance) { + + String componentInstanceName = componentInstance.getName(); + Long creationDate = System.currentTimeMillis(); + GroupInstanceDataDefinition groupInstance = new GroupInstanceDataDefinition(); + String groupUid = group.getUniqueId(); + + groupInstance.setGroupUid(groupUid); + groupInstance.setType(group.getType()); + groupInstance.setCustomizationUUID(generateCustomizationUUID()); + groupInstance.setCreationTime(creationDate); + groupInstance.setModificationTime(creationDate); + groupInstance.setName(buildGroupInstanceName(componentInstanceName, group.getName())); + groupInstance.setGroupName(groupInstance.getName()); + groupInstance.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(groupInstance.getName())); + groupInstance.setUniqueId(UniqueIdBuilder.buildResourceInstanceUniuqeId(componentInstance.getUniqueId(), groupUid, groupInstance.getNormalizedName())); + groupInstance.setArtifacts(group.getArtifacts()); + groupInstance.setArtifactsUuid(group.getArtifactsUuid()); + groupInstance.setProperties(group.getProperties()); + groupInstance.setInvariantUUID(group.getInvariantUUID()); + groupInstance.setGroupUUID(group.getGroupUUID()); + groupInstance.setVersion(group.getVersion()); + + return groupInstance; + } + + 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(); + if (creationDate == null) { + creationDate = System.currentTimeMillis(); + } + dataDefinition.setComponentUid(ciOriginComponentUid); + dataDefinition.setCreationTime(creationDate); + dataDefinition.setModificationTime(creationDate); + 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 (StringUtils.isEmpty(dataDefinition.getToscaComponentName()) && originToscaElement != null) + dataDefinition.setToscaComponentName((String) originToscaElement.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME)); + if (dataDefinition.getOriginType() == null && originToscaElement != null) { + ResourceTypeEnum resourceType = originToscaElement.getResourceType(); + OriginTypeEnum originType = null; + switch (resourceType) { + case VF: + originType = OriginTypeEnum.VF; + break; + case VFC: + originType = OriginTypeEnum.VFC; + break; + case VL: + originType = OriginTypeEnum.VL; + break; + case CP: + originType = OriginTypeEnum.CP; + break; + default: + break; + } + dataDefinition.setOriginType(originType); + } + 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 buildGroupInstanceName(String instanceName, String groupName) { + int groupNameIndex = groupName.indexOf(".."); + //turn group name from VFName..heatfile..module-n to VFiName..heatfile..module-n + return ValidationUtils.normaliseComponentName(instanceName) + groupName.substring(groupNameIndex); + } + + private String generateCustomizationUUID() { + return UUID.randomUUID().toString(); + } + + 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 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<RequirementAndRelationshipPair> relationshipsResult = new ArrayList<RequirementAndRelationshipPair>(); + 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<RequirementAndRelationshipPair> 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 (RequirementAndRelationshipPair immutablePair : relationships) { + String requirement = immutablePair.getRequirement(); + + Either<RelationshipInstDataDefinition, StorageOperationStatus> associateRes = connectInstancesInContainer(fromNode, toNode, immutablePair, 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 = associateRes.left().value(); + RelationshipImpl relationshipImplResult = new RelationshipImpl(); + relationshipImplResult.setType(relationshipInstData.getType()); + RequirementAndRelationshipPair requirementAndRelationshipPair = new RequirementAndRelationshipPair(requirement, relationshipImplResult); + requirementAndRelationshipPair.setCapability(immutablePair.getCapability()); + requirementAndRelationshipPair.setCapabilityOwnerId(relationshipInstData.getCapabilityOwnerId()); + requirementAndRelationshipPair.setRequirementOwnerId(relationshipInstData.getRequirementOwnerId()); + requirementAndRelationshipPair.setCapabilityUid(immutablePair.getCapabilityUid()); + requirementAndRelationshipPair.setRequirementUid(immutablePair.getRequirementUid()); + relationshipsResult.add(requirementAndRelationshipPair); + 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, fullfilled 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 - validatations + 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<RequirementAndRelationshipPair> 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> 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(); + + for (RequirementAndRelationshipPair 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)) { + if (relationPair.equalsTo(relationInJson)) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Remove relation from {} to {} capabilty {} capOwnerId {} reqOwnerId {} ", toResInstanceUid, componentId, relationInJson.getType(), + relationInJson.getCapabilityOwnerId(), relationInJson.getRequirementOwnerId()); + iterator.remove(); + + // update calculated cap/req + StorageOperationStatus status = updateCalculatedCapabiltyAfterDeleteRelation(calculatedCapabilty, fullFilledCapabilty, toResInstanceUid, relationInJson); + if (status != StorageOperationStatus.OK) { + return Either.right(status); + } + status = updateCalculatedRequirementsAfterDeleteRelation(calculatedRequirement, fullfilledRequirement, fromResInstanceUid, relationInJson); + if (status != StorageOperationStatus.OK) { + return Either.right(status); + } + isDeleted = true; + } + } + } + if (isDeleted == false) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No relation to delete from {} to {} capabilty {} capOwnerId {} reqOwnerId {} ", toResInstanceUid, componentId, relationPair.getCapability(), + relationPair.getCapabilityOwnerId(), relationPair.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); + } + + private StorageOperationStatus updateCalculatedRequirementsAfterDeleteRelation(Map<String, MapListRequirementDataDefinition> calculatedRequirement, Map<String, MapListRequirementDataDefinition> fullFilledRequirement, String fromResInstanceUid, + RelationshipInstDataDefinition relation) { + StorageOperationStatus status; + MapListRequirementDataDefinition reqByInstance = calculatedRequirement.get(fromResInstanceUid); + if (reqByInstance == null) { + // move from fullfilled + status = moveFromFullFilledRequirement(calculatedRequirement, fullFilledRequirement, fromResInstanceUid, relation); + } else { + ListRequirementDataDefinition reqByType = reqByInstance.findByKey(relation.getType()); + if (reqByType == null) { + // move from fullfilled + status = moveFromFullFilledRequirement(calculatedRequirement, fullFilledRequirement, fromResInstanceUid, relation); + } else { + Optional<RequirementDataDefinition> requirementOptional = reqByType.getListToscaDataDefinition().stream() + .filter(cap -> cap.getOwnerId().equals(relation.getRequirementOwnerId()) && cap.getName().equals(relation.getRequirement()) && cap.getUniqueId().equals(relation.getRequirementId())).findFirst(); + + if (requirementOptional.isPresent()) { + + RequirementDataDefinition requirement = requirementOptional.get(); + String leftOccurrences = requirement.getLeftOccurrences(); + if (leftOccurrences != null && !leftOccurrences.equals(RequirementDataDefinition.MAX_OCCURRENCES)) { + Integer leftIntValue = Integer.parseInt(leftOccurrences); + ++leftIntValue; + requirement.setLeftOccurrences(String.valueOf(leftIntValue)); + } + status = StorageOperationStatus.OK; + } else { + // move from fullfilled + status = moveFromFullFilledRequirement(calculatedRequirement, fullFilledRequirement, fromResInstanceUid, relation); + } + } + } + return status; + } + + private StorageOperationStatus updateCalculatedCapabiltyAfterDeleteRelation(Map<String, MapListCapabiltyDataDefinition> calculatedCapabilty, Map<String, MapListCapabiltyDataDefinition> fullFilledCapabilty, String toResInstanceUid, + RelationshipInstDataDefinition relation) { + StorageOperationStatus status; + MapListCapabiltyDataDefinition capByInstance = calculatedCapabilty.get(toResInstanceUid); + if (capByInstance == null) { + // move from fullfilled + status = moveFromFullFilledCapabilty(calculatedCapabilty, fullFilledCapabilty, toResInstanceUid, relation); + } else { + ListCapabilityDataDefinition capByType = capByInstance.findByKey(relation.getType()); + if (capByType == null) { + // move from fullfilled + status = moveFromFullFilledCapabilty(calculatedCapabilty, fullFilledCapabilty, toResInstanceUid, relation); + } else { + Optional<CapabilityDataDefinition> capabiltyOptional = capByType.getListToscaDataDefinition().stream() + .filter(cap -> cap.getOwnerId().equals(relation.getCapabilityOwnerId()) && cap.getUniqueId().equals(relation.getCapabiltyId())).findFirst(); + + if (capabiltyOptional.isPresent()) { + + CapabilityDataDefinition capability = capabiltyOptional.get(); + String leftOccurrences = capability.getLeftOccurrences(); + if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) { + Integer leftIntValue = Integer.parseInt(leftOccurrences); + ++leftIntValue; + capability.setLeftOccurrences(String.valueOf(leftIntValue)); + } + status = StorageOperationStatus.OK; + } else { + // move from fullfilled + status = moveFromFullFilledCapabilty(calculatedCapabilty, fullFilledCapabilty, toResInstanceUid, relation); + } + } + } + return status; + } + + private StorageOperationStatus moveFromFullFilledCapabilty(Map<String, MapListCapabiltyDataDefinition> calculatedCapabilty, Map<String, MapListCapabiltyDataDefinition> fullFilledCapabilty, String toResInstanceUid, + RelationshipInstDataDefinition relation) { + MapListCapabiltyDataDefinition capByInstance = fullFilledCapabilty.get(toResInstanceUid); + if (capByInstance == null) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No capabilty in fullfilled list for instance {} ", toResInstanceUid); + return StorageOperationStatus.GENERAL_ERROR; + } + ListCapabilityDataDefinition capByType = capByInstance.findByKey(relation.getType()); + if (capByType == null) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No capabilty type {} in fullfilled list for instance {} ", relation.getType(), toResInstanceUid); + return StorageOperationStatus.GENERAL_ERROR; + } + Iterator<CapabilityDataDefinition> iterator = capByType.getListToscaDataDefinition().iterator(); + boolean found = false; + while (iterator.hasNext()) { + CapabilityDataDefinition cap = iterator.next(); + if (cap.getOwnerId().equals(relation.getCapabilityOwnerId()) && cap.getName().equals(relation.getRequirement()) && cap.getUniqueId().equals(relation.getCapabiltyId())) { + 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 = calculatedCapabilty.get(toResInstanceUid); + if (mapListCapaDataDef == null) { + mapListCapaDataDef = new MapListCapabiltyDataDefinition(); + } + ListCapabilityDataDefinition findByKey = mapListCapaDataDef.findByKey(relation.getType()); + if (findByKey == null) { + findByKey = new ListCapabilityDataDefinition(); + mapListCapaDataDef.put(relation.getType(), findByKey); + } + findByKey.add(cap); + break; + } + } + if (found == false) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No capabilty type {} with ownerId {} in fullfilled list for instance {} ", relation.getType(), relation.getCapabilityOwnerId(), toResInstanceUid); + return StorageOperationStatus.GENERAL_ERROR; + } + return StorageOperationStatus.OK; + } + + private StorageOperationStatus moveFromFullFilledRequirement(Map<String, MapListRequirementDataDefinition> calculatedRequirement, Map<String, MapListRequirementDataDefinition> fullFilledRequirement, String fromResInstanceUid, + RelationshipInstDataDefinition relation) { + MapListRequirementDataDefinition reqByInstance = fullFilledRequirement.get(fromResInstanceUid); + if (reqByInstance == null) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No requirement in fullfilled list for instance {} ", fromResInstanceUid); + return StorageOperationStatus.GENERAL_ERROR; + } + ListRequirementDataDefinition reqByType = reqByInstance.findByKey(relation.getType()); + if (reqByType == null) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No requirement type {} in fullfilled list for instance {} ", relation.getType(), fromResInstanceUid); + return StorageOperationStatus.GENERAL_ERROR; + } + 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(relation.getType()); + if (findByKey == null) { + findByKey = new ListRequirementDataDefinition(); + mapListReqDataDef.put(relation.getType(), findByKey); + } + findByKey.add(req); + break; + } + } + if (found == false) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No requirement type {} with ownerId {} in fullfilled list for instance {} ", relation.getType(), relation.getCapabilityOwnerId(), fromResInstanceUid); + 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 Either<RelationshipInstDataDefinition, StorageOperationStatus> connectInstancesInContainer(String fromResInstanceUid, String toResInstanceUid, RequirementAndRelationshipPair 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<RelationshipInstDataDefinition, 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); + } + RelationshipInstDataDefinition relation = reqVsCap.left().value(); + + // add to json new relations + compositionDataDefinition.addRelation(relation.getUniqueId(), relation); + + return Either.left(relation); + } + + 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); + } + + private Either<RelationshipInstDataDefinition, StorageOperationStatus> connectRequirementVsCapability(ComponentInstanceDataDefinition fromResInstance, ComponentInstanceDataDefinition toResInstance, RequirementAndRelationshipPair 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); + + 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 capabiltyForRelation = null; + Iterator<CapabilityDataDefinition> iteratorCap = listCapabilityDataDefinition.getListToscaDataDefinition().iterator(); + while (iteratorCap.hasNext()) { + CapabilityDataDefinition cap = iteratorCap.next(); + if (cap.getUniqueId().equals(relationPair.getCapabilityUid()) && cap.getOwnerId().equals(relationPair.getCapabilityOwnerId())) { + capabiltyForRelation = cap; + String leftOccurrences = cap.getLeftOccurrences(); + if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) { + Integer leftIntValue = Integer.parseInt(leftOccurrences); + if (leftIntValue > 0) { + --leftIntValue; + capabiltyForRelation.setLeftOccurrences(String.valueOf(leftIntValue)); + if (leftIntValue == 0) { + // remove from calculated + iteratorCap.remove(); + // move to fullfilled + 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(capabiltyForRelation); + } + break; + } else { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No left occurrences capabilty {} to {} in container {}.", capabiltyForRelation.getType(), toInstId, containerId); + return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); + } + } + } + } + if (capabiltyForRelation == 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; + + 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 fullfilled + 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 (!capabiltyForRelation.getType().equals(requirementForRelation.getCapability())) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No math for capabilty from type {} and requirement {} from {} to {} in container {}.", capabiltyForRelation.getType(), requirementForRelation.getCapability(), fromInstId, toInstId, + containerId); + return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); + } + + RelationshipInstDataDefinition relationshipTypeData = buildRelationshipInstData(fromInstId, toInstId, relationPair); + + relationshipTypeData.setType(type); + + return Either.left(relationshipTypeData); + } + + private RelationshipInstDataDefinition buildRelationshipInstData(String fromResInstanceUid, String toInstId, RequirementAndRelationshipPair 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.setCapabiltyId(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) { + 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(), EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, 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 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 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 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); + } + + +} 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 new file mode 100644 index 0000000000..1eb67e5c51 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/NodeTypeOperation.java @@ -0,0 +1,774 @@ +package org.openecomp.sdc.be.model.jsontitan.operations; + +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.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.AttributeDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapCapabiltyProperty; +import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.DerivedNodeTypeResolver; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.RequirementDefinition; +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; +import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.common.jsongraph.util.CommonUtility; +import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Qualifier; + +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.regex.Pattern; + +@org.springframework.stereotype.Component("node-type-operation") +public class NodeTypeOperation extends ToscaElementOperation { + public static Pattern uuidNewVersion = Pattern.compile("^\\d{1,}.1"); + public static Pattern uuidNormativeNewVersion = Pattern.compile("^\\d{1,}.0"); + + private static Logger log = LoggerFactory.getLogger(NodeTypeOperation.class.getName()); + + private DerivedNodeTypeResolver derivedResourceResolver; + + public NodeTypeOperation(@Qualifier("derived-resource-resolver") DerivedNodeTypeResolver derivedNodeTypeResolver) { + this.derivedResourceResolver = derivedNodeTypeResolver; + } + + public Either<NodeType, StorageOperationStatus> createNodeType(NodeType nodeType) { + + Either<NodeType, StorageOperationStatus> result = null; + + nodeType.generateUUID(); + + nodeType = getResourceMetaDataFromResource(nodeType); + 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(); + } + + GraphVertex nodeTypeVertex = new GraphVertex(VertexTypeEnum.NODE_TYPE); + fillToscaElementVertexData(nodeTypeVertex, nodeType, JsonParseFlagEnum.ParseAll); + + 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, InterfaceDataDefinition.class, 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, AttributeDataDefinition>, 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, AdditionalInfoParameterDataDefinition.class, 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) { + addInformationAll.putAll(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, ListCapabilityDataDefinition.class, 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); + }); + }); + + for (Entry<String, ListCapabilityDataDefinition> entry : capabilties.entrySet()) { + capabiltiesAll.merge(entry.getKey(), entry.getValue(), (list1, list2) -> list1.mergeListItemsByName(list2)); + } + } + 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, ListRequirementDataDefinition.class, 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); + }); + }); + + for (Entry<String, ListRequirementDataDefinition> entry : requirements.entrySet()) { + requirementsAll.merge(entry.getKey(), entry.getValue(), (list1, list2) -> list1.mergeListItemsByName(list2)); + } + } + 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, AttributeDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, AttributeDataDefinition.class, EdgeLabelEnum.ATTRIBUTES); + if (dataFromDerived.isRight()) { + return dataFromDerived.right().value(); + } + Map<String, AttributeDataDefinition> attributesAll = dataFromDerived.left().value(); + + Map<String, AttributeDataDefinition> 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); + }); + attributesAll.putAll(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, MapPropertiesDataDefinition.class, 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); + }); + } + }); + propertiesAll.putAll(capabiltiesProps); + } + if (propertiesAll != null) { + 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) { + log.error("Multiple parent resources called {} found in the graph.", parentResource); + return Either.right(StorageOperationStatus.MULTIPLE_PARENT_RESOURCE_FOUND); + } + GraphVertex parentResourceData = resources.get(0); + derivedResources.add(parentResourceData); + } + + } + + } + } + return Either.left(derivedResources); + } + + 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 = null; + + 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 newDerived = getParentResources.left().value().get(0); + StorageOperationStatus updateStatus = updateDataFromNewDerived(newDerived, nodeTypeV); + if (updateStatus != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update data for {} from new derived {} ", nodeTypeV.getUniqueId(), newDerived.getUniqueId(), updateStatus); + return updateStatus; + } + + Either<Edge, TitanOperationStatus> deleteEdge = titanDao.deleteEdge(nodeTypeV, firstDerivedInChain, EdgeLabelEnum.DERIVED_FROM); + if (deleteEdge.isRight()) { + TitanOperationStatus deleteError = deleteEdge.right().value(); + log.debug("Failed to disassociate element {} from derived {} , error {}", nodeTypeV.getUniqueId(), firstDerivedInChain.getUniqueId(), deleteError); + return DaoStatusConverter.convertTitanStatusToStorageStatus(deleteError); + } + + titanDao.createEdge(nodeTypeV, newDerived, EdgeLabelEnum.DERIVED_FROM, null); + } + } + + return StorageOperationStatus.OK; + } + + private StorageOperationStatus updateDataFromNewDerived(GraphVertex newDerived, GraphVertex nodeTypeV) { + StorageOperationStatus status = updateDataByType(newDerived, nodeTypeV, EdgeLabelEnum.CAPABILITIES, CapabilityDataDefinition.class); + if (status != StorageOperationStatus.OK) { + return status; + } + status = updateDataByType(newDerived, nodeTypeV, EdgeLabelEnum.REQUIREMENTS, RequirementDefinition.class); + if (status != StorageOperationStatus.OK) { + return status; + } + status = updateDataByType(newDerived, nodeTypeV, EdgeLabelEnum.PROPERTIES, PropertyDataDefinition.class); + if (status != StorageOperationStatus.OK) { + return status; + } + status = updateDataByType(newDerived, nodeTypeV, EdgeLabelEnum.ATTRIBUTES, AttributeDataDefinition.class); + if (status != StorageOperationStatus.OK) { + return status; + } + // TODO + // status = updateDataByType(newDerived, nodeTypeV, + // EdgeLabelEnum.CAPABILITIES_PROPERTIES, capa); + // if ( status != StorageOperationStatus.OK){ + // return status; + // } + status = updateDataByType(newDerived, nodeTypeV, EdgeLabelEnum.ADDITIONAL_INFORMATION, AdditionalInfoParameterDataDefinition.class); + return status; + } + + private <T extends ToscaDataDefinition> StorageOperationStatus updateDataByType(GraphVertex newDerived, GraphVertex nodeTypeV, EdgeLabelEnum label, Class<T> clazz) { + log.debug("Update data from derived for element {} type {}", nodeTypeV.getUniqueId(), label); + Either<GraphVertex, TitanOperationStatus> dataFromGraph = getDataVertex(nodeTypeV, label); + if (dataFromGraph.isRight()) { + return DaoStatusConverter.convertTitanStatusToStorageStatus(dataFromGraph.right().value()); + } + GraphVertex dataV = dataFromGraph.left().value(); + + Map<String, T> mapFromGraph = (Map<String, T>) dataV.getJson(); + mapFromGraph.entrySet().removeIf(e -> e.getValue().getOwnerId() != null); + + List<GraphVertex> derivedList = new ArrayList<>(); + derivedList.add(newDerived); + + Either<Map<String, T>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedList, clazz, EdgeLabelEnum.CAPABILITIES); + if (dataFromDerived.isRight()) { + return dataFromDerived.right().value(); + } + Map<String, T> capabiltiesAll = dataFromDerived.left().value(); + capabiltiesAll.putAll(mapFromGraph); + + Either<GraphVertex, TitanOperationStatus> updateDataV = updateOrCopyOnUpdate(dataV, nodeTypeV, label); + if (updateDataV.isRight()) { + return DaoStatusConverter.convertTitanStatusToStorageStatus(updateDataV.right().value()); + } + return StorageOperationStatus.OK; + } + + @Override + public <T extends ToscaElement> void fillToscaElementVertexData(GraphVertex elementV, T toscaElementToUpdate, JsonParseFlagEnum flag) { + fillMetadata(elementV, (NodeType) toscaElementToUpdate); + } + +} 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 new file mode 100644 index 0000000000..62d04edf4f --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperation.java @@ -0,0 +1,1037 @@ +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 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.JsonParseFlagEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapAttributesDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapCapabiltyProperty; +import org.openecomp.sdc.be.datatypes.elements.MapGroupsDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapListCapabiltyDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapListRequirementDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.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.ComponentParametersView; +import org.openecomp.sdc.be.model.DistributionStatusEnum; +import org.openecomp.sdc.be.model.User; +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.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 com.google.gson.reflect.TypeToken; + +import fj.data.Either; + +@org.springframework.stereotype.Component("topology-template-operation") +public class TopologyTemplateOperation extends ToscaElementOperation { + private static Logger log = LoggerFactory.getLogger(TopologyTemplateOperation.class.getName()); + + 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 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 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; + } + return Either.left(topologyTemplate); + + } + + 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 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 addInstInputsToComponent(GraphVertex nodeTypeVertex, Map<String, MapPropertiesDataDefinition> instInputs) { + + if (instInputs != null && !instInputs.isEmpty()) { + instInputs.entrySet().forEach(i -> { + StorageOperationStatus status = addToscaDataDeepElementsBlockToToscaElement(nodeTypeVertex, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, i.getValue(), i.getKey()); + if (status != StorageOperationStatus.OK) { + return; + } + }); + } + + 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 associateInstArtifactToComponent(GraphVertex nodeTypeVertex, Map<String, MapArtifactDataDefinition> instProps) { + if (instProps != null && !instProps.isEmpty()) { + Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, 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, MapAttributesDataDefinition> instAttr = topologyTemplate.getInstAttributes(); + return associateInstAttributeToComponent(nodeTypeVertex, instAttr); + } + + public StorageOperationStatus associateInstAttributeToComponent(GraphVertex nodeTypeVertex, Map<String, MapAttributesDataDefinition> 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 = 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.isIgnoreCategories()) { + status = setTopologyTempalteCategoriesFromGraph(componentV, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + + } + } + if (false == componentParametersView.isIgnoreArtifacts()) { + TitanOperationStatus storageStatus = setAllArtifactsFromGraph(componentV, toscaElement); + if (storageStatus != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(storageStatus)); + } + } + if (false == componentParametersView.isIgnoreComponentInstancesProperties()) { + status = setComponentInstancesPropertiesFromGraph(componentV, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + } + if (false == componentParametersView.isIgnoreCapabilities()) { + status = setCapabilitiesFromGraph(componentV, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + } + if (false == componentParametersView.isIgnoreRequirements()) { + status = setRequirementsFromGraph(componentV, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + } + if (false == componentParametersView.isIgnoreAllVersions()) { + status = setAllVersions(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.isIgnoreGroups()) { + status = setGroupsFromGraph(componentV, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + + } + if (false == componentParametersView.isIgnoreComponentInstances()) { + status = setInstGroupsFromGraph(componentV, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + + } + if (false == componentParametersView.isIgnoreInputs()) { + status = setInputsFromGraph(componentV, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + + } + if (false == componentParametersView.isIgnoreProperties()) { + status = setPropertiesFromGraph(componentV, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + + } + + if (false == componentParametersView.isIgnoreComponentInstancesInputs()) { + status = setComponentInstancesInputsFromGraph(componentV, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + + } + } + + if (false == componentParametersView.isIgnoreCapabiltyProperties()) { + status = setComponentInstancesCapPropertiesFromGraph(componentV, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + + } + } + return Either.left(toscaElement); + } + + 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((String) metadataProperties.get(GraphPropertyEnum.UNIQUE_ID)); + 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; + } + + 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.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()); + } + + 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())) { + return true; + } + } + + } + } + } + + return false; + } + + 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; + } + +} 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 new file mode 100644 index 0000000000..27b296d3f2 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaDataOperation.java @@ -0,0 +1,11 @@ +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 new file mode 100644 index 0000000000..be995089a9 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementLifecycleOperation.java @@ -0,0 +1,1192 @@ +package org.openecomp.sdc.be.model.jsontitan.operations; + +import java.util.EnumMap; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +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.tinkerpop.gremlin.structure.Direction; +import org.apache.tinkerpop.gremlin.structure.Edge; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.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.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.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.ComponentParametersView; +import org.openecomp.sdc.be.model.DistributionStatusEnum; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; +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 fj.data.Either; + +@org.springframework.stereotype.Component("tosca-element-lifecycle-operation") + +/** + * Allows to perform lifecycle operations: + * checkin, checkout, submit for testing, start certification and certification process + * for tosca element + */ +public class ToscaElementLifecycleOperation extends BaseOperation { + + 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; + try { + getToscaElementRes = titanDao.getVertexById(toscaElementId, JsonParseFlagEnum.ParseMetadata); + if(getToscaElementRes.isRight()){ + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getToscaElementRes.right().value())); + } + if(result == null && hasPreviousVersion(getToscaElementRes.left().value())){ + // find previous version + nextVersionComponentIter = getToscaElementRes.left().value().getVertex().edges(Direction.IN, EdgeLabelEnum.VERSION.name()); + if(nextVersionComponentIter == null || !nextVersionComponentIter.hasNext()){ + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch previous version of tosca element with name {}. ", + getToscaElementRes.left().value().getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME).toString()); + result = Either.right(StorageOperationStatus.NOT_FOUND); + } + if(result == null){ + StorageOperationStatus updateOldResourceResult = updateOldToscaElementBeforeUndoCheckout(nextVersionComponentIter.next().outVertex()); + if (updateOldResourceResult != StorageOperationStatus.OK) { + result = Either.right(updateOldResourceResult); + } + } + } + if(result == null){ + operation = getToscaElementOperation(getToscaElementRes.left().value().getLabel()); + result = operation.deleteToscaElement(getToscaElementRes.left().value()); + } + } 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){ + + 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); + } + } + } + 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){ + 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.parseToJson((String)previousVersionToscaElement.property(GraphPropertyEnum.METADATA.getProperty()).value()); + jsonMetadataMap.put(GraphPropertyEnum.IS_HIGHEST_VERSION.getProperty(), true); + propertiesToUpdate.put(GraphPropertyEnum.METADATA.getProperty(), JsonParserUtils.jsonToString(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()){ + String fetchedVersion = (String) nextVersionComponentIter.next().inVertex().property(GraphPropertyEnum.VERSION.getProperty()).value(); + String fetchedName = (String) nextVersionComponentIter.next().inVertex().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()); + } + } + if (result == null) { + 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){ + result = operation.getToscaElement(cloneResult.left().value().getUniqueId()); + } + return result; + } + + 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(); + 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 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; + } +} 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 new file mode 100644 index 0000000000..95e65e1e82 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaElementOperation.java @@ -0,0 +1,1198 @@ +package org.openecomp.sdc.be.model.jsontitan.operations; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import org.apache.tinkerpop.gremlin.structure.Direction; +import org.apache.tinkerpop.gremlin.structure.Edge; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.dao.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.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.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.category.SubCategoryDefinition; +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; +import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.be.resources.data.UserData; +import org.openecomp.sdc.common.jsongraph.util.CommonUtility; +import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; +import org.openecomp.sdc.common.util.ValidationUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; + +import fj.data.Either; + +public abstract class ToscaElementOperation extends BaseOperation { + private static Logger log = LoggerFactory.getLogger(ToscaElementOperation.class.getName()); + + private static final Gson gson = new Gson(); + + protected Gson getGson() { + return gson; + } + + @Autowired + protected CategoryOperation categoryOperation; + + protected Either<GraphVertex, StorageOperationStatus> getComponentByLabelAndId(String uniqueId, ToscaElementTypeEnum nodeType, JsonParseFlagEnum parseFlag) { + + Map<GraphPropertyEnum, Object> propertiesToMatch = new HashMap<GraphPropertyEnum, Object>(); + propertiesToMatch.put(GraphPropertyEnum.UNIQUE_ID, uniqueId); + + VertexTypeEnum vertexType = ToscaElementTypeEnum.getVertexTypeByToscaType(nodeType); + Either<List<GraphVertex>, TitanOperationStatus> getResponse = titanDao.getByCriteria(vertexType, propertiesToMatch, parseFlag); + if (getResponse.isRight()) { + log.debug("Couldn't fetch component with type {} and unique id {}, error: {}", vertexType, uniqueId, getResponse.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getResponse.right().value())); + + } + List<GraphVertex> componentList = getResponse.left().value(); + if (componentList.isEmpty()) { + log.debug("Component with type {} and unique id {} was not found", vertexType, uniqueId); + return Either.right(StorageOperationStatus.NOT_FOUND); + } + GraphVertex vertexG = componentList.get(0); + return Either.left(vertexG); + } + + public Either<ToscaElement, StorageOperationStatus> getToscaElement(String uniqueId) { + return getToscaElement(uniqueId, new ComponentParametersView()); + } + + public Either<GraphVertex, StorageOperationStatus> markComponentToDelete(GraphVertex componentToDelete) { + Either<GraphVertex, StorageOperationStatus> result = null; + + Boolean isDeleted = (Boolean) componentToDelete.getMetadataProperty(GraphPropertyEnum.IS_DELETED); + if (isDeleted != null && isDeleted && !(Boolean) componentToDelete.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION)) { + // component already marked for delete + result = Either.left(componentToDelete); + return result; + } else { + + componentToDelete.addMetadataProperty(GraphPropertyEnum.IS_DELETED, Boolean.TRUE); + componentToDelete.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); + + Either<GraphVertex, TitanOperationStatus> updateNode = titanDao.updateVertex(componentToDelete); + + StorageOperationStatus updateComponent; + if (updateNode.isRight()) { + log.debug("Failed to update component {}. status is {}", componentToDelete.getUniqueId(), updateNode.right().value()); + updateComponent = DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value()); + result = Either.right(updateComponent); + return result; + } + + result = Either.left(componentToDelete); + return result; + } + } + + /** + * Performs a shadow clone of previousToscaElement + * + * @param previousToscaElement + * @param nextToscaElement + * @param user + * @return + */ + public Either<GraphVertex, StorageOperationStatus> cloneToscaElement(GraphVertex previousToscaElement, GraphVertex nextToscaElement, GraphVertex user) { + + Either<GraphVertex, StorageOperationStatus> result = null; + GraphVertex createdToscaElementVertex = null; + TitanOperationStatus status; + + Either<GraphVertex, TitanOperationStatus> createNextVersionRes = titanDao.createVertex(nextToscaElement); + if (createNextVersionRes.isRight()) { + status = createNextVersionRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create tosca element vertex {} with version {} on graph. Status is {}. ", previousToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), + previousToscaElement.getMetadataProperty(GraphPropertyEnum.VERSION), status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + if (result == null) { + createdToscaElementVertex = createNextVersionRes.left().value(); + Map<EdgePropertyEnum, Object> properties = new HashMap<EdgePropertyEnum, Object>(); + properties.put(EdgePropertyEnum.STATE, createdToscaElementVertex.getMetadataProperty(GraphPropertyEnum.STATE)); + status = titanDao.createEdge(user.getVertex(), createdToscaElementVertex.getVertex(), EdgeLabelEnum.STATE, properties); + if (status != TitanOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge with label {} from user vertex {} to tosca element vertex {} on graph. Status is {}. ", EdgeLabelEnum.STATE, user.getUniqueId(), + previousToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + } + if (result == null) { + status = titanDao.createEdge(user.getVertex(), createdToscaElementVertex.getVertex(), EdgeLabelEnum.LAST_MODIFIER, new HashMap<>()); + if (status != TitanOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge with label {} from user vertex {} to tosca element vertex {} on graph. Status is {}. ", EdgeLabelEnum.LAST_MODIFIER, user.getUniqueId(), + nextToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + } + if (result == null) { + status = titanDao.createEdge(user.getVertex(), createdToscaElementVertex.getVertex(), EdgeLabelEnum.CREATOR, new HashMap<>()); + if (status != TitanOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge with label {} from user vertex {} to tosca element vertex {} on graph. Status is {}. ", EdgeLabelEnum.CREATOR, user.getUniqueId(), + nextToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + } + if (result == null) { + Iterator<Edge> edgesToCopyIter = previousToscaElement.getVertex().edges(Direction.OUT); + while (edgesToCopyIter.hasNext()) { + Edge currEdge = edgesToCopyIter.next(); + Vertex currVertex = currEdge.inVertex(); + // if(EdgeLabelEnum.getEdgeLabelEnum(currEdge.label()).equals(EdgeLabelEnum.VERSION)){ + // continue; + // } + status = titanDao.createEdge(createdToscaElementVertex.getVertex(), currVertex, EdgeLabelEnum.getEdgeLabelEnum(currEdge.label()), currEdge); + if (status != TitanOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge with label {} from tosca element vertex {} to vertex with label {} on graph. Status is {}. ", currEdge.label(), createdToscaElementVertex.getUniqueId(), + currVertex.property(GraphPropertyEnum.LABEL.getProperty()), status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + break; + } + } + } + + if (result == null) { + result = Either.left(createdToscaElementVertex); + } else { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to clone tosca element {} with the name {}. ", previousToscaElement.getUniqueId(), previousToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME)); + } + return result; + } + + protected TitanOperationStatus setLastModifierFromGraph(GraphVertex componentV, ToscaElement toscaElement) { + Either<GraphVertex, TitanOperationStatus> parentVertex = titanDao.getParentVertex(componentV, EdgeLabelEnum.LAST_MODIFIER, JsonParseFlagEnum.NoParse); + if (parentVertex.isRight()) { + log.debug("Failed to fetch last modifier for tosca element with id {} error {}", componentV.getUniqueId(), parentVertex.right().value()); + return parentVertex.right().value(); + } + GraphVertex userV = parentVertex.left().value(); + String userId = (String) userV.getMetadataProperty(GraphPropertyEnum.USERID); + toscaElement.setLastUpdaterUserId(userId); + toscaElement.setLastUpdaterFullName(buildFullName(userV)); + return TitanOperationStatus.OK; + } + public String buildFullName(GraphVertex userV) { + + String fullName = (String) userV.getMetadataProperty(GraphPropertyEnum.FIRST_NAME); + if (fullName == null) { + fullName = ""; + } else { + fullName = fullName + " "; + } + String lastName = (String) userV.getMetadataProperty(GraphPropertyEnum.LAST_NAME); + if (lastName != null) { + fullName += lastName; + } + return fullName; + } + protected TitanOperationStatus setCreatorFromGraph(GraphVertex componentV, ToscaElement toscaElement) { + Either<GraphVertex, TitanOperationStatus> parentVertex = titanDao.getParentVertex(componentV, EdgeLabelEnum.CREATOR, JsonParseFlagEnum.NoParse); + if (parentVertex.isRight()) { + log.debug("Failed to fetch creator for tosca element with id {} error {}", componentV.getUniqueId(), parentVertex.right().value()); + return parentVertex.right().value(); + } + GraphVertex userV = parentVertex.left().value(); + String creatorUserId = (String) userV.getMetadataProperty(GraphPropertyEnum.USERID); + toscaElement.setCreatorUserId(creatorUserId); + toscaElement.setCreatorFullName(buildFullName(userV)); + + return TitanOperationStatus.OK; + } + + protected <T extends ToscaElement> T getResourceMetaDataFromResource(T toscaElement) { + if (toscaElement.getNormalizedName() == null || toscaElement.getNormalizedName().isEmpty()) { + toscaElement.setNormalizedName(ValidationUtils.normaliseComponentName(toscaElement.getName())); + } + if (toscaElement.getSystemName() == null || toscaElement.getSystemName().isEmpty()) { + toscaElement.setSystemName(ValidationUtils.convertToSystemName(toscaElement.getName())); + } + + LifecycleStateEnum lifecycleStateEnum = toscaElement.getLifecycleState(); + if (lifecycleStateEnum == null) { + toscaElement.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + } + long currentDate = System.currentTimeMillis(); + if (toscaElement.getCreationDate() == null) { + toscaElement.setCreationDate(currentDate); + } + toscaElement.setLastUpdateDate(currentDate); + + return toscaElement; + } + + protected void fillCommonMetadata(GraphVertex nodeTypeVertex, ToscaElement toscaElement) { + if (toscaElement.isHighestVersion() == null) { + toscaElement.setHighestVersion(true); + } + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_DELETED, toscaElement.getMetadataValue(JsonPresentationFields.IS_DELETED)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION, toscaElement.getMetadataValueOrDefault(JsonPresentationFields.HIGHEST_VERSION, Boolean.TRUE)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.STATE, toscaElement.getMetadataValue(JsonPresentationFields.LIFECYCLE_STATE)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.RESOURCE_TYPE, toscaElement.getMetadataValue(JsonPresentationFields.RESOURCE_TYPE)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.VERSION, toscaElement.getMetadataValue(JsonPresentationFields.VERSION)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME, toscaElement.getMetadataValue(JsonPresentationFields.NORMALIZED_NAME)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.UNIQUE_ID, toscaElement.getMetadataValue(JsonPresentationFields.UNIQUE_ID)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaElement.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.UUID, toscaElement.getMetadataValue(JsonPresentationFields.UUID)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.IS_ABSTRACT, toscaElement.getMetadataValue(JsonPresentationFields.IS_ABSTRACT)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.INVARIANT_UUID, toscaElement.getMetadataValue(JsonPresentationFields.INVARIANT_UUID)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.NAME, toscaElement.getMetadataValue(JsonPresentationFields.NAME)); + nodeTypeVertex.addMetadataProperty(GraphPropertyEnum.SYSTEM_NAME, toscaElement.getMetadataValue(JsonPresentationFields.SYSTEM_NAME)); + toscaElement.getMetadata().entrySet().stream().filter(e -> e.getValue() != null).forEach(e -> nodeTypeVertex.setJsonMetadataField(JsonPresentationFields.getByPresentation(e.getKey()), e.getValue())); + + nodeTypeVertex.setUniqueId(toscaElement.getUniqueId()); + nodeTypeVertex.setType(toscaElement.getComponentType()); + + } + + protected StorageOperationStatus assosiateToUsers(GraphVertex nodeTypeVertex, ToscaElement toscaElement) { + // handle user + String userId = toscaElement.getCreatorUserId(); + + Either<GraphVertex, TitanOperationStatus> findUser = findUserVertex(userId); + + if (findUser.isRight()) { + TitanOperationStatus status = findUser.right().value(); + log.error("Cannot find user {} in the graph. status is {}", userId, status); + return DaoStatusConverter.convertTitanStatusToStorageStatus(status); + + } + GraphVertex creatorVertex = findUser.left().value(); + GraphVertex updaterVertex = creatorVertex; + String updaterId = toscaElement.getLastUpdaterUserId(); + if (updaterId != null && !updaterId.equals(userId)) { + findUser = findUserVertex(updaterId); + if (findUser.isRight()) { + TitanOperationStatus status = findUser.right().value(); + log.error("Cannot find user {} in the graph. status is {}", userId, status); + return DaoStatusConverter.convertTitanStatusToStorageStatus(status); + } else { + updaterVertex = findUser.left().value(); + } + } + Map<EdgePropertyEnum, Object> props = new HashMap<EdgePropertyEnum, Object>(); + props.put(EdgePropertyEnum.STATE, (String) toscaElement.getMetadataValue(JsonPresentationFields.LIFECYCLE_STATE)); + + TitanOperationStatus result = titanDao.createEdge(updaterVertex, nodeTypeVertex, EdgeLabelEnum.STATE, props); + log.debug("After associating user {} to resource {}. Edge type is {}", updaterVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.STATE); + if (TitanOperationStatus.OK != result) { + return DaoStatusConverter.convertTitanStatusToStorageStatus(result); + } + result = titanDao.createEdge(updaterVertex, nodeTypeVertex, EdgeLabelEnum.LAST_MODIFIER, null); + log.debug("After associating user {} to resource {}. Edge type is {}", updaterVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER); + if (!result.equals(TitanOperationStatus.OK)) { + log.error("Failed to associate user {} to resource {}. Edge type is {}", updaterVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.LAST_MODIFIER); + return DaoStatusConverter.convertTitanStatusToStorageStatus(result); + } + + toscaElement.setLastUpdaterUserId(toscaElement.getCreatorUserId()); + toscaElement.setLastUpdaterFullName(toscaElement.getCreatorFullName()); + + result = titanDao.createEdge(creatorVertex, nodeTypeVertex, EdgeLabelEnum.CREATOR, null); + log.debug("After associating user {} to resource {}. Edge type is {} ", creatorVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.CREATOR); + if (!result.equals(TitanOperationStatus.OK)) { + log.error("Failed to associate user {} to resource {}. Edge type is {} ", creatorVertex, nodeTypeVertex.getUniqueId(), EdgeLabelEnum.CREATOR); + return DaoStatusConverter.convertTitanStatusToStorageStatus(result); + } + return StorageOperationStatus.OK; + } + + protected StorageOperationStatus assosiateResourceMetadataToCategory(GraphVertex nodeTypeVertex, ToscaElement nodeType) { + String subcategoryName = nodeType.getCategories().get(0).getSubcategories().get(0).getName(); + String categoryName = nodeType.getCategories().get(0).getName(); + Either<GraphVertex, StorageOperationStatus> getCategoryVertex = getResourceCategoryVertex(nodeType.getUniqueId(), subcategoryName, categoryName); + + if (getCategoryVertex.isRight()) { + return getCategoryVertex.right().value(); + } + + GraphVertex subCategoryV = getCategoryVertex.left().value(); + + TitanOperationStatus createEdge = titanDao.createEdge(nodeTypeVertex, subCategoryV, EdgeLabelEnum.CATEGORY, new HashMap<>()); + if (createEdge != TitanOperationStatus.OK) { + log.trace("Failed to associate resource {} to category {} with id {}", nodeType.getUniqueId(), subcategoryName, subCategoryV.getUniqueId()); + return DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge); + } + return StorageOperationStatus.OK; + } + + protected Either<GraphVertex, StorageOperationStatus> getResourceCategoryVertex(String elementId, String subcategoryName, String categoryName) { + Either<GraphVertex, StorageOperationStatus> category = categoryOperation.getCategory(categoryName, VertexTypeEnum.RESOURCE_CATEGORY); + if (category.isRight()) { + log.trace("Failed to fetch category {} for resource {} error {}", categoryName, elementId, category.right().value()); + return Either.right(category.right().value()); + } + GraphVertex categoryV = category.left().value(); + + if (subcategoryName != null) { + Either<GraphVertex, StorageOperationStatus> subCategory = categoryOperation.getSubCategoryForCategory(categoryV, subcategoryName); + if (subCategory.isRight()) { + log.trace("Failed to fetch subcategory {} of category for resource {} error {}", subcategoryName, categoryName, elementId, subCategory.right().value()); + return Either.right(subCategory.right().value()); + } + + GraphVertex subCategoryV = subCategory.left().value(); + return Either.left(subCategoryV); + } + return Either.left(categoryV); + } + + private StorageOperationStatus associateArtifactsToResource(GraphVertex nodeTypeVertex, ToscaElement toscaElement) { + Map<String, ArtifactDataDefinition> artifacts = toscaElement.getArtifacts(); + Either<GraphVertex, StorageOperationStatus> status; + if (artifacts != null) { + artifacts.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> { + String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase()); + a.setUniqueId(uniqueId); + }); + status = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.ARTIFACTS, EdgeLabelEnum.ARTIFACTS, artifacts); + if (status.isRight()) { + return status.right().value(); + } + } + Map<String, ArtifactDataDefinition> toscaArtifacts = toscaElement.getToscaArtifacts(); + if (toscaArtifacts != null) { + toscaArtifacts.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> { + String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase()); + a.setUniqueId(uniqueId); + }); + status = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.TOSCA_ARTIFACTS, EdgeLabelEnum.TOSCA_ARTIFACTS, toscaArtifacts); + if (status.isRight()) { + return status.right().value(); + } + } + Map<String, ArtifactDataDefinition> deploymentArtifacts = toscaElement.getDeploymentArtifacts(); + if (deploymentArtifacts != null) { + deploymentArtifacts.values().stream().filter(a -> a.getUniqueId() == null).forEach(a -> { + String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId().toLowerCase(), a.getArtifactLabel().toLowerCase()); + a.setUniqueId(uniqueId); + }); + status = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.DEPLOYMENT_ARTIFACTS, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS, deploymentArtifacts); + if (status.isRight()) { + return status.right().value(); + } + } + return StorageOperationStatus.OK; + } + + protected TitanOperationStatus disassociateAndDeleteCommonElements(GraphVertex toscaElementVertex) { + TitanOperationStatus status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ARTIFACTS); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to disaccociate artifact for {} error {}", toscaElementVertex.getUniqueId(), status); + return status; + } + status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.TOSCA_ARTIFACTS); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to disaccociate tosca artifact for {} error {}", toscaElementVertex.getUniqueId(), status); + return status; + } + status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to deployment artifact for {} error {}", toscaElementVertex.getUniqueId(), status); + return status; + } + status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.PROPERTIES); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to disaccociate properties for {} error {}", toscaElementVertex.getUniqueId(), status); + return status; + } + status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ATTRIBUTES); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to disaccociate attributes for {} error {}", toscaElementVertex.getUniqueId(), status); + return status; + } + status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.ADDITIONAL_INFORMATION); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to disaccociate additional information for {} error {}", toscaElementVertex.getUniqueId(), status); + return status; + } + status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CAPABILITIES); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to disaccociate capabilities for {} error {}", toscaElementVertex.getUniqueId(), status); + return status; + } + status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.REQUIREMENTS); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to disaccociate requirements for {} error {}", toscaElementVertex.getUniqueId(), status); + return status; + } + return TitanOperationStatus.OK; + } + + protected StorageOperationStatus assosiateCommonForToscaElement(GraphVertex nodeTypeVertex, ToscaElement toscaElement, List<GraphVertex> derivedResources) { + + StorageOperationStatus associateUsers = assosiateToUsers(nodeTypeVertex, toscaElement); + if (associateUsers != StorageOperationStatus.OK) { + return associateUsers; + } + StorageOperationStatus associateArtifacts = associateArtifactsToResource(nodeTypeVertex, toscaElement); + if (associateArtifacts != StorageOperationStatus.OK) { + return associateArtifacts; + } + StorageOperationStatus associateProperties = associatePropertiesToResource(nodeTypeVertex, toscaElement, derivedResources); + if (associateProperties != StorageOperationStatus.OK) { + return associateProperties; + } + StorageOperationStatus associateAdditionaInfo = associateAdditionalInfoToResource(nodeTypeVertex, toscaElement); + if (associateAdditionaInfo != StorageOperationStatus.OK) { + return associateAdditionaInfo; + } + + return StorageOperationStatus.OK; + } + + private StorageOperationStatus associatePropertiesToResource(GraphVertex nodeTypeVertex, ToscaElement nodeType, List<GraphVertex> derivedResources) { + // Note : currently only one derived supported!!!! + Either<Map<String, PropertyDataDefinition>, StorageOperationStatus> dataFromDerived = getDataFromDerived(derivedResources, PropertyDataDefinition.class, EdgeLabelEnum.PROPERTIES); + if (dataFromDerived.isRight()) { + return dataFromDerived.right().value(); + } + Map<String, PropertyDataDefinition> propertiesAll = dataFromDerived.left().value(); + + Map<String, PropertyDataDefinition> properties = nodeType.getProperties(); + + if (properties != null) { + properties.values().stream().filter(p -> p.getUniqueId() == null).forEach(p -> { + String uid = UniqueIdBuilder.buildPropertyUniqueId(nodeTypeVertex.getUniqueId(), p.getName()); + p.setUniqueId(uid); + }); + + Either<Map<String, PropertyDataDefinition>, String> eitherMerged = PropertyDataDefinition.mergeProperties(propertiesAll, properties, false); + if (eitherMerged.isRight()) { + // TODO re-factor error handling - moving BL to operation resulted in loss of info about the invalid property + log.debug("property {} cannot be overriden", eitherMerged.right().value()); + return StorageOperationStatus.INVALID_PROPERTY; + } + + } + if (!propertiesAll.isEmpty()) { + Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.PROPERTIES, EdgeLabelEnum.PROPERTIES, propertiesAll); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + private StorageOperationStatus associateAdditionalInfoToResource(GraphVertex nodeTypeVertex, ToscaElement nodeType) { + Map<String, AdditionalInfoParameterDataDefinition> additionalInformation = nodeType.getAdditionalInformation(); + if (additionalInformation != null) { + Either<GraphVertex, StorageOperationStatus> assosiateElementToData = assosiateElementToData(nodeTypeVertex, VertexTypeEnum.ADDITIONAL_INFORMATION, EdgeLabelEnum.ADDITIONAL_INFORMATION, additionalInformation); + if (assosiateElementToData.isRight()) { + return assosiateElementToData.right().value(); + } + } + return StorageOperationStatus.OK; + } + + protected <T extends ToscaDataDefinition> Either<Map<String, T>, StorageOperationStatus> getDataFromDerived(List<GraphVertex> derivedResources, Class<T> clazz, EdgeLabelEnum edge) { + Map<String, T> propertiesAll = new HashMap<>(); + + if (derivedResources != null && !derivedResources.isEmpty()) { + for (GraphVertex derived : derivedResources) { + Either<List<GraphVertex>, TitanOperationStatus> derivedProperties = titanDao.getChildrenVertecies(derived, edge, JsonParseFlagEnum.ParseJson); + if (derivedProperties.isRight()) { + if (derivedProperties.right().value() != TitanOperationStatus.NOT_FOUND) { + log.debug("Failed to get properties for derived from {} error {}", derived.getUniqueId(), derivedProperties.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(derivedProperties.right().value())); + } else { + continue; + } + } + List<GraphVertex> propList = derivedProperties.left().value(); + for (GraphVertex propV : propList) { + Map<String, T> propertiesFromDerived = (Map<String, T>) propV.getJson(); + if (propertiesFromDerived != null) { + propertiesFromDerived.entrySet().forEach(x -> x.getValue().setOwnerIdIfEmpty(derived.getUniqueId())); + propertiesAll.putAll(propertiesFromDerived); + } + } + } + } + return Either.left(propertiesAll); + } + + protected TitanOperationStatus setArtifactsFromGraph(GraphVertex componentV, ToscaElement toscaElement) { + Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.ARTIFACTS); + if (result.isLeft()) { + toscaElement.setArtifacts(result.left().value()); + } else { + if (result.right().value() != TitanOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + result = getDataFromGraph(componentV, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS); + if (result.isLeft()) { + toscaElement.setDeploymentArtifacts(result.left().value()); + } else { + if (result.right().value() != TitanOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + result = getDataFromGraph(componentV, EdgeLabelEnum.TOSCA_ARTIFACTS); + if (result.isLeft()) { + toscaElement.setToscaArtifacts(result.left().value()); + } else { + if (result.right().value() != TitanOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return TitanOperationStatus.OK; + } + + protected TitanOperationStatus setAllVersions(GraphVertex componentV, ToscaElement toscaElement) { + Map<String, String> allVersion = new HashMap<>(); + + allVersion.put((String) componentV.getMetadataProperty(GraphPropertyEnum.VERSION), componentV.getUniqueId()); + Either<GraphVertex, TitanOperationStatus> childResourceRes = titanDao.getChildVertex(componentV, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); + while (childResourceRes.isLeft()) { + GraphVertex child = childResourceRes.left().value(); + allVersion.put((String) child.getMetadataProperty(GraphPropertyEnum.VERSION), child.getUniqueId()); + childResourceRes = titanDao.getChildVertex(child, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); + } + TitanOperationStatus operationStatus = childResourceRes.right().value(); + + if (operationStatus != TitanOperationStatus.NOT_FOUND) { + return operationStatus; + } else { + Either<GraphVertex, TitanOperationStatus> parentResourceRes = titanDao.getParentVertex(componentV, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); + while (parentResourceRes.isLeft()) { + GraphVertex parent = parentResourceRes.left().value(); + allVersion.put((String) parent.getMetadataProperty(GraphPropertyEnum.VERSION), parent.getUniqueId()); + parentResourceRes = titanDao.getParentVertex(parent, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); + } + operationStatus = parentResourceRes.right().value(); + if (operationStatus != TitanOperationStatus.NOT_FOUND) { + return operationStatus; + } else { + toscaElement.setAllVersions(allVersion); + return TitanOperationStatus.OK; + } + } + } + + protected <T extends ToscaElement> Either<List<T>, StorageOperationStatus> getFollowedComponent(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, ComponentTypeEnum neededType) { + + Either<List<T>, StorageOperationStatus> result = null; + + Map<GraphPropertyEnum, Object> props = null; + + if (userId != null) { + props = new HashMap<>(); + // for Designer retrieve specific user + props.put(GraphPropertyEnum.USERID, userId); + } + // in case of user id == null -> get all users by label + // for Tester and Admin retrieve all users + Either<List<GraphVertex>, TitanOperationStatus> usersByCriteria = titanDao.getByCriteria(VertexTypeEnum.USER, props, JsonParseFlagEnum.NoParse); + if (usersByCriteria.isRight()) { + log.debug("Failed to fetch users by criteria {} error {}", props, usersByCriteria.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(usersByCriteria.right().value())); + } + List<GraphVertex> users = usersByCriteria.left().value(); + + List<T> components = new ArrayList<>(); + List<T> componentsPerUser; + for (GraphVertex userV : users) { + + HashSet<String> ids = new HashSet<String>(); + Either<List<GraphVertex>, TitanOperationStatus> childrenVertecies = titanDao.getChildrenVertecies(userV, EdgeLabelEnum.STATE, JsonParseFlagEnum.NoParse); + if (childrenVertecies.isRight() && childrenVertecies.right().value() != TitanOperationStatus.NOT_FOUND) { + log.debug("Failed to fetch children vertices for user {} by edge {} error {}", userV.getMetadataProperty(GraphPropertyEnum.USERID), EdgeLabelEnum.STATE, childrenVertecies.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(childrenVertecies.right().value())); + } + + // get all resource with current state + if (childrenVertecies.isLeft()) { + componentsPerUser = fetchComponents(lifecycleStates, childrenVertecies.left().value(), neededType, EdgeLabelEnum.STATE); + + if (componentsPerUser != null) { + for (T comp : componentsPerUser) { + ids.add(comp.getUniqueId()); + components.add(comp); + } + } + } + if (lastStateStates != null && !lastStateStates.isEmpty()) { + // get all resource with last state + childrenVertecies = titanDao.getChildrenVertecies(userV, EdgeLabelEnum.LAST_STATE, JsonParseFlagEnum.NoParse); + if (childrenVertecies.isRight() && childrenVertecies.right().value() != TitanOperationStatus.NOT_FOUND) { + log.debug("Failed to fetch children vertices for user {} by edge {} error {}", userV.getMetadataProperty(GraphPropertyEnum.USERID), EdgeLabelEnum.LAST_STATE, childrenVertecies.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(childrenVertecies.right().value())); + } + if (childrenVertecies.isLeft()) { + boolean isFirst; + componentsPerUser = fetchComponents(lastStateStates, childrenVertecies.left().value(), neededType, EdgeLabelEnum.LAST_STATE); + if (componentsPerUser != null) { + for (T comp : componentsPerUser) { + isFirst = true; + + if (ids.contains(comp.getUniqueId())) { + isFirst = false; + } + if (isFirst == true) { + components.add(comp); + } + + } + } + } + } + + } // whlile users + ; + result = Either.left(components); + return result; + + } + + private <T extends ToscaElement> List<T> fetchComponents(Set<LifecycleStateEnum> lifecycleStates, List<GraphVertex> vertices, ComponentTypeEnum neededType, EdgeLabelEnum edgelabel) { + List<T> components = new ArrayList<>(); + for (GraphVertex node : vertices) { + + Iterator<Edge> edges = node.getVertex().edges(Direction.IN, edgelabel.name()); + while (edges.hasNext()) { + Edge edge = edges.next(); + String stateStr = (String) titanDao.getProperty(edge, EdgePropertyEnum.STATE); + + LifecycleStateEnum nodeState = LifecycleStateEnum.findState(stateStr); + if (nodeState == null) { + log.debug("no supported STATE {} for element {}", stateStr, node.getUniqueId()); + continue; + } + if (lifecycleStates != null && lifecycleStates.contains(nodeState)) { + + Boolean isDeleted = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_DELETED); + if (isDeleted != null && isDeleted) { + log.trace("Deleted element {}, discard", node.getUniqueId()); + continue; + } + + Boolean isHighest = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION); + if (isHighest) { + + ComponentTypeEnum componentType = node.getType(); + // get only latest versions + + if (componentType == null) { + log.debug("No supported type {} for vertex {}", componentType, node.getUniqueId()); + continue; + } + if (neededType == componentType) { + switch (componentType) { + case SERVICE: + case PRODUCT: + handleNode(components, node, componentType); + break; + case RESOURCE: + Boolean isAbtract = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_ABSTRACT); + if (isAbtract == null || false == isAbtract) { + handleNode(components, node, componentType); + } // if not abstract + break; + default: + log.debug("not supported node type {}", componentType); + break; + }// case + } // needed type + } + } // if + } // while edges + } // while resources + return components; + } + + protected <T extends ToscaElement> void handleNode(List<T> components, GraphVertex vertexComponent, ComponentTypeEnum nodeType) { + + Either<T, StorageOperationStatus> component = getLightComponent(vertexComponent, nodeType, new ComponentParametersView(true)); + if (component.isRight()) { + log.debug("Failed to get component for id = {} error : {} skip resource", vertexComponent.getUniqueId(), component.right().value()); + } else { + components.add(component.left().value()); + } + } + + protected <T extends ToscaElement> Either<T, StorageOperationStatus> getLightComponent(String componentUid, ComponentTypeEnum nodeType, ComponentParametersView parametersFilter) { + Either<GraphVertex, TitanOperationStatus> getVertexRes = titanDao.getVertexById(componentUid); + if (getVertexRes.isRight()) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexRes.right().value())); + } + return getLightComponent(getVertexRes.left().value(), nodeType, parametersFilter); + } + + protected <T extends ToscaElement> Either<T, StorageOperationStatus> getLightComponent(GraphVertex vertexComponent, ComponentTypeEnum nodeType, ComponentParametersView parametersFilter) { + + log.trace("Starting to build light component of type {}, id {}", nodeType, vertexComponent.getUniqueId()); + + titanDao.parseVertexProperties(vertexComponent, JsonParseFlagEnum.ParseMetadata); + + T toscaElement = convertToComponent(vertexComponent); + + TitanOperationStatus status = setCreatorFromGraph(vertexComponent, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + + status = setLastModifierFromGraph(vertexComponent, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + status = setCategoriesFromGraph(vertexComponent, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + if (!parametersFilter.isIgnoreAllVersions()) { + status = setAllVersions(vertexComponent, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + } + if (!parametersFilter.isIgnoreCapabilities()) { + status = setCapabilitiesFromGraph(vertexComponent, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + } + if (!parametersFilter.isIgnoreRequirements()) { + status = setRequirementsFromGraph(vertexComponent, toscaElement); + if (status != TitanOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + } + log.debug("Ended to build light component of type {}, id {}", nodeType, vertexComponent.getUniqueId()); + return Either.left(toscaElement); + } + + @SuppressWarnings("unchecked") + protected <T extends ToscaElement> T convertToComponent(GraphVertex componentV) { + ToscaElement toscaElement = null; + VertexTypeEnum label = componentV.getLabel(); + switch (label) { + case NODE_TYPE: + toscaElement = new NodeType(); + break; + case TOPOLOGY_TEMPLATE: + toscaElement = new TopologyTemplate(); + break; + default: + log.debug("Not supported tosca type {}", label); + break; + } + + Map<String, Object> jsonMetada = componentV.getMetadataJson(); + if (toscaElement != null) { + toscaElement.setMetadata(jsonMetada); + } + return (T) toscaElement; + } + + protected TitanOperationStatus setResourceCategoryFromGraph(GraphVertex componentV, ToscaElement toscaElement) { + List<CategoryDefinition> categories = new ArrayList<>(); + SubCategoryDefinition subcategory; + + Either<GraphVertex, TitanOperationStatus> childVertex = titanDao.getChildVertex(componentV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse); + if (childVertex.isRight()) { + log.debug("failed to fetch {} for tosca element with id {}, error {}", EdgeLabelEnum.CATEGORY, componentV.getUniqueId(), childVertex.right().value()); + return childVertex.right().value(); + } + GraphVertex subCategoryV = childVertex.left().value(); + Map<GraphPropertyEnum, Object> metadataProperties = subCategoryV.getMetadataProperties(); + subcategory = new SubCategoryDefinition(); + subcategory.setUniqueId(subCategoryV.getUniqueId()); + subcategory.setNormalizedName((String) metadataProperties.get(GraphPropertyEnum.NORMALIZED_NAME)); + subcategory.setName((String) metadataProperties.get(GraphPropertyEnum.NAME)); + + Type listTypeSubcat = new TypeToken<List<String>>() { + }.getType(); + List<String> iconsfromJsonSubcat = getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.ICONS), listTypeSubcat); + subcategory.setIcons(iconsfromJsonSubcat); + + Either<GraphVertex, TitanOperationStatus> parentVertex = titanDao.getParentVertex(subCategoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse); + if (parentVertex.isRight()) { + log.debug("failed to fetch {} for category with id {}, error {}", EdgeLabelEnum.SUB_CATEGORY, subCategoryV.getUniqueId(), parentVertex.right().value()); + return childVertex.right().value(); + } + GraphVertex categoryV = parentVertex.left().value(); + metadataProperties = categoryV.getMetadataProperties(); + + CategoryDefinition category = new CategoryDefinition(); + category.setUniqueId(categoryV.getUniqueId()); + category.setNormalizedName((String) metadataProperties.get(GraphPropertyEnum.NORMALIZED_NAME)); + category.setName((String) metadataProperties.get(GraphPropertyEnum.NAME)); + + Type listTypeCat = new TypeToken<List<String>>() { + }.getType(); + List<String> iconsfromJsonCat = getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.ICONS), listTypeCat); + category.setIcons(iconsfromJsonCat); + + category.addSubCategory(subcategory); + categories.add(category); + toscaElement.setCategories(categories); + + return TitanOperationStatus.OK; + } + + public <T extends ToscaElement> Either<T, StorageOperationStatus> updateToscaElement(T toscaElementToUpdate, GraphVertex elementV, ComponentParametersView filterResult) { + Either<T, StorageOperationStatus> result = null; + + log.debug("In updateToscaElement. received component uid = {}", (toscaElementToUpdate == null ? null : toscaElementToUpdate.getUniqueId())); + if (toscaElementToUpdate == null) { + log.error("Service object is null"); + result = Either.right(StorageOperationStatus.BAD_REQUEST); + return result; + } + + String modifierUserId = toscaElementToUpdate.getLastUpdaterUserId(); + if (modifierUserId == null || modifierUserId.isEmpty()) { + log.error("UserId is missing in the request."); + result = Either.right(StorageOperationStatus.BAD_REQUEST); + return result; + } + Either<GraphVertex, TitanOperationStatus> findUser = findUserVertex(modifierUserId); + + if (findUser.isRight()) { + TitanOperationStatus status = findUser.right().value(); + log.error("Cannot find user {} in the graph. status is {}", modifierUserId, status); + return result; + } + + GraphVertex modifierV = findUser.left().value(); + // UserData modifierUserData = findUser.left().value(); + String toscaElementId = toscaElementToUpdate.getUniqueId(); + + Either<GraphVertex, TitanOperationStatus> parentVertex = titanDao.getParentVertex(elementV, EdgeLabelEnum.LAST_MODIFIER, JsonParseFlagEnum.NoParse); + if (parentVertex.isRight()) { + log.debug("Failed to fetch last modifier for tosca element with id {} error {}", toscaElementId, parentVertex.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentVertex.right().value())); + } + GraphVertex userV = parentVertex.left().value(); + String currentModifier = (String) userV.getMetadataProperty(GraphPropertyEnum.USERID); + + String prevSystemName = (String) elementV.getMetadataProperty(GraphPropertyEnum.SYSTEM_NAME); + + if (currentModifier.equals(modifierUserId)) { + log.debug("Graph LAST MODIFIER edge should not be changed since the modifier is the same as the last modifier."); + } else { + log.debug("Going to update the last modifier user of the resource from {} to {}", currentModifier, modifierUserId); + StorageOperationStatus status = moveLastModifierEdge(elementV, modifierV); + log.debug("Finish to update the last modifier user of the resource from {} to {}. status is {}", currentModifier, modifierUserId, status); + if (status != StorageOperationStatus.OK) { + result = Either.right(status); + return result; + } + } + + final long currentTimeMillis = System.currentTimeMillis(); + log.debug("Going to update the last Update Date of the resource from {} to {}", elementV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE), currentTimeMillis); + elementV.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, currentTimeMillis); + + StorageOperationStatus checkCategories = validateCategories(toscaElementToUpdate, elementV); + if (checkCategories != StorageOperationStatus.OK) { + result = Either.right(checkCategories); + return result; + } + + // update all data on vertex + fillToscaElementVertexData(elementV, toscaElementToUpdate, JsonParseFlagEnum.ParseMetadata); + + Either<GraphVertex, TitanOperationStatus> updateElement = titanDao.updateVertex(elementV); + + if (updateElement.isRight()) { + log.error("Failed to update resource {}. status is {}", toscaElementId, updateElement.right().value()); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value())); + return result; + } + GraphVertex updateElementV = updateElement.left().value(); + + // DE230195 in case resource name changed update TOSCA artifacts + // file names accordingly + String newSystemName = (String) updateElementV.getMetadataProperty(GraphPropertyEnum.SYSTEM_NAME); + if (newSystemName != null && !newSystemName.equals(prevSystemName)) { + Either<Map<String, ArtifactDataDefinition>, TitanOperationStatus> resultToscaArt = getDataFromGraph(updateElementV, EdgeLabelEnum.TOSCA_ARTIFACTS); + if (resultToscaArt.isRight()) { + log.debug("Failed to get tosca artifact from graph for tosca element {} error {}", toscaElementId, resultToscaArt.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resultToscaArt.right().value())); + } + + Map<String, ArtifactDataDefinition> toscaArtifacts = resultToscaArt.left().value(); + if (toscaArtifacts != null) { + for (Entry<String, ArtifactDataDefinition> artifact : toscaArtifacts.entrySet()) { + generateNewToscaFileName(toscaElementToUpdate.getComponentType().getValue().toLowerCase(), newSystemName, artifact.getValue()); + } + // TODO call to new Artifact operation in order to update list of artifacts + + } + // US833308 VLI in service - specific network_role property value logic + if (ComponentTypeEnum.SERVICE == toscaElementToUpdate.getComponentType()) { + // update method logs success/error and returns boolean (true if nothing fails) + // TODO!!!! + // updateServiceNameInVLIsNetworkRolePropertyValues(component, prevSystemName, newSystemName); + } + } + + if (toscaElementToUpdate.getComponentType() == ComponentTypeEnum.RESOURCE) { + StorageOperationStatus resultDerived = updateDerived(toscaElementToUpdate, updateElementV); + if (resultDerived != StorageOperationStatus.OK) { + log.debug("Failed to update from derived data for element {} error {}", toscaElementId, resultDerived); + return Either.right(resultDerived); + } + } + + Either<T, StorageOperationStatus> updatedResource = getToscaElement(updateElementV, filterResult); + if (updatedResource.isRight()) { + log.error("Failed to fetch tosca element {} after update , error {}", toscaElementId, updatedResource.right().value()); + result = Either.right(StorageOperationStatus.BAD_REQUEST); + return result; + } + + T updatedResourceValue = updatedResource.left().value(); + result = Either.left(updatedResourceValue); + + return result; + } + + protected StorageOperationStatus moveLastModifierEdge(GraphVertex elementV, GraphVertex modifierV) { + return DaoStatusConverter.convertTitanStatusToStorageStatus(titanDao.moveEdge(elementV, modifierV, EdgeLabelEnum.LAST_MODIFIER, Direction.IN)); + } + + protected StorageOperationStatus moveCategoryEdge(GraphVertex elementV, GraphVertex categoryV) { + return DaoStatusConverter.convertTitanStatusToStorageStatus(titanDao.moveEdge(elementV, categoryV, EdgeLabelEnum.CATEGORY, Direction.OUT)); + } + + private void generateNewToscaFileName(String componentType, String componentName, ArtifactDataDefinition artifactInfo) { + Map<String, Object> getConfig = (Map<String, Object>) ConfigurationManager.getConfigurationManager().getConfiguration().getToscaArtifacts().entrySet().stream().filter(p -> p.getKey().equalsIgnoreCase(artifactInfo.getArtifactLabel())) + .findAny().get().getValue(); + artifactInfo.setArtifactName(componentType + "-" + componentName + getConfig.get("artifactName")); + } + + protected <T extends ToscaElement> StorageOperationStatus validateResourceCategory(T toscaElementToUpdate, GraphVertex elementV) { + StorageOperationStatus status = StorageOperationStatus.OK; + List<CategoryDefinition> newCategoryList = toscaElementToUpdate.getCategories(); + CategoryDefinition newCategory = newCategoryList.get(0); + + Either<GraphVertex, TitanOperationStatus> childVertex = titanDao.getChildVertex(elementV, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse); + if (childVertex.isRight()) { + log.debug("failed to fetch {} for tosca element with id {}, error {}", EdgeLabelEnum.CATEGORY, elementV.getUniqueId(), childVertex.right().value()); + return DaoStatusConverter.convertTitanStatusToStorageStatus(childVertex.right().value()); + } + GraphVertex subCategoryV = childVertex.left().value(); + Map<GraphPropertyEnum, Object> metadataProperties = subCategoryV.getMetadataProperties(); + String subCategoryNameCurrent = (String) metadataProperties.get(GraphPropertyEnum.NAME); + + Either<GraphVertex, TitanOperationStatus> parentVertex = titanDao.getParentVertex(subCategoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse); + if (parentVertex.isRight()) { + log.debug("failed to fetch {} for category with id {}, error {}", EdgeLabelEnum.SUB_CATEGORY, subCategoryV.getUniqueId(), parentVertex.right().value()); + return DaoStatusConverter.convertTitanStatusToStorageStatus(childVertex.right().value()); + } + GraphVertex categoryV = parentVertex.left().value(); + metadataProperties = categoryV.getMetadataProperties(); + String categoryNameCurrent = (String) metadataProperties.get(GraphPropertyEnum.NAME); + + boolean categoryWasChanged = false; + + String newCategoryName = newCategory.getName(); + SubCategoryDefinition newSubcategory = newCategory.getSubcategories().get(0); + String newSubCategoryName = newSubcategory.getName(); + if (newCategoryName != null && false == newCategoryName.equals(categoryNameCurrent)) { + // the category was changed + categoryWasChanged = true; + } else { + // the sub-category was changed + if (newSubCategoryName != null && false == newSubCategoryName.equals(subCategoryNameCurrent)) { + log.debug("Going to update the category of the resource from {} to {}", categoryNameCurrent, newCategory); + categoryWasChanged = true; + } + } + if (categoryWasChanged) { + Either<GraphVertex, StorageOperationStatus> getCategoryVertex = getResourceCategoryVertex(elementV.getUniqueId(), newSubCategoryName, newCategoryName); + + if (getCategoryVertex.isRight()) { + return getCategoryVertex.right().value(); + } + GraphVertex newCategoryV = getCategoryVertex.left().value(); + status = moveCategoryEdge(elementV, newCategoryV); + log.debug("Going to update the category of the resource from {} to {}. status is {}", categoryNameCurrent, newCategory, status); + } + return status; + } + + + public <T extends ToscaElement> Either<List<T>, StorageOperationStatus> getElementCatalogData(ComponentTypeEnum componentType , ToscaElementTypeEnum toscaElement) { + Either<List<GraphVertex>, TitanOperationStatus> listOfHighestAndAllCertifiedComponents = this.getListOfHighestAndAllCertifiedComponents(componentType , toscaElement); + if (listOfHighestAndAllCertifiedComponents.isRight() && listOfHighestAndAllCertifiedComponents.right().value() != TitanOperationStatus.NOT_FOUND) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(listOfHighestAndAllCertifiedComponents.right().value())); + } + List<GraphVertex> highestAndAllCertified = listOfHighestAndAllCertifiedComponents.left().value(); + List<T> result = new ArrayList<>(); + if (highestAndAllCertified != null && false == highestAndAllCertified.isEmpty()) { + for (GraphVertex vertexComponent : highestAndAllCertified) { + Either<T, StorageOperationStatus> component = getLightComponent(vertexComponent, componentType, new ComponentParametersView(true)); + if (component.isRight()) { + log.debug("Failed to fetch ligth element for {} error {}", vertexComponent.getUniqueId(), component.right().value()); + return Either.right(component.right().value()); + } else { + result.add(component.left().value()); + } + } + } + return Either.left(result); + } + + +public Either<List<GraphVertex>, TitanOperationStatus> getListOfHighestAndAllCertifiedComponents(ComponentTypeEnum componentType , ToscaElementTypeEnum toscaElement) { + long startFetchAllStates = System.currentTimeMillis(); + Map<GraphPropertyEnum, Object> propertiesToMatchCertified = new HashMap<>(); + propertiesToMatchCertified.put(GraphPropertyEnum.STATE , LifecycleStateEnum.CERTIFIED.name()); + propertiesToMatchCertified.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); + if (componentType == ComponentTypeEnum.RESOURCE ){ + propertiesToMatchCertified.put(GraphPropertyEnum.IS_ABSTRACT, false); + } + + Map<GraphPropertyEnum, Object> propertiesHasNotToMatchCertified = new HashMap<>(); + propertiesHasNotToMatchCertified.put(GraphPropertyEnum.IS_DELETED, true); + + + Either<List<GraphVertex>, TitanOperationStatus> certifiedNodes = titanDao.getByCriteria(ToscaElementTypeEnum.getVertexTypeByToscaType(toscaElement) , propertiesToMatchCertified, propertiesHasNotToMatchCertified, JsonParseFlagEnum.ParseMetadata); + if (certifiedNodes.isRight() && certifiedNodes.right().value() != TitanOperationStatus.NOT_FOUND) { + return Either.right(certifiedNodes.right().value()); + } + + Map<GraphPropertyEnum, Object> propertiesToMatchHighest = new HashMap<>(); + propertiesToMatchHighest.put(GraphPropertyEnum.IS_HIGHEST_VERSION , true); + propertiesToMatchHighest.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); + if (componentType == ComponentTypeEnum.RESOURCE ){ + propertiesToMatchHighest.put(GraphPropertyEnum.IS_ABSTRACT, false); + } + + + Map<GraphPropertyEnum, Object> propertiesHasNotToMatchHighest = new HashMap<>(); + propertiesHasNotToMatchHighest.put(GraphPropertyEnum.IS_DELETED, true); + propertiesHasNotToMatchHighest.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + + + Either<List<GraphVertex>, TitanOperationStatus> highestNode = titanDao.getByCriteria(ToscaElementTypeEnum.getVertexTypeByToscaType(toscaElement) , propertiesToMatchHighest, propertiesHasNotToMatchHighest, JsonParseFlagEnum.ParseMetadata); + if (highestNode.isRight() && highestNode.right().value() != TitanOperationStatus.NOT_FOUND) { + return Either.right(highestNode.right().value()); + } + + long endFetchAllStates = System.currentTimeMillis(); + + + List<GraphVertex> allNodes = new ArrayList<>(); + + if (certifiedNodes.isLeft()) { + allNodes.addAll(certifiedNodes.left().value()); + } + if (highestNode.isLeft()){ + allNodes.addAll(highestNode.left().value()); + } + + int certifiedSize; + int nonCertifiedSize; + + if (certifiedNodes.isRight()){ + certifiedSize = 0; + } else { + certifiedSize = certifiedNodes.left().value().size(); + } + + if (highestNode.isRight()){ + nonCertifiedSize = 0; + } else { + nonCertifiedSize = highestNode.left().value().size(); + } + + + log.debug("Fetch catalog {}s all states: certified {}, noncertified {}", componentType, certifiedSize , nonCertifiedSize ); + log.debug("Fetch catalog {}s all states from graph took {} ms", componentType, endFetchAllStates - startFetchAllStates); + return Either.left(allNodes); +} + + + protected Either<List<GraphVertex>, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) { + + // get all components marked for delete + Map<GraphPropertyEnum, Object> props = new HashMap<GraphPropertyEnum, Object>(); + props.put(GraphPropertyEnum.IS_DELETED, true); + props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); + + Either<List<GraphVertex>, TitanOperationStatus> componentsToDelete = titanDao.getByCriteria(null, props, JsonParseFlagEnum.NoParse); + + if (componentsToDelete.isRight()) { + TitanOperationStatus error = componentsToDelete.right().value(); + if (error.equals(TitanOperationStatus.NOT_FOUND)) { + log.trace("no components to delete"); + return Either.left(new ArrayList<>()); + } else { + log.info("failed to find components to delete. error : {}", error.name()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error)); + } + } + return Either.left(componentsToDelete.left().value()); + } + + protected TitanOperationStatus setAdditionalInformationFromGraph(GraphVertex componentV, ToscaElement toscaElement) { + Either<Map<String, AdditionalInfoParameterDataDefinition>, TitanOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.ADDITIONAL_INFORMATION); + if (result.isLeft()) { + toscaElement.setAdditionalInformation(result.left().value()); + } else { + if (result.right().value() != TitanOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return TitanOperationStatus.OK; + } + + // -------------------------------------------- + public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> getToscaElement(String uniqueId, ComponentParametersView componentParametersView); + + public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> getToscaElement(GraphVertex toscaElementVertex, ComponentParametersView componentParametersView); + + public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> deleteToscaElement(GraphVertex toscaElementVertex); + + public abstract <T extends ToscaElement> Either<T, StorageOperationStatus> createToscaElement(ToscaElement toscaElement); + + protected abstract <T extends ToscaElement> TitanOperationStatus setCategoriesFromGraph(GraphVertex vertexComponent, T toscaElement); + + protected abstract <T extends ToscaElement> TitanOperationStatus setCapabilitiesFromGraph(GraphVertex componentV, T toscaElement); + + protected abstract <T extends ToscaElement> TitanOperationStatus setRequirementsFromGraph(GraphVertex componentV, T toscaElement); + + protected abstract <T extends ToscaElement> StorageOperationStatus validateCategories(T toscaElementToUpdate, GraphVertex elementV); + + protected abstract <T extends ToscaElement> StorageOperationStatus updateDerived(T toscaElementToUpdate, GraphVertex updateElementV); + + public abstract <T extends ToscaElement> void fillToscaElementVertexData(GraphVertex elementV, T toscaElementToUpdate, JsonParseFlagEnum flag); + +} 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 new file mode 100644 index 0000000000..9c7f108a05 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/ToscaOperationFacade.java @@ -0,0 +1,2123 @@ +package org.openecomp.sdc.be.model.jsontitan.operations; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.commons.lang3.tuple.Pair; +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.components.ComponentMetadataDataDefinition; +import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition; +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.MapAttributesDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapCapabiltyProperty; +import org.openecomp.sdc.be.datatypes.elements.MapListCapabiltyDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapListRequirementDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.AttributeDefinition; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstanceInput; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.DistributionStatusEnum; +import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.GroupInstance; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; +import org.openecomp.sdc.be.model.RequirementDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate; +import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; +import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; +import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.be.resources.data.ComponentMetadataData; +import org.openecomp.sdc.be.utils.CommonBeUtils; +import org.openecomp.sdc.common.jsongraph.util.CommonUtility; +import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; +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 { + @Autowired + private NodeTypeOperation nodeTypeOperation; + @Autowired + private TopologyTemplateOperation topologyTemplateOperation; + @Autowired + private NodeTemplateOperation nodeTemplateOperation; + @Autowired + private GroupsOperation groupsOperation; + @Autowired + private TitanDao titanDao; + + private static Logger log = LoggerFactory.getLogger(ToscaOperationFacade.class.getName()); + + public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId) { + + return getToscaElement(componentId, JsonParseFlagEnum.ParseAll); + + } + public <T extends Component> Either<T, StorageOperationStatus> getToscaFullElement(String componentId) { + ComponentParametersView filters = new ComponentParametersView(); + filters.setIgnoreCapabiltyProperties(false); + + return getToscaElement(componentId, filters); + } + public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, ComponentParametersView filters) { + + Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, filters.detectParseFlag()); + if (getVertexEither.isRight()) { + log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); + + } + return getToscaElementByOperation(getVertexEither.left().value(), filters); + } + + public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(String componentId, JsonParseFlagEnum parseFlag) { + + Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, parseFlag); + if (getVertexEither.isRight()) { + log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); + + } + return getToscaElementByOperation(getVertexEither.left().value()); + } + + public <T extends Component> Either<T, StorageOperationStatus> getToscaElement(GraphVertex componentVertex) { + return getToscaElementByOperation(componentVertex); + } + + public Either<Boolean, StorageOperationStatus> validateComponentExists(String componentId) { + + Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + TitanOperationStatus status = getVertexEither.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + return Either.left(false); + } else { + log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); + } + } + return Either.left(true); + } + + public <T extends Component> Either<T, StorageOperationStatus> findLastCertifiedToscaElementByUUID(T component) { + Map<GraphPropertyEnum, Object> props = new HashMap<>(); + props.put(GraphPropertyEnum.UUID, component.getUUID()); + props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + + Either<List<GraphVertex>, TitanOperationStatus> getVertexEither = titanDao.getByCriteria(ModelConverter.getVertexType(component), props); + if (getVertexEither.isRight()) { + log.debug("Couldn't fetch component with and unique id {}, error: {}", component.getUniqueId(), getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); + + } + return getToscaElementByOperation(getVertexEither.left().value().get(0)); + } + + private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV) { + return getToscaElementByOperation(componentV, new ComponentParametersView()); + } + + private <T extends Component> Either<T, StorageOperationStatus> getToscaElementByOperation(GraphVertex componentV, ComponentParametersView filters) { + VertexTypeEnum label = componentV.getLabel(); + + ToscaElementOperation toscaOperation = getToscaElementOperation(componentV); + Either<ToscaElement, StorageOperationStatus> toscaElement; + String componentId = componentV.getUniqueId(); + if (toscaOperation != null) { + log.debug("Need to fetch tosca element for id {}", componentId); + toscaElement = toscaOperation.getToscaElement(componentV, filters); + } else { + log.debug("not supported tosca type {} for id {}", label, componentId); + toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST); + } + if (toscaElement.isRight()) { + return Either.right(toscaElement.right().value()); + } + return Either.left(ModelConverter.convertFromToscaElement(toscaElement.left().value())); + } + + private ToscaElementOperation getToscaElementOperation(GraphVertex componentV) { + VertexTypeEnum label = componentV.getLabel(); + switch (label) { + case NODE_TYPE: + return nodeTypeOperation; + case TOPOLOGY_TEMPLATE: + return topologyTemplateOperation; + default: + return null; + } + } + + /** + * + * @param resource + * @return + */ + public <T extends Component> Either<T, StorageOperationStatus> createToscaComponent(T resource) { + ToscaElement toscaElement = ModelConverter.convertToToscaElement(resource); + + ToscaElementOperation toscaElementOperation = getToscaElementOperation(toscaElement); + Either<ToscaElement, StorageOperationStatus> createToscaElement = toscaElementOperation.createToscaElement(toscaElement); + if (createToscaElement.isLeft()) { + log.debug("Component created successfully!!!"); + T dataModel = ModelConverter.convertFromToscaElement(createToscaElement.left().value()); + return Either.left(dataModel); + } + return Either.right(createToscaElement.right().value()); + } + + /** + * + * @param componentToDelete + * @return + */ + public StorageOperationStatus markComponentToDelete(Component componentToDelete) { + + if ((componentToDelete.getIsDeleted() != null) && componentToDelete.getIsDeleted() && !componentToDelete.isHighestVersion()) { + // component already marked for delete + return StorageOperationStatus.OK; + } else { + + Either<GraphVertex, TitanOperationStatus> getResponse = titanDao.getVertexById(componentToDelete.getUniqueId(), JsonParseFlagEnum.ParseAll); + if (getResponse.isRight()) { + log.debug("Couldn't fetch component with and unique id {}, error: {}", componentToDelete.getUniqueId(), getResponse.right().value()); + return DaoStatusConverter.convertTitanStatusToStorageStatus(getResponse.right().value()); + + } + GraphVertex componentV = getResponse.left().value(); + + // same operation for node type and topology template operations + Either<GraphVertex, StorageOperationStatus> result = nodeTypeOperation.markComponentToDelete(componentV); + if (result.isRight()) { + return result.right().value(); + } + return StorageOperationStatus.OK; + } + } + + /** + * + * @param componentId + * @return + */ + public <T extends Component> Either<T, StorageOperationStatus> deleteToscaComponent(String componentId) { + + Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll); + if (getVertexEither.isRight()) { + log.debug("Couldn't fetch component vertex with and unique id {}, error: {}", componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); + + } + Either<ToscaElement, StorageOperationStatus> deleteElement = deleteToscaElement(getVertexEither.left().value()); + if (deleteElement.isRight()) { + log.debug("Failed to delete component with and unique id {}, error: {}", componentId, deleteElement.right().value()); + return Either.right(deleteElement.right().value()); + } + T dataModel = ModelConverter.convertFromToscaElement(deleteElement.left().value()); + + return Either.left(dataModel); + } + + private Either<ToscaElement, StorageOperationStatus> deleteToscaElement(GraphVertex componentV) { + VertexTypeEnum label = componentV.getLabel(); + Either<ToscaElement, StorageOperationStatus> toscaElement; + Object componentId = componentV.getUniqueId(); + switch (label) { + case NODE_TYPE: + log.debug("Need to fetch node type for id {}", componentId); + toscaElement = nodeTypeOperation.deleteToscaElement(componentV); + break; + case TOPOLOGY_TEMPLATE: + log.debug("Need to fetch topology template for id {}", componentId); + toscaElement = topologyTemplateOperation.deleteToscaElement(componentV); + break; + default: + log.debug("not supported tosca type {} for id {}", label, componentId); + toscaElement = Either.right(StorageOperationStatus.BAD_REQUEST); + break; + } + return toscaElement; + } + + private ToscaElementOperation getToscaElementOperation(ToscaElement toscaElement) { + + ComponentTypeEnum componentType = toscaElement.getComponentType(); + switch (componentType) { + case RESOURCE: + ResourceTypeEnum resourceType = toscaElement.getResourceType(); + if (resourceType == ResourceTypeEnum.VF) { + return topologyTemplateOperation; + } else { + return nodeTypeOperation; + } + case SERVICE: + case PRODUCT: + return topologyTemplateOperation; + default: + break; + } + return null; + } + + private ToscaElementOperation getToscaElementOperation(Component component) { + + switch (component.getComponentType()) { + case RESOURCE: + ResourceTypeEnum resourceType = ((Resource) component).getResourceType(); + if (resourceType != null && resourceType == ResourceTypeEnum.VF) { + return topologyTemplateOperation; + } else { + return nodeTypeOperation; + } + case SERVICE: + case PRODUCT: + return topologyTemplateOperation; + default: + break; + } + return null; + } + + public <T extends Component> Either<T, StorageOperationStatus> getLatestByToscaResourceName(String toscaResourceName) { + return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName); + + } + + public <T extends Component> Either<T, StorageOperationStatus> getLatestByName(String resourceName) { + return getLatestByName(GraphPropertyEnum.NAME, resourceName); + + } + + public Either<Integer, StorageOperationStatus> validateCsarUuidUniqueness(String csarUUID) { + Either<List<ToscaElement>, StorageOperationStatus> byCsar = null; + + Map<GraphPropertyEnum, Object> properties = new HashMap<GraphPropertyEnum, Object>(); + properties.put(GraphPropertyEnum.CSAR_UUID, csarUUID); + + Either<List<GraphVertex>, TitanOperationStatus> resources = titanDao.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata); + + if (resources.isRight()) { + if (resources.right().value() == TitanOperationStatus.NOT_FOUND) { + return Either.left(new Integer(0)); + } else { + log.debug("failed to get resources from graph with property name: {}", csarUUID); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value())); + } + } + + List<GraphVertex> resourceList = (resources.isLeft() ? resources.left().value() : null); + + return Either.left(new Integer(resourceList.size())); + + } + + public <T extends Component> Either<List<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); + } + + List<T> components = new ArrayList<>(); + if (followedResources.isRight() && followedResources.right().value() != StorageOperationStatus.NOT_FOUND) { + return Either.right(followedResources.right().value()); + } + if (followedResources.isLeft()) { + List<ToscaElement> toscaElements = followedResources.left().value(); + toscaElements.forEach(te -> { + T component = ModelConverter.convertFromToscaElement(te); + components.add(component); + }); + } + return Either.left(components); + } + + public Either<Resource, StorageOperationStatus> getLatestCertifiedNodeTypeByToscaResourceName(String toscaResourceName) { + + return getLatestCertifiedByToscaResourceName(toscaResourceName, VertexTypeEnum.NODE_TYPE, JsonParseFlagEnum.ParseMetadata); + } + + public Either<Resource, StorageOperationStatus> getLatestCertifiedByToscaResourceName(String toscaResourceName, VertexTypeEnum vertexType, JsonParseFlagEnum parseFlag) { + + Either<Resource, StorageOperationStatus> result = null; + Map<GraphPropertyEnum, Object> props = new HashMap<GraphPropertyEnum, Object>(); + props.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName); + props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + Either<List<GraphVertex>, TitanOperationStatus> getLatestRes = titanDao.getByCriteria(vertexType, props, parseFlag); + + if (getLatestRes.isRight()) { + TitanOperationStatus status = getLatestRes.right().value(); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch {} with name {}. status={} ", vertexType, toscaResourceName, status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + if (result == null) { + List<GraphVertex> resources = getLatestRes.left().value(); + double version = 0.0; + GraphVertex highestResource = null; + for (GraphVertex resource : resources) { + double resourceVersion = Double.parseDouble((String) resource.getJsonMetadataField(JsonPresentationFields.VERSION)); + if (resourceVersion > version) { + version = resourceVersion; + highestResource = resource; + } + } + result = getToscaElement(highestResource.getUniqueId()); + } + return result; + } + + public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExists(String templateName) { + Either<Boolean, StorageOperationStatus> validateUniquenessRes = validateToscaResourceNameUniqueness(templateName); + if (validateUniquenessRes.isLeft()) { + return Either.left(!validateUniquenessRes.left().value()); + } + return validateUniquenessRes; + } + + public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) { + return nodeTemplateOperation.dissociateResourceInstances(componentId, requirementDef); + + } + + public StorageOperationStatus associateResourceInstances(String componentId, List<RequirementCapabilityRelDef> relations) { + Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> status = nodeTemplateOperation.associateResourceInstances(componentId, relations); + if (status.isRight()) { + return status.right().value(); + } + return StorageOperationStatus.OK; + } + + protected Either<Boolean, StorageOperationStatus> validateToscaResourceNameUniqueness(String name) { + + Map<GraphPropertyEnum, Object> properties = new HashMap<GraphPropertyEnum, Object>(); + properties.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, name); + + Either<List<GraphVertex>, TitanOperationStatus> resources = titanDao.getByCriteria(null, properties, JsonParseFlagEnum.ParseMetadata); + + if (resources.isRight() && resources.right().value() != TitanOperationStatus.NOT_FOUND) { + log.debug("failed to get resources from graph with property name: {}", name); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resources.right().value())); + } + List<GraphVertex> resourceList = (resources.isLeft() ? resources.left().value() : null); + if (resourceList != null && resourceList.size() > 0) { + if (log.isDebugEnabled()) { + StringBuilder builder = new StringBuilder(); + for (GraphVertex resourceData : resourceList) { + builder.append(resourceData.getUniqueId() + "|"); + } + log.debug("resources with property name:{} exists in graph. found {}", name, builder.toString()); + } + return Either.left(false); + } else { + log.debug("resources with property name:{} does not exists in graph", name); + return Either.left(true); + } + + } + + /** + * + * @param newComponent + * @param oldComponent + * @return + */ + public <T extends Component> Either<T, StorageOperationStatus> overrideComponent(T newComponent, T oldComponent) { + + // TODO + // newComponent.setInterfaces(oldComponent.getInterfaces); + newComponent.setArtifacts(oldComponent.getArtifacts()); + newComponent.setDeploymentArtifacts(oldComponent.getDeploymentArtifacts()); + newComponent.setGroups(oldComponent.getGroups()); + newComponent.setInputs(null); + newComponent.setLastUpdateDate(null); + newComponent.setHighestVersion(true); + + Either<GraphVertex, TitanOperationStatus> componentVEither = titanDao.getVertexById(oldComponent.getUniqueId(), JsonParseFlagEnum.NoParse); + if (componentVEither.isRight()) { + log.debug("Falied to fetch component {} error {}", oldComponent.getUniqueId(), componentVEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(componentVEither.right().value())); + } + GraphVertex componentv = componentVEither.left().value(); + Either<GraphVertex, TitanOperationStatus> parentVertexEither = titanDao.getParentVertex(componentv, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); + if (parentVertexEither.isRight() && parentVertexEither.right().value() != TitanOperationStatus.NOT_FOUND) { + log.debug("Falied to fetch parent version for component {} error {}", oldComponent.getUniqueId(), parentVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentVertexEither.right().value())); + } + + Either<ToscaElement, StorageOperationStatus> deleteToscaComponent = deleteToscaElement(componentv); + if (deleteToscaComponent.isRight()) { + log.debug("Falied to remove old component {} error {}", oldComponent.getUniqueId(), deleteToscaComponent.right().value()); + return Either.right(deleteToscaComponent.right().value()); + } + Either<T, StorageOperationStatus> createToscaComponent = createToscaComponent(newComponent); + if (createToscaComponent.isRight()) { + log.debug("Falied to create tosca element component {} error {}", newComponent.getUniqueId(), createToscaComponent.right().value()); + return Either.right(createToscaComponent.right().value()); + } + T newElement = createToscaComponent.left().value(); + Either<GraphVertex, TitanOperationStatus> newVersionEither = titanDao.getVertexById(newElement.getUniqueId(), JsonParseFlagEnum.NoParse); + if (newVersionEither.isRight()) { + log.debug("Falied to fetch new tosca element component {} error {}", newComponent.getUniqueId(), newVersionEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(newVersionEither.right().value())); + } + if (parentVertexEither.isLeft()) { + GraphVertex previousVersionV = parentVertexEither.left().value(); + TitanOperationStatus createEdge = titanDao.createEdge(previousVersionV, newVersionEither.left().value(), EdgeLabelEnum.VERSION, null); + if (createEdge != TitanOperationStatus.OK) { + log.debug("Falied to associate to previous version {} new version {} error {}", previousVersionV.getUniqueId(), newVersionEither.right().value(), createEdge); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createEdge)); + } + } + return Either.left(newElement); + } + + /** + * + * @param componentToUpdate + * @return + */ + public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate) { + return updateToscaElement(componentToUpdate, new ComponentParametersView()); + } + + /** + * + * @param componentToUpdate + * @param type + * @param filterResult + * @return + */ + public <T extends Component> Either<T, StorageOperationStatus> updateToscaElement(T componentToUpdate, ComponentParametersView filterResult) { + String componentId = componentToUpdate.getUniqueId(); + Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll); + if (getVertexEither.isRight()) { + log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); + } + GraphVertex elementV = getVertexEither.left().value(); + ToscaElementOperation toscaElementOperation = getToscaElementOperation(elementV); + + ToscaElement toscaElementToUpdate = ModelConverter.convertToToscaElement(componentToUpdate); + Either<ToscaElement, StorageOperationStatus> updateToscaElement = toscaElementOperation.updateToscaElement(toscaElementToUpdate, elementV, filterResult); + if (updateToscaElement.isRight()) { + log.debug("Failed to update tosca element {} error {}", componentId, updateToscaElement.right().value()); + return Either.right(updateToscaElement.right().value()); + } + return Either.left(ModelConverter.convertFromToscaElement(updateToscaElement.left().value())); + } + + private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName) { + Either<T, StorageOperationStatus> result; + + Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); + + propertiesToMatch.put(property, nodeName); + propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + + propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); + + Either<List<GraphVertex>, TitanOperationStatus> highestResources = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseMetadata); + if (highestResources.isRight()) { + TitanOperationStatus status = highestResources.right().value(); + log.debug("failed to find resource with name {}. status={} ", nodeName, status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + return result; + } + + List<GraphVertex> resources = highestResources.left().value(); + double version = 0.0; + GraphVertex highestResource = null; + for (GraphVertex vertex : resources) { + Object versionObj = vertex.getMetadataProperty(GraphPropertyEnum.VERSION); + double resourceVersion = Double.valueOf((String) versionObj); + if (resourceVersion > version) { + version = resourceVersion; + highestResource = vertex; + } + } + return getToscaElementByOperation(highestResource); + } + + public <T extends Component> Either<List<T>, StorageOperationStatus> getBySystemName(ComponentTypeEnum componentType, String systemName) { + + Either<List<T>, StorageOperationStatus> result = null; + Either<T, StorageOperationStatus> getComponentRes; + List<T> components = new ArrayList<>(); + List<GraphVertex> componentVertices; + Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); + + propertiesToMatch.put(GraphPropertyEnum.SYSTEM_NAME, systemName); + if (componentType != null) + propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); + + propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); + + Either<List<GraphVertex>, TitanOperationStatus> getComponentsRes = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll); + if (getComponentsRes.isRight()) { + TitanOperationStatus status = getComponentsRes.right().value(); + log.debug("Failed to fetch the component with system name {}. Status is {} ", systemName, status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + if (result == null) { + componentVertices = getComponentsRes.left().value(); + for (GraphVertex componentVertex : componentVertices) { + getComponentRes = getToscaElementByOperation(componentVertex); + if (getComponentRes.isRight()) { + log.debug("Failed to get the component {}. Status is {} ", componentVertex.getJsonMetadataField(JsonPresentationFields.NAME), getComponentRes.right().value()); + result = Either.right(getComponentRes.right().value()); + break; + } + T componentBySystemName = getComponentRes.left().value(); + log.debug("Found component, id: {}", componentBySystemName.getUniqueId()); + components.add(componentBySystemName); + } + } + if (result == null) { + result = Either.left(components); + } + return result; + } + + public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version) { + return getComponentByNameAndVersion(componentType, name, version, JsonParseFlagEnum.ParseAll); + } + + public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVersion(ComponentTypeEnum componentType, String name, String version, JsonParseFlagEnum parseFlag) { + Either<T, StorageOperationStatus> result; + + Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class); + Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class); + + hasProperties.put(GraphPropertyEnum.NAME, name); + hasProperties.put(GraphPropertyEnum.VERSION, version); + hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true); + if (componentType != null) { + hasProperties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); + } + Either<List<GraphVertex>, TitanOperationStatus> getResourceRes = titanDao.getByCriteria(null, hasProperties, hasNotProperties, parseFlag); + if (getResourceRes.isRight()) { + TitanOperationStatus status = getResourceRes.right().value(); + log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + return result; + } + return getToscaElementByOperation(getResourceRes.left().value().get(0)); + } + + public <T extends Component> Either<List<T>, StorageOperationStatus> getCatalogComponents(ComponentTypeEnum componentType) { + List<T> components = new ArrayList<>(); + Either<List<ToscaElement>, StorageOperationStatus> catalogDataResult; + List<ToscaElement> toscaElements; + switch (componentType) { + case RESOURCE: + catalogDataResult = nodeTypeOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE ,ToscaElementTypeEnum.NodeType); + if (catalogDataResult.isRight()) { + return Either.right(catalogDataResult.right().value()); + } + toscaElements = catalogDataResult.left().value(); + Either<List<ToscaElement>, StorageOperationStatus> resourceCatalogData = topologyTemplateOperation.getElementCatalogData(ComponentTypeEnum.RESOURCE ,ToscaElementTypeEnum.TopologyTemplate); + if (resourceCatalogData.isRight()) { + return Either.right(resourceCatalogData.right().value()); + } + toscaElements.addAll(resourceCatalogData.left().value()); + break; + case SERVICE: + catalogDataResult = topologyTemplateOperation.getElementCatalogData(ComponentTypeEnum.SERVICE , ToscaElementTypeEnum.TopologyTemplate); + if (catalogDataResult.isRight()) { + return Either.right(catalogDataResult.right().value()); + } + toscaElements = catalogDataResult.left().value(); + break; + default: + log.debug("Not supported component type {}", componentType); + return Either.right(StorageOperationStatus.BAD_REQUEST); + } + toscaElements.forEach(te -> { + T component = ModelConverter.convertFromToscaElement(te); + components.add(component); + }); + return Either.left(components); + } + + public Either<List<String>, StorageOperationStatus> deleteMarkedElements(ComponentTypeEnum componentType) { + Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion; + List<String> deleted = new ArrayList<>(); + switch (componentType) { + case RESOURCE: + allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType); + break; + case SERVICE: + case PRODUCT: + allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType); + break; + default: + log.debug("Not supported component type {}", componentType); + return Either.right(StorageOperationStatus.BAD_REQUEST); + } + if (allComponentsMarkedForDeletion.isRight()) { + return Either.right(allComponentsMarkedForDeletion.right().value()); + } + List<GraphVertex> allMarked = allComponentsMarkedForDeletion.left().value(); + + Either<List<GraphVertex>, TitanOperationStatus> allNotDeletedElements = topologyTemplateOperation.getAllNotDeletedElements(); + if (allNotDeletedElements.isRight()) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(allNotDeletedElements.right().value())); + } + List<GraphVertex> allNonMarked = allNotDeletedElements.left().value(); + for (GraphVertex elementV : allMarked) { + if (topologyTemplateOperation.isInUse(elementV, allNonMarked) == false) { + Either<ToscaElement, StorageOperationStatus> deleteToscaElement = deleteToscaElement(elementV); + if (deleteToscaElement.isRight()) { + log.debug("Failed to delete marked element {} error {}", elementV.getUniqueId(), deleteToscaElement.right().value()); + } + } else { + deleted.add(elementV.getUniqueId()); + log.debug("Marked element {} in use. don't delete it", elementV.getUniqueId()); + } + } + return Either.left(deleted); + } + + public Either<List<String>, StorageOperationStatus> getAllComponentsMarkedForDeletion(ComponentTypeEnum componentType) { + Either<List<GraphVertex>, StorageOperationStatus> allComponentsMarkedForDeletion; + switch (componentType) { + case RESOURCE: + allComponentsMarkedForDeletion = nodeTypeOperation.getAllComponentsMarkedForDeletion(componentType); + break; + case SERVICE: + case PRODUCT: + allComponentsMarkedForDeletion = topologyTemplateOperation.getAllComponentsMarkedForDeletion(componentType); + break; + default: + log.debug("Not supported component type {}", componentType); + return Either.right(StorageOperationStatus.BAD_REQUEST); + } + if (allComponentsMarkedForDeletion.isRight()) { + return Either.right(allComponentsMarkedForDeletion.right().value()); + } + return Either.left(allComponentsMarkedForDeletion.left().value().stream().map(v -> v.getUniqueId()).collect(Collectors.toList())); + } + + public Either<Boolean, StorageOperationStatus> isComponentInUse(String componentId) { + Either<Boolean, StorageOperationStatus> result; + Either<List<GraphVertex>, TitanOperationStatus> allNotDeletedElements = topologyTemplateOperation.getAllNotDeletedElements(); + if (allNotDeletedElements.isRight()) { + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(allNotDeletedElements.right().value())); + } else { + result = Either.left(topologyTemplateOperation.isInUse(componentId, allNotDeletedElements.left().value())); + } + return result; + } + + public Either<ImmutablePair<Component, String>, StorageOperationStatus> addComponentInstanceToTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance, boolean allowDeleted, User user) { + + Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null; + Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null; + componentInstance.setIcon(origComponent.getIcon()); + Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addResult = nodeTemplateOperation.addComponentInstanceToTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), + ModelConverter.convertToToscaElement(origComponent), getNextComponentInstanceCounter(containerComponent, origComponent.getName()), componentInstance, allowDeleted, user); + + if (addResult.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the component instance {} to container component {}. ", componentInstance.getName(), containerComponent.getName()); + result = Either.right(addResult.right().value()); + } + if (result == null) { + updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponent.getUniqueId()); + if (updateContainerComponentRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with updated component instance {}. ", containerComponent.getName(), componentInstance.getName()); + result = Either.right(updateContainerComponentRes.right().value()); + } + } + if (result == null) { + Component updatedComponent = ModelConverter.convertFromToscaElement(updateContainerComponentRes.left().value()); + String createdInstanceId = addResult.left().value().getRight(); + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been added to container component {}. ", createdInstanceId, updatedComponent.getName()); + result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId)); + } + return result; + } + + public StorageOperationStatus associateComponentInstancesToComponent(Component containerComponent, Map<ComponentInstance, Resource> resourcesInstancesMap, boolean allowDeleted) { + + StorageOperationStatus result = null; + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to add component instances to component {}", containerComponent.getUniqueId()); + + Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(containerComponent.getUniqueId(), JsonParseFlagEnum.ParseAll); + if (metadataVertex.isRight()) { + TitanOperationStatus status = metadataVertex.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); + } + if (result == null) { + result = nodeTemplateOperation.associateComponentInstancesToComponent(containerComponent, resourcesInstancesMap, metadataVertex.left().value(), allowDeleted); + } + return result; + } + + public Either<ImmutablePair<Component, String>, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance) { + + Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null; + + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName()); + componentInstance.setIcon(origComponent.getIcon()); + Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), + ModelConverter.convertToToscaElement(origComponent), componentInstance); + if (updateResult.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata of the component instance {} belonging to container component {}. ", componentInstance.getName(), containerComponent.getName()); + result = Either.right(updateResult.right().value()); + } + if (result == null) { + Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft()); + String createdInstanceId = updateResult.left().value().getRight(); + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata of the component instance {} has been updated to container component {}. ", createdInstanceId, updatedComponent.getName()); + result = Either.left(new ImmutablePair<>(updatedComponent, createdInstanceId)); + } + return result; + } + + public Either<Component, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent) { + + Either<Component, StorageOperationStatus> result = null; + + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update the metadata belonging to container component {}. ", containerComponent.getName()); + + Either<TopologyTemplate, StorageOperationStatus> updateResult = nodeTemplateOperation.updateComponentInstanceMetadataOfTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent)); + if (updateResult.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the metadata belonging to container component {}. ", containerComponent.getName()); + result = Either.right(updateResult.right().value()); + } + if (result == null) { + Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value()); + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The metadata has been updated to container component {}. ", updatedComponent.getName()); + result = Either.left(updatedComponent); + } + return result; + } + + public Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteComponentInstanceFromTopologyTemplate(Component containerComponent, String resourceInstanceId) { + + Either<ImmutablePair<Component, String>, StorageOperationStatus> result = null; + + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName()); + + Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateResult = nodeTemplateOperation.deleteComponentInstanceFromTopologyTemplate(ModelConverter.convertToToscaElement(containerComponent), resourceInstanceId); + if (updateResult.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete the component instance {} belonging to container component {}. ", resourceInstanceId, containerComponent.getName()); + result = Either.right(updateResult.right().value()); + } + if (result == null) { + Component updatedComponent = ModelConverter.convertFromToscaElement(updateResult.left().value().getLeft()); + String deletedInstanceId = updateResult.left().value().getRight(); + CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "The component instance {} has been deleted from container component {}. ", deletedInstanceId, updatedComponent.getName()); + result = Either.left(new ImmutablePair<>(updatedComponent, deletedInstanceId)); + } + return result; + } + + private String getNextComponentInstanceCounter(Component containerComponent, String originResourceName) { + + Integer nextCounter = 0; + + if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) { + + String normalizedName = ValidationUtils.normalizeComponentInstanceName(originResourceName); + Integer maxCounterFromNames = getMaxCounterFromNames(containerComponent, normalizedName); + Integer maxCounterFromIds = getMaxCounterFromIds(containerComponent, normalizedName); + + if (maxCounterFromNames == null && maxCounterFromIds != null) { + nextCounter = maxCounterFromIds + 1; + } else if (maxCounterFromIds == null && maxCounterFromNames != null) { + nextCounter = maxCounterFromNames + 1; + } else if (maxCounterFromIds != null && maxCounterFromNames != null) { + nextCounter = maxCounterFromNames > maxCounterFromIds ? maxCounterFromNames + 1 : maxCounterFromIds + 1; + } + } + return nextCounter.toString(); + } + + private Integer getMaxCounterFromNames(Component containerComponent, String normalizedName) { + + Integer maxCounter = 0; + List<String> countersStr = containerComponent.getComponentInstances().stream().filter(ci -> ci.getNormalizedName() != null && ci.getNormalizedName().startsWith(normalizedName)).map(ci -> ci.getNormalizedName().split(normalizedName)[1]) + .collect(Collectors.toList()); + + if (CollectionUtils.isEmpty(countersStr)) { + return null; + } + Integer currCounter = null; + for (String counter : countersStr) { + if (StringUtils.isEmpty(counter)) { + continue; + } + try { + currCounter = Integer.parseInt(counter); + } catch (Exception e) { + continue; + } + maxCounter = maxCounter < currCounter ? currCounter : maxCounter; + } + if (currCounter == null) { + return null; + } + return maxCounter; + } + + private Integer getMaxCounterFromIds(Component containerComponent, String normalizedName) { + + Integer maxCounter = 0; + List<String> countersStr = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId() != null && ci.getUniqueId().contains(normalizedName)).map(ci -> ci.getUniqueId().split(normalizedName)[1]) + .collect(Collectors.toList()); + + if (CollectionUtils.isEmpty(countersStr)) { + return null; + } + Integer currCounter = null; + for (String counter : countersStr) { + if (StringUtils.isEmpty(counter)) { + continue; + } + try { + currCounter = Integer.parseInt(counter); + } catch (Exception e) { + continue; + } + maxCounter = maxCounter < currCounter ? currCounter : maxCounter; + } + if (currCounter == null) { + return null; + } + return maxCounter; + } + + public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) { + return nodeTemplateOperation.associateResourceInstances(componentId, requirementDef); + + } + + public Either<List<InputDefinition>, StorageOperationStatus> createAndAssociateInputs(Map<String, InputDefinition> inputs, String componentId) { + + Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); + + } + + GraphVertex vertex = getVertexEither.left().value(); + Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue()))); + + StorageOperationStatus status = topologyTemplateOperation.associateInputsToComponent(vertex, inputsMap, componentId); + + if (StorageOperationStatus.OK == status) { + log.debug("Component created successfully!!!"); + List<InputDefinition> inputsResList = null; + if (inputsMap != null && !inputsMap.isEmpty()) { + inputsResList = inputsMap.values().stream().map(i -> new InputDefinition(i)).collect(Collectors.toList()); + } + return Either.left(inputsResList); + } + return Either.right(status); + + } + + public Either<List<InputDefinition>, StorageOperationStatus> addInputsToComponent(Map<String, InputDefinition> inputs, String componentId) { + + Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); + + } + + GraphVertex vertex = getVertexEither.left().value(); + Map<String, PropertyDataDefinition> inputsMap = inputs.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new PropertyDataDefinition(e.getValue()))); + + StorageOperationStatus status = topologyTemplateOperation.addToscaDataToToscaElement(vertex, EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputsMap, JsonPresentationFields.NAME); + + if (StorageOperationStatus.OK == status) { + log.debug("Component created successfully!!!"); + List<InputDefinition> inputsResList = null; + if (inputsMap != null && !inputsMap.isEmpty()) { + inputsResList = inputsMap.values().stream().map(i -> new InputDefinition(i)).collect(Collectors.toList()); + } + return Either.left(inputsResList); + } + return Either.right(status); + + } + + public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> associateComponentInstancePropertiesToComponent(Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) { + + Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value())); + + } + + GraphVertex vertex = getVertexEither.left().value(); + Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>(); + if (instProperties != null) { + + 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); + + } + + public Either<Map<String, List<ComponentInstanceInput>>, StorageOperationStatus> addComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instProperties, String componentId) { + + Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); + return 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<ComponentInstanceInput>> entry : instProperties.entrySet()) { + propertiesMap = new MapPropertiesDataDefinition(); + + propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e))); + + instPropsMap.put(entry.getKey(), propertiesMap); + } + } + + StorageOperationStatus status = topologyTemplateOperation.addInstInputsToComponent(vertex, instPropsMap); + + if (StorageOperationStatus.OK == status) { + log.debug("Component created successfully!!!"); + return Either.left(instProperties); + } + return Either.right(status); + + } + + public StorageOperationStatus deleteComponentInstanceInputsToComponent(Map<String, List<ComponentInstanceInput>> instProperties, String componentId) { + + Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); + return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()); + + } + + GraphVertex vertex = getVertexEither.left().value(); + Map<String, MapPropertiesDataDefinition> instPropsMap = new HashMap<>(); + if (instProperties != null) { + + MapPropertiesDataDefinition propertiesMap; + for (Entry<String, List<ComponentInstanceInput>> entry : instProperties.entrySet()) { + propertiesMap = new MapPropertiesDataDefinition(); + + propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new PropertyDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e))); + + instPropsMap.put(entry.getKey(), propertiesMap); + } + } + + return topologyTemplateOperation.deleteInstInputsToComponent(vertex, instPropsMap); + + } + + public Either<Map<String, List<ComponentInstanceProperty>>, StorageOperationStatus> addComponentInstancePropertiesToComponent(Component containerComponent, Map<String, List<ComponentInstanceProperty>> instProperties, String componentId) { + + StorageOperationStatus status = StorageOperationStatus.OK; + if (instProperties != null) { + + for (Entry<String, List<ComponentInstanceProperty>> entry : instProperties.entrySet()) { + List<ComponentInstanceProperty> props = entry.getValue(); + String componentInstanseId = entry.getKey(); + List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanseId); + if (props != null && !props.isEmpty()) { + for (ComponentInstanceProperty property : props) { + Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny(); + if (instanceProperty.isPresent()) { + status = updateComponentInstanceProperty(containerComponent, componentInstanseId, property); + } else { + status = addComponentInstanceProperty(containerComponent, componentInstanseId, property); + } + + } + } + } + } + + return Either.left(instProperties); + + } + + public StorageOperationStatus associateArtifactToInstances(Map<String, Map<String, ArtifactDefinition>> instArtifacts, String componentId, User user) { + + Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); + return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()); + + } + + GraphVertex vertex = getVertexEither.left().value(); + Map<String, MapArtifactDataDefinition> instArtMap = new HashMap<>(); + if (instArtifacts != null) { + + MapArtifactDataDefinition artifactsMap; + for (Entry<String, Map<String, ArtifactDefinition>> entry : instArtifacts.entrySet()) { + Map<String, ArtifactDefinition> artList = entry.getValue(); + Map<String, ArtifactDataDefinition> artifacts = artList.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); + artifactsMap = nodeTemplateOperation.prepareInstDeploymentArtifactPerInstance(artifacts, entry.getKey(), user, NodeTemplateOperation.HEAT_VF_ENV_NAME); + + instArtMap.put(entry.getKey(), artifactsMap); + } + } + + return topologyTemplateOperation.associateInstArtifactToComponent(vertex, instArtMap); + + } + + public StorageOperationStatus associateInstAttributeToComponentToInstances(Map<String, List<AttributeDefinition>> 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, MapAttributesDataDefinition> instAttr = new HashMap<>(); + if (instArttributes != null) { + + MapAttributesDataDefinition attributesMap; + for (Entry<String, List<AttributeDefinition>> entry : instArttributes.entrySet()) { + attributesMap = new MapAttributesDataDefinition(); + attributesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new AttributeDataDefinition(e)).collect(Collectors.toMap(e -> e.getName(), e -> e))); + instAttr.put(entry.getKey(), attributesMap); + } + } + + return topologyTemplateOperation.associateInstAttributeToComponent(vertex, instAttr); + + } + + public StorageOperationStatus associateCalculatedCapReq(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReg, String componentId) { + Either<GraphVertex, TitanOperationStatus> getVertexEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); + if (getVertexEither.isRight()) { + log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); + return DaoStatusConverter.convertTitanStatusToStorageStatus(getVertexEither.right().value()); + + } + + GraphVertex vertex = getVertexEither.left().value(); + + Map<String, MapListRequirementDataDefinition> calcRequirements = new HashMap<>(); + + Map<String, MapListCapabiltyDataDefinition> calcCapabilty = new HashMap<>(); + Map<String, MapCapabiltyProperty> calculatedCapabilitiesProperties = new HashMap<>();; + if (instCapabilties != null) { + for (Entry<ComponentInstance, Map<String, List<CapabilityDefinition>>> entry : instCapabilties.entrySet()) { + + Map<String, List<CapabilityDefinition>> caps = entry.getValue(); + Map<String, ListCapabilityDataDefinition> mapToscaDataDefinition = new HashMap<>(); + for (Entry<String, List<CapabilityDefinition>> instCapability : caps.entrySet()) { + mapToscaDataDefinition.put(instCapability.getKey(), new ListCapabilityDataDefinition(instCapability.getValue().stream().map(iCap -> new CapabilityDataDefinition(iCap)).collect(Collectors.toList()))); + } + + ComponentInstanceDataDefinition componentInstance = new ComponentInstanceDataDefinition(entry.getKey()); + MapListCapabiltyDataDefinition capMap = nodeTemplateOperation.prepareCalculatedCapabiltyForNodeType(mapToscaDataDefinition, componentInstance); + + MapCapabiltyProperty mapCapabiltyProperty = ModelConverter.convertToMapOfMapCapabiltyProperties(caps, componentInstance.getUniqueId(), true); + + calcCapabilty.put(entry.getKey().getUniqueId(), capMap); + calculatedCapabilitiesProperties.put(entry.getKey().getUniqueId(), mapCapabiltyProperty); + } + } + + if (instReg != null) { + for (Entry<ComponentInstance, Map<String, List<RequirementDefinition>>> entry : instReg.entrySet()) { + + Map<String, List<RequirementDefinition>> req = entry.getValue(); + Map<String, ListRequirementDataDefinition> mapToscaDataDefinition = new HashMap<>(); + for (Entry<String, List<RequirementDefinition>> instReq : req.entrySet()) { + mapToscaDataDefinition.put(instReq.getKey(), new ListRequirementDataDefinition(instReq.getValue().stream().map(iCap -> new RequirementDataDefinition(iCap)).collect(Collectors.toList()))); + } + + MapListRequirementDataDefinition capMap = nodeTemplateOperation.prepareCalculatedRequirementForNodeType(mapToscaDataDefinition, new ComponentInstanceDataDefinition(entry.getKey())); + + calcRequirements.put(entry.getKey().getUniqueId(), capMap); + } + } + + StorageOperationStatus status = topologyTemplateOperation.associateCalcCapReqToComponent(vertex, calcRequirements, calcCapabilty, calculatedCapabilitiesProperties); + + return status; + } + + private Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractToscaElementsMetadataOnly(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, + VertexTypeEnum vertexType) { + + Map<GraphPropertyEnum, Object> hasProps = new EnumMap<>(GraphPropertyEnum.class); + Map<GraphPropertyEnum, Object> hasNotProps = new EnumMap<>(GraphPropertyEnum.class); + + fillPropsMap(hasProps, hasNotProps, internalComponentType, componentTypeEnum, isAbstract, vertexType); + + Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(vertexType, hasProps, hasNotProps, JsonParseFlagEnum.ParseMetadata); + if (getRes.isRight()) { + if (getRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { + return Either.left(new ArrayList<>()); + } else { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value())); + } + } else { + List<Component> nonAbstractLatestComponents = new ArrayList<>(); + ComponentParametersView params = new ComponentParametersView(true); + params.setIgnoreAllVersions(false); + for (GraphVertex vertexComponent : getRes.left().value()) { + Either<ToscaElement, StorageOperationStatus> componentRes = topologyTemplateOperation.getLightComponent(vertexComponent, componentTypeEnum, params); + if (componentRes.isRight()) { + log.debug("Failed to fetch ligth element for {} error {}", vertexComponent.getUniqueId(), componentRes.right().value()); + return Either.right(componentRes.right().value()); + } else { + Component component = ModelConverter.convertFromToscaElement(componentRes.left().value()); + + nonAbstractLatestComponents.add(component); + } + } + + return Either.left(nonAbstractLatestComponents); + } + } + + public Either<ComponentMetadataData, StorageOperationStatus> getLatestComponentMetadataByUuid(String componentUuid, JsonParseFlagEnum parseFlag) { + + Either<ComponentMetadataData, StorageOperationStatus> result; + + Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class); + + hasProperties.put(GraphPropertyEnum.UUID, componentUuid); + hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + + Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); + propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); + + Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(null, hasProperties, propertiesNotToMatch, parseFlag); + if (getRes.isRight()) { + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value())); + } else { + List<ComponentMetadataData> latestVersionList = getRes.left().value().stream().map(ModelConverter::convertToComponentMetadata).collect(Collectors.toList()); + ComponentMetadataData latestVersion = latestVersionList.size() == 1 ? latestVersionList.get(0) + : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getMetadataDataDefinition().getVersion()), Double.parseDouble(c2.getMetadataDataDefinition().getVersion()))).get(); + result = Either.left(latestVersion); + } + return result; + } + + public Either<ComponentMetadataData, StorageOperationStatus> getComponentMetadata(String componentId) { + + Either<ComponentMetadataData, StorageOperationStatus> result; + Either<GraphVertex, TitanOperationStatus> getRes = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata); + if (getRes.isRight()) { + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value())); + } else { + ComponentMetadataData componentMetadata = ModelConverter.convertToComponentMetadata(getRes.left().value()); + result = Either.left(componentMetadata); + } + return result; + } + + private Map<String, ComponentMetadataData> findLatestVersion(List<ComponentMetadataData> resourceDataList) { + Map<Pair<String, String>, ComponentMetadataData> latestVersionMap = new HashMap<Pair<String, String>, ComponentMetadataData>(); + for (ComponentMetadataData resourceData : resourceDataList) { + ComponentMetadataData latestVersionData = resourceData; + + ComponentMetadataDataDefinition metadataDataDefinition = resourceData.getMetadataDataDefinition(); + Pair<String, String> pair = createKeyPair(latestVersionData); + if (latestVersionMap.containsKey(pair)) { + latestVersionData = latestVersionMap.get(pair); + String currentVersion = latestVersionData.getMetadataDataDefinition().getVersion(); + String newVersion = metadataDataDefinition.getVersion(); + if (CommonBeUtils.compareAsdcComponentVersions(newVersion, currentVersion)) { + latestVersionData = resourceData; + } + } + if (log.isDebugEnabled()) + log.debug("last certified version of resource = {} version is {}", latestVersionData.getMetadataDataDefinition().getName(), latestVersionData.getMetadataDataDefinition().getVersion()); + + latestVersionMap.put(pair, latestVersionData); + } + + Map<String, ComponentMetadataData> resVersionMap = new HashMap<String, ComponentMetadataData>(); + for (ComponentMetadataData resourceData : latestVersionMap.values()) { + ComponentMetadataData latestVersionData = resourceData; + ComponentMetadataDataDefinition metadataDataDefinition = resourceData.getMetadataDataDefinition(); + if (resVersionMap.containsKey(metadataDataDefinition.getUUID())) { + latestVersionData = resVersionMap.get(metadataDataDefinition.getUUID()); + String currentVersion = latestVersionData.getMetadataDataDefinition().getVersion(); + String newVersion = metadataDataDefinition.getVersion(); + if (CommonBeUtils.compareAsdcComponentVersions(newVersion, currentVersion)) { + latestVersionData = resourceData; + } + } + if (log.isDebugEnabled()) + log.debug("last uuid version of resource = {} version is {}", latestVersionData.getMetadataDataDefinition().getName(), latestVersionData.getMetadataDataDefinition().getVersion()); + resVersionMap.put(latestVersionData.getMetadataDataDefinition().getUUID(), latestVersionData); + } + + return resVersionMap; + } + + private Pair<String, String> createKeyPair(ComponentMetadataData metadataData) { + Pair<String, String> pair; + NodeTypeEnum label = NodeTypeEnum.getByName(metadataData.getLabel()); + switch (label) { + case Resource: + pair = new ImmutablePair<>(metadataData.getMetadataDataDefinition().getName(), ((ResourceMetadataDataDefinition) metadataData.getMetadataDataDefinition()).getResourceType().name()); + break; + default: + pair = new ImmutablePair<>(metadataData.getMetadataDataDefinition().getName(), metadataData.getLabel()); + break; + } + + return pair; + } + + public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractComponents(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids) { + + Either<List<Component>, StorageOperationStatus> result = null; + List<Component> components = new ArrayList<>(); + if (componentUids == null) { + Either<List<String>, StorageOperationStatus> componentUidsRes = getComponentUids(isAbstract, isHighest, componentTypeEnum, internalComponentType, componentUids); + if (componentUidsRes.isRight()) { + result = Either.right(componentUidsRes.right().value()); + } else { + componentUids = componentUidsRes.left().value(); + } + } + if (!componentUids.isEmpty()) { + for (String componentUid : componentUids) { + ComponentParametersView componentParametersView = buildComponentViewForNotAbstract(); + if (internalComponentType != null && "vl".equalsIgnoreCase(internalComponentType)) { + componentParametersView.setIgnoreCapabilities(false); + componentParametersView.setIgnoreRequirements(false); + } + Either<ToscaElement, StorageOperationStatus> getToscaElementRes = nodeTemplateOperation.getToscaElementOperation(componentTypeEnum).getLightComponent(componentUid, componentTypeEnum, componentParametersView); + if (getToscaElementRes.isRight()) { + if (log.isDebugEnabled()) + log.debug("Failed to fetch resource for error is {}", getToscaElementRes.right().value()); + result = Either.right(getToscaElementRes.right().value()); + break; + } + Component component = ModelConverter.convertFromToscaElement(getToscaElementRes.left().value()); + component.setContactId(null); + component.setCreationDate(null); + component.setCreatorUserId(null); + component.setCreatorFullName(null); + component.setLastUpdateDate(null); + component.setLastUpdaterUserId(null); + component.setLastUpdaterFullName(null); + component.setNormalizedName(null); + components.add(component); + } + } + if (result == null) { + result = Either.left(components); + } + return result; + } + + private Either<List<String>, StorageOperationStatus> getComponentUids(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType, List<String> componentUids) { + + Either<List<String>, StorageOperationStatus> result = null; + Either<List<Component>, StorageOperationStatus> getToscaElementsRes = getLatestVersionNotAbstractMetadataOnly(isAbstract, isHighest, componentTypeEnum, internalComponentType); + if (getToscaElementsRes.isRight()) { + result = Either.right(getToscaElementsRes.right().value()); + } else { + List<Component> collection = getToscaElementsRes.left().value(); + if (collection == null) { + componentUids = new ArrayList<>(); + } else { + componentUids = collection.stream().map(p -> p.getUniqueId()).collect(Collectors.toList()); + } + } + if (result == null) { + result = Either.left(componentUids); + } + return result; + } + + private ComponentParametersView buildComponentViewForNotAbstract() { + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.disableAll(); + componentParametersView.setIgnoreCategories(false); + componentParametersView.setIgnoreAllVersions(false); + return componentParametersView; + } + + public Either<Boolean, StorageOperationStatus> validateComponentNameExists(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) { + Either<Boolean, StorageOperationStatus> result = validateComponentNameUniqueness(name, resourceType, componentType); + if (result.isLeft()) { + result = Either.left(!result.left().value()); + } + return result; + } + + public Either<Boolean, StorageOperationStatus> validateComponentNameUniqueness(String name, ResourceTypeEnum resourceType, ComponentTypeEnum componentType) { + VertexTypeEnum vertexType = getVertexTypeByComponentAndResourceTypeEnum(resourceType, componentType); + String normalizedName = ValidationUtils.normaliseComponentName(name); + Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class); + properties.put(GraphPropertyEnum.NORMALIZED_NAME, normalizedName); + properties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); + + Either<List<GraphVertex>, TitanOperationStatus> vertexEither = titanDao.getByCriteria(vertexType, properties, JsonParseFlagEnum.NoParse); + if (vertexEither.isRight() && vertexEither.right().value() != TitanOperationStatus.NOT_FOUND) { + log.debug("failed to get vertex from graph with property normalizedName: {}", normalizedName); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexEither.right().value())); + } + List<GraphVertex> vertexList = vertexEither.isLeft() ? vertexEither.left().value() : null; + if (vertexList != null && !vertexList.isEmpty()) { + return Either.left(false); + } else { + return Either.left(true); + } + } + + // UI query parameter is either VFC/CP/VL(for yaml upload/update) or VF (for CSAR upload/user composed VF) + // TODO implementation of topology template VFCs may require updating this method - depending on UI implementation + private VertexTypeEnum getVertexTypeByComponentAndResourceTypeEnum(ResourceTypeEnum resourceType, ComponentTypeEnum componentType) { + VertexTypeEnum vertexType = VertexTypeEnum.TOPOLOGY_TEMPLATE; + if (ComponentTypeEnum.RESOURCE == componentType && ResourceTypeEnum.VF != resourceType) { + vertexType = VertexTypeEnum.NODE_TYPE; + } + return vertexType; + } + + private void fillNodeTypePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType) { + switch (internalComponentType.toLowerCase()) { + case "vf": + hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VF.name()); + hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VFCMT.name()); + break; + case "service": + hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VFC.name()); + hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VFCMT.name()); + break; + case "vl": + hasProps.put(GraphPropertyEnum.RESOURCE_TYPE, ResourceTypeEnum.VL.name()); + break; + default: + break; + } + } + + private void fillTopologyTemplatePropsMap(Map<GraphPropertyEnum, Object> hasProps, ComponentTypeEnum componentTypeEnum) { + switch (componentTypeEnum) { + case RESOURCE: + hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); + break; + case SERVICE: + hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); + break; + default: + break; + } + } + + private void fillPropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType, ComponentTypeEnum componentTypeEnum, boolean isAbstract, VertexTypeEnum internalVertexType) { + hasNotProps.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()); + + hasNotProps.put(GraphPropertyEnum.IS_DELETED, true); + if (VertexTypeEnum.NODE_TYPE == internalVertexType) { + hasProps.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract); + if (internalComponentType != null) { + fillNodeTypePropsMap(hasProps, hasNotProps, internalComponentType); + } + } else { + fillTopologyTemplatePropsMap(hasProps, componentTypeEnum); + } + } + + private List<VertexTypeEnum> getInternalVertexTypes(ComponentTypeEnum componentTypeEnum, String internalComponentType) { + List<VertexTypeEnum> internalVertexTypes = new ArrayList<>(); + if (ComponentTypeEnum.RESOURCE == componentTypeEnum) { + internalVertexTypes.add(VertexTypeEnum.NODE_TYPE); + } + if (ComponentTypeEnum.SERVICE == componentTypeEnum || "service".equalsIgnoreCase(internalComponentType)) { + internalVertexTypes.add(VertexTypeEnum.TOPOLOGY_TEMPLATE); + } + return internalVertexTypes; + } + + public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractMetadataOnly(boolean isAbstract, Boolean isHighest, ComponentTypeEnum componentTypeEnum, String internalComponentType) { + List<VertexTypeEnum> internalVertexTypes = getInternalVertexTypes(componentTypeEnum, internalComponentType); + List<Component> result = new ArrayList<>(); + for (VertexTypeEnum vertexType : internalVertexTypes) { + Either<List<Component>, StorageOperationStatus> listByVertexType = getLatestVersionNotAbstractToscaElementsMetadataOnly(isAbstract, isHighest, componentTypeEnum, internalComponentType, vertexType); + if (listByVertexType.isRight()) { + return listByVertexType; + } + result.addAll(listByVertexType.left().value()); + } + return Either.left(result); + + } + + public Either<List<Component>, StorageOperationStatus> getLatestComponentListByUuid(String componentUuid) { + Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + return getComponentListByUuid(componentUuid, propertiesToMatch); + } + + 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); + } + + List<Component> latestComponents = new ArrayList<Component>(); + for (GraphVertex vertex : vertexList) { + latestComponents.add(getToscaElementByOperation(vertex).left().value()); + } + + return Either.left(latestComponents); + } + + public Either<Component, StorageOperationStatus> getLatestComponentByUuid(String componentUuid) { + + Either<List<Component>, StorageOperationStatus> latestVersionListEither = getLatestComponentListByUuid(componentUuid); + + if (latestVersionListEither.isRight()) { + return Either.right(latestVersionListEither.right().value()); + } + + List<Component> latestVersionList = latestVersionListEither.left().value(); + + if (latestVersionList.isEmpty()) { + return Either.right(StorageOperationStatus.NOT_FOUND); + } + Component component = latestVersionList.size() == 1 ? latestVersionList.get(0) : latestVersionList.stream().max((c1, c2) -> Double.compare(Double.parseDouble(c1.getVersion()), Double.parseDouble(c2.getVersion()))).get(); + + return Either.left(component); + } + + public Either<List<Resource>, StorageOperationStatus> getAllCertifiedResources(boolean isAbstract, Boolean isHighest) { + + List<Resource> resources = new ArrayList<>(); + Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); + + propertiesToMatch.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract); + if (isHighest != null) { + propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, isHighest.booleanValue()); + } + propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.RESOURCE.name()); + propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); + + Either<List<GraphVertex>, TitanOperationStatus> getResourcesRes = titanDao.getByCriteria(null, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll); + + if (getResourcesRes.isRight()) { + log.debug("Failed to fetch all certified resources. Status is {}", getResourcesRes.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getResourcesRes.right().value())); + } + List<GraphVertex> resourceVerticies = getResourcesRes.left().value(); + for (GraphVertex resourceV : resourceVerticies) { + Either<Resource, StorageOperationStatus> getResourceRes = getToscaElement(resourceV); + if (getResourceRes.isRight()) { + return Either.right(getResourceRes.right().value()); + } + resources.add(getResourceRes.left().value()); + } + return Either.left(resources); + } + + public <T extends Component> Either<T, StorageOperationStatus> getLatestByNameAndVersion(String name, String version, JsonParseFlagEnum parseFlag) { + Either<T, StorageOperationStatus> result; + + Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class); + Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class); + + hasProperties.put(GraphPropertyEnum.NAME, name); + hasProperties.put(GraphPropertyEnum.VERSION, version); + hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + + hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true); + + Either<List<GraphVertex>, TitanOperationStatus> getResourceRes = titanDao.getByCriteria(null, hasProperties, hasNotProperties, parseFlag); + if (getResourceRes.isRight()) { + TitanOperationStatus status = getResourceRes.right().value(); + log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + return result; + } + return getToscaElementByOperation(getResourceRes.left().value().get(0)); + } + + public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName) { + return getLatestComponentByCsarOrName(componentType, csarUUID, systemName, false, JsonParseFlagEnum.ParseAll); + } + + public Either<Resource, StorageOperationStatus> getLatestComponentByCsarOrName(ComponentTypeEnum componentType, String csarUUID, String systemName, boolean allowDeleted, JsonParseFlagEnum parseFlag) { + Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class); + props.put(GraphPropertyEnum.CSAR_UUID, csarUUID); + props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + if (componentType != null) { + props.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name()); + } + Map<GraphPropertyEnum, Object> propsHasNot = new EnumMap<>(GraphPropertyEnum.class); + propsHasNot.put(GraphPropertyEnum.IS_DELETED, true); + + GraphVertex resourceMetadataData = null; + List<GraphVertex> resourceMetadataDataList = null; + Either<List<GraphVertex>, TitanOperationStatus> byCsar = titanDao.getByCriteria(null, props, propsHasNot, JsonParseFlagEnum.ParseMetadata); + if (byCsar.isRight()) { + if (TitanOperationStatus.NOT_FOUND == byCsar.right().value()) { + // Fix Defect DE256036 + if (StringUtils.isEmpty(systemName)) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.NOT_FOUND)); + } + + props.clear(); + props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + props.put(GraphPropertyEnum.SYSTEM_NAME, systemName); + Either<List<GraphVertex>, TitanOperationStatus> bySystemname = titanDao.getByCriteria(null, props, JsonParseFlagEnum.ParseMetadata); + if (bySystemname.isRight()) { + log.debug("getLatestResourceByCsarOrName - Failed to find by system name {} error {} ", systemName, bySystemname.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(bySystemname.right().value())); + } + if (bySystemname.left().value().size() > 2) { + log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) must return only 2 latest version, but was returned - {}", bySystemname.left().value().size()); + return Either.right(StorageOperationStatus.GENERAL_ERROR); + } + resourceMetadataDataList = bySystemname.left().value(); + if (resourceMetadataDataList.size() == 1) { + resourceMetadataData = resourceMetadataDataList.get(0); + } else { + for (GraphVertex curResource : resourceMetadataDataList) { + if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) { + resourceMetadataData = curResource; + break; + } + } + } + if (resourceMetadataData == null) { + log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) returned 2 latest CERTIFIED versions"); + return Either.right(StorageOperationStatus.GENERAL_ERROR); + } + if (resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID) != null && !((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID)).equals(csarUUID)) { + log.debug("getLatestResourceByCsarOrName - same system name {} but different csarUUID. exist {} and new {} ", systemName, resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID), csarUUID); + // correct error will be returned from create flow. with all + // correct audit records!!!!! + return Either.right(StorageOperationStatus.NOT_FOUND); + } + Either<Resource, StorageOperationStatus> resource = getToscaElement((String) resourceMetadataData.getUniqueId()); + return resource; + } + } else { + resourceMetadataDataList = byCsar.left().value(); + if (resourceMetadataDataList.size() > 2) { + log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) must return only 2 latest version, but was returned - {}", byCsar.left().value().size()); + return Either.right(StorageOperationStatus.GENERAL_ERROR); + } + if (resourceMetadataDataList.size() == 1) { + resourceMetadataData = resourceMetadataDataList.get(0); + } else { + for (GraphVertex curResource : resourceMetadataDataList) { + if (!((String) curResource.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals("CERTIFIED")) { + resourceMetadataData = curResource; + break; + } + } + } + if (resourceMetadataData == null) { + log.debug("getLatestResourceByCsarOrName - getByCriteria(by csar) returned 2 latest CERTIFIED versions"); + return Either.right(StorageOperationStatus.GENERAL_ERROR); + } + Either<Resource, StorageOperationStatus> resource = getToscaElement((String) resourceMetadataData.getJsonMetadataField(JsonPresentationFields.UNIQUE_ID), parseFlag); + return resource; + } + return null; + } + + public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends) { + + String currentTemplateNameChecked = templateNameExtends; + + while (currentTemplateNameChecked != null && !currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) { + Either<Resource, StorageOperationStatus> latestByToscaResourceName = getLatestByToscaResourceName(currentTemplateNameChecked); + + if (latestByToscaResourceName.isRight()) { + return latestByToscaResourceName.right().value() == StorageOperationStatus.NOT_FOUND ? Either.left(false) : Either.right(latestByToscaResourceName.right().value()); + } + + Resource value = latestByToscaResourceName.left().value(); + + if (value.getDerivedFrom() != null) { + currentTemplateNameChecked = value.getDerivedFrom().get(0); + } else { + currentTemplateNameChecked = null; + } + } + + return (currentTemplateNameChecked != null && currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) ? Either.left(true) : Either.left(false); + } + + public Either<List<Component>, StorageOperationStatus> fetchByResourceType(String resourceType) { + + Map<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class); + props.put(GraphPropertyEnum.RESOURCE_TYPE, resourceType); + props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true); + Either<List<GraphVertex>, TitanOperationStatus> resourcesByTypeEither = titanDao.getByCriteria(null, props); + + if (resourcesByTypeEither.isRight()) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resourcesByTypeEither.right().value())); + } + + List<GraphVertex> vertexList = resourcesByTypeEither.left().value(); + List<Component> components = new ArrayList<>(); + + for (GraphVertex vertex : vertexList) { + components.add(getToscaElementByOperation(vertex).left().value()); + } + + return Either.left(components); + + } + + public void commit() { + titanDao.commit(); + } + + public Either<Service, StorageOperationStatus> updateDistributionStatus(Service service, User user, DistributionStatusEnum distributionStatus) { + Either<GraphVertex, StorageOperationStatus> updateDistributionStatus = topologyTemplateOperation.updateDistributionStatus(service.getUniqueId(), user, distributionStatus); + if ( updateDistributionStatus.isRight() ){ + return Either.right(updateDistributionStatus.right().value()); + } + GraphVertex serviceV = updateDistributionStatus.left().value(); + service.setDistributionStatus(distributionStatus); + service.setLastUpdateDate((Long) serviceV.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE)); + return Either.left(service); + } + + public Either<ComponentMetadataData, StorageOperationStatus> updateComponentLastUpdateDateOnGraph(Component component, Long modificationTime) { + + Either<ComponentMetadataData, StorageOperationStatus> result = null; + GraphVertex serviceVertex; + Either<GraphVertex, TitanOperationStatus> updateRes = null; + Either<GraphVertex, TitanOperationStatus> getRes = titanDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.ParseMetadata); + if (getRes.isRight()) { + TitanOperationStatus status = getRes.right().value(); + log.error("Failed to fetch component {}. status is {}", component.getUniqueId(), status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + if (result == null) { + serviceVertex = getRes.left().value(); + long lastUpdateDate = System.currentTimeMillis(); + serviceVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate); + component.setLastUpdateDate(lastUpdateDate); + updateRes = titanDao.updateVertex(serviceVertex); + if (updateRes.isRight()) { + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateRes.right().value())); + } + } + if (result == null) { + result = Either.left(ModelConverter.convertToComponentMetadata(updateRes.left().value())); + } + return result; + } + + public TitanDao getTitanDao() { + return titanDao; + } + + public Either<List<Service>, StorageOperationStatus> getCertifiedServicesWithDistStatus(Set<DistributionStatusEnum> distStatus) { + Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + propertiesToMatch.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name()); + + return getServicesWithDistStatus(distStatus, propertiesToMatch); + } + + public Either<List<Service>, StorageOperationStatus> getServicesWithDistStatus(Set<DistributionStatusEnum> distStatus, Map<GraphPropertyEnum, Object> additionalPropertiesToMatch) { + + List<Service> servicesAll = new ArrayList<>(); + + Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class); + Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class); + + if(additionalPropertiesToMatch != null && !additionalPropertiesToMatch.isEmpty()) { + propertiesToMatch.putAll(additionalPropertiesToMatch); + } + + propertiesToMatch.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name()); + + propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true); + + if (distStatus != null && !distStatus.isEmpty()) { + for (DistributionStatusEnum state : distStatus) { + propertiesToMatch.put(GraphPropertyEnum.DISTRIBUTION_STATUS, state.name()); + Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria = fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch); + if ( fetchServicesByCriteria.isRight() ){ + return fetchServicesByCriteria; + } + else{ + servicesAll = fetchServicesByCriteria.left().value(); + } + } + return Either.left(servicesAll); + } else { + return fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch); + } + } + + private Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria(List<Service> servicesAll, Map<GraphPropertyEnum, Object> propertiesToMatch, Map<GraphPropertyEnum, Object> propertiesNotToMatch) { + Either<List<GraphVertex>, TitanOperationStatus> getRes = titanDao.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll); + if (getRes.isRight()) { + if (getRes.right().value() != TitanOperationStatus.NOT_FOUND) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified services by match properties {} not match properties {} . Status is {}. ", propertiesToMatch, propertiesNotToMatch, getRes.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getRes.right().value())); + } + } else { + for (GraphVertex vertex : getRes.left().value()) { + Either<Component, StorageOperationStatus> getServiceRes = getToscaElementByOperation(vertex); + if (getServiceRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch certified service {}. Status is {}. ", vertex.getJsonMetadataField(JsonPresentationFields.NAME), getServiceRes.right().value()); + return Either.right(getServiceRes.right().value()); + } else { + servicesAll.add((Service) getToscaElementByOperation(vertex).left().value()); + } + } + } + return Either.left(servicesAll); + } + + public void rollback() { + titanDao.rollback(); + } + + public StorageOperationStatus addDeploymentArtifactsToInstance(String componentId, ComponentInstance componentInstance, Map<String, ArtifactDefinition> finalDeploymentArtifacts) { + Map<String, ArtifactDataDefinition> instDeplArtifacts = finalDeploymentArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); + + return nodeTemplateOperation.addDeploymentArtifactsToInstance(componentId, componentInstance.getUniqueId(), instDeplArtifacts); + } + + public StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId) { + return nodeTemplateOperation.generateCustomizationUUIDOnInstance(componentId, instanceId); + } + + public StorageOperationStatus generateCustomizationUUIDOnInstanceGroup(String componentId, String instanceId, List<String> groupInstances) { + return nodeTemplateOperation.generateCustomizationUUIDOnInstanceGroup(componentId, instanceId, groupInstances); + } + + public Either<PropertyDefinition, StorageOperationStatus> addPropertyToResource(String propertyName, PropertyDefinition newPropertyDefinition, Resource resource) { + + Either<PropertyDefinition, StorageOperationStatus> result = null; + Either<Component, StorageOperationStatus> getUpdatedComponentRes = null; + newPropertyDefinition.setName(propertyName); + newPropertyDefinition.setParentUniqueId(resource.getUniqueId()); + StorageOperationStatus status = getToscaElementOperation(resource).addToscaDataToToscaElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", propertyName, resource.getName(), status); + result = Either.right(status); + } + if (result == null) { + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreProperties(false); + getUpdatedComponentRes = getToscaElement(resource.getUniqueId(), filter); + if (getUpdatedComponentRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", resource.getUniqueId(), getUpdatedComponentRes.right().value()); + result = Either.right(status); + } + } + if (result == null) { + PropertyDefinition newProperty = null; + List<PropertyDefinition> properties = ((Resource) getUpdatedComponentRes.left().value()).getProperties(); + if (CollectionUtils.isNotEmpty(properties)) { + Optional<PropertyDefinition> newPropertyOptional = properties.stream().filter(p -> p.getName().equals(propertyName)).findAny(); + if (newPropertyOptional.isPresent()) { + newProperty = newPropertyOptional.get(); + } + } + if (newProperty == null) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", propertyName, resource.getUniqueId(), StorageOperationStatus.NOT_FOUND); + result = Either.right(StorageOperationStatus.NOT_FOUND); + } else { + result = Either.left(newProperty); + } + } + return result; + } + + public StorageOperationStatus deletePropertyOfResource(Resource resource, String propertyName) { + return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, propertyName, JsonPresentationFields.NAME); + } + + public StorageOperationStatus deleteAttributeOfResource(Component component, String attributeName) { + return getToscaElementOperation(component).deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, attributeName, JsonPresentationFields.NAME); + } + + public StorageOperationStatus deleteInputOfResource(Component resource, String inputName) { + return getToscaElementOperation(resource).deleteToscaDataElement(resource.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, inputName, JsonPresentationFields.NAME); + } + + public Either<PropertyDefinition, StorageOperationStatus> updatePropertyOfResource(Resource resource, PropertyDefinition newPropertyDefinition) { + + Either<Component, StorageOperationStatus> getUpdatedComponentRes = null; + Either<PropertyDefinition, StorageOperationStatus> result = null; + StorageOperationStatus status = getToscaElementOperation(resource).updateToscaDataOfToscaElement(resource.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newPropertyDefinition.getName(), resource.getName(), status); + result = Either.right(status); + } + if (result == null) { + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreProperties(false); + getUpdatedComponentRes = getToscaElement(resource.getUniqueId(), filter); + if (getUpdatedComponentRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", resource.getUniqueId(), getUpdatedComponentRes.right().value()); + result = Either.right(status); + } + } + if (result == null) { + Optional<PropertyDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getProperties().stream().filter(p -> p.getName().equals(newPropertyDefinition.getName())).findAny(); + if (newProperty.isPresent()) { + result = Either.left(newProperty.get()); + } else { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newPropertyDefinition.getName(), resource.getUniqueId(), StorageOperationStatus.NOT_FOUND); + result = Either.right(StorageOperationStatus.NOT_FOUND); + } + } + return result; + } + + public Either<AttributeDefinition, StorageOperationStatus> addAttributeOfResource(Component component, AttributeDefinition newAttributeDef) { + + Either<Component, StorageOperationStatus> getUpdatedComponentRes = null; + Either<AttributeDefinition, 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<AttributeDefinition> 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<AttributeDefinition, StorageOperationStatus> updateAttributeOfResource(Component component, AttributeDefinition newAttributeDef) { + + Either<Component, StorageOperationStatus> getUpdatedComponentRes = null; + Either<AttributeDefinition, 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<AttributeDefinition> newProperty = ((Resource) getUpdatedComponentRes.left().value()).getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny(); + if (newProperty.isPresent()) { + result = Either.left(newProperty.get()); + } else { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newAttributeDef.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND); + result = Either.right(StorageOperationStatus.NOT_FOUND); + } + } + return result; + } + + public Either<InputDefinition, StorageOperationStatus> updateInputOfComponent(Component component, InputDefinition newInputDefinition) { + + Either<Component, StorageOperationStatus> getUpdatedComponentRes = null; + Either<InputDefinition, StorageOperationStatus> result = null; + StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.INPUTS, VertexTypeEnum.INPUTS, newInputDefinition, JsonPresentationFields.NAME); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the input {} to the component {}. Status is {}. ", newInputDefinition.getName(), component.getName(), status); + result = Either.right(status); + } + if (result == null) { + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreInputs(false); + getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter); + if (getUpdatedComponentRes.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value()); + result = Either.right(status); + } + } + if (result == null) { + Optional<InputDefinition> updatedInput = getUpdatedComponentRes.left().value().getInputs().stream().filter(p -> p.getName().equals(newInputDefinition.getName())).findAny(); + if (updatedInput.isPresent()) { + result = Either.left(updatedInput.get()); + } else { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently updated inputs {} on the resource {}. Status is {}. ", newInputDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND); + result = Either.right(StorageOperationStatus.NOT_FOUND); + } + } + return result; + } + + public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupDefinition> groups, Map<String, List<ArtifactDefinition>> groupInstancesArtifacts) { + return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groups, groupInstancesArtifacts); + } + + public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsOnComponent(Component component, ComponentTypeEnum componentType, List<GroupDataDefinition> updatedGroups) { + return groupsOperation.updateGroups(component, componentType, updatedGroups); + } + + public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstancesOnComponent(Component component, ComponentTypeEnum componentType, String instanceId, List<GroupInstance> updatedGroupInstances) { + return groupsOperation.updateGroupInstances(component, componentType, instanceId, updatedGroupInstances); + } + + public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupInstance> groupInstances) { + return nodeTemplateOperation.addGroupInstancesToComponentInstance(containerComponent, componentInstance, groupInstances); + } + + public StorageOperationStatus addDeploymentArtifactsToComponentInstance(Component containerComponent, ComponentInstance componentInstance, Map<String, ArtifactDefinition> deploymentArtifacts) { + return nodeTemplateOperation.addDeploymentArtifactsToComponentInstance(containerComponent, componentInstance, deploymentArtifacts); + } + + public StorageOperationStatus updateComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) { + return nodeTemplateOperation.updateComponentInstanceProperty(containerComponent, componentInstanceId, property); + } + + public StorageOperationStatus addComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) { + return nodeTemplateOperation.addComponentInstanceProperty(containerComponent, componentInstanceId, property); + } + + public StorageOperationStatus updateComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) { + return nodeTemplateOperation.updateComponentInstanceInput(containerComponent, componentInstanceId, property); + } + + public StorageOperationStatus addComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) { + return nodeTemplateOperation.addComponentInstanceInput(containerComponent, componentInstanceId, property); + } + + public void setNodeTypeOperation(NodeTypeOperation nodeTypeOperation) { + this.nodeTypeOperation = nodeTypeOperation; + } + + public void setTopologyTemplateOperation(TopologyTemplateOperation topologyTemplateOperation) { + this.topologyTemplateOperation = topologyTemplateOperation; + } + +} 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 new file mode 100644 index 0000000000..07845c8ea5 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/ModelConverter.java @@ -0,0 +1,1258 @@ +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 org.apache.commons.collections.CollectionUtils; +import org.apache.commons.collections.MapUtils; +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.*; +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.AttributeDefinition; +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.ComponentInstanceAttribute; +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.PropertyDefinition; +import org.openecomp.sdc.be.model.RelationshipImpl; +import org.openecomp.sdc.be.model.RequirementAndRelationshipPair; +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.jsontitan.datamodel.NodeType; +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.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 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; + } + + private static boolean isAtomicComponent(ResourceTypeEnum resourceType) { + if (resourceType == null || resourceType == ResourceTypeEnum.VF) + return false; + return true; + } + + private static Service convertToService(ToscaElement toscaElement) { + Service service = new Service(); + convertComponentFields(service, toscaElement); + + convertServiceSpecificFields(toscaElement, service); + + TopologyTemplate topologyTemplate = (TopologyTemplate) toscaElement; + + convertComponentInstances(topologyTemplate, service); + + convertInputs(topologyTemplate, service); + + convertRelations(topologyTemplate, service); + + convertArtifacts(topologyTemplate, service); + + convertServiceApiArtifacts(topologyTemplate, 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)); + } + + 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); + + } else { + TopologyTemplate topologyTemplate = (TopologyTemplate) toscaElement; + if (resource.getResourceType() == ResourceTypeEnum.VF) { + 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)); + + } + convertComponentInstances(topologyTemplate, resource); + convertRelations(topologyTemplate, resource); + convertInputs(topologyTemplate, resource); + convertGroups(topologyTemplate, resource); + } + convertArtifacts(toscaElement, resource); + convertAdditionalInformation(toscaElement, resource); + + return resource; + } + + private static void convertAttributes(NodeType nodeType, Resource resource) { + Map<String, AttributeDataDefinition> attributes = nodeType.getAttributes(); + if (attributes != null) { + List<AttributeDefinition> attrs = attributes.values().stream().map(dataDef -> ModelConverter.fromDataDefinition(resource.getUniqueId(), dataDef)).collect(Collectors.toList()); + resource.setAttributes(attrs); + } + } + + private static AttributeDefinition fromDataDefinition(String resourceId, AttributeDataDefinition dataDefinition) { + AttributeDefinition attributeDefinition = new AttributeDefinition(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); + } + } + + /** + * 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())) { + + setComponentInstancesAttributesToComponent(topologyTemplate, component); + + setComponentInstancesPropertiesToComponent(topologyTemplate, component); + + setComponentInstancesInputsToComponent(topologyTemplate, component); + + setComponentInstancesToComponent(topologyTemplate, component); + + setComponentInstancesCapabilitiesToComponentAndCI(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()); + List<RequirementAndRelationshipPair> relationships = new ArrayList<>(); + RequirementAndRelationshipPair relationshipPair = new RequirementAndRelationshipPair(); + relationshipPair.setId(relation.getUniqueId()); + + relationshipPair.setCapabilityOwnerId(relation.getCapabilityOwnerId()); + relationshipPair.setCapabilityUid(relation.getCapabiltyId()); + relationshipPair.setRequirementOwnerId(relation.getRequirementOwnerId()); + relationshipPair.setRequirementUid(relation.getRequirementId()); + relationshipPair.setRequirement(relation.getRequirement()); + RelationshipImpl relationship = new RelationshipImpl(); + relationship.setType(relation.getType()); + relationshipPair.setRelationships(relationship); + + relationships.add(relationshipPair); + requirementCapabilityRelDef.setRelationships(relationships); + return requirementCapabilityRelDef; + } + + public static List<RelationshipInstDataDefinition> convertRelationToToscaRelation(RequirementCapabilityRelDef relation) { + + List<RelationshipInstDataDefinition> relationsList = new ArrayList<>(); + + List<RequirementAndRelationshipPair> relationship = relation.getRelationships(); + relationship.forEach(p -> { + RelationshipInstDataDefinition requirementCapabilityRelDef = new RelationshipInstDataDefinition(); + requirementCapabilityRelDef.setFromId(relation.getFromNode()); + requirementCapabilityRelDef.setToId(relation.getToNode()); + requirementCapabilityRelDef.setUniqueId(p.getId()); + requirementCapabilityRelDef.setCapabilityOwnerId(p.getCapabilityOwnerId()); + requirementCapabilityRelDef.setCapabiltyId(p.getCapabilityUid()); + requirementCapabilityRelDef.setRequirementOwnerId(p.getRequirementOwnerId()); + requirementCapabilityRelDef.setRequirementId(p.getRequirementUid()); + requirementCapabilityRelDef.setRequirement(p.getRequirement()); + requirementCapabilityRelDef.setType(p.getRelationship().getType()); + requirementCapabilityRelDef.setCapability(p.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); + } + + public static MapCapabiltyProperty convertToMapOfMapCapabiltyProperties(Map<String, List<CapabilityDefinition>> instCapabilities, String instanceId, boolean fromCsar) { + + Map<String, MapPropertiesDataDefinition> toscaCapPropMap = new HashMap<>(); + + instCapabilities.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)); + } + // 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(), 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); + } + + private static void convertRequirements(TopologyTemplate toscaElement, Component component) { + + if (CollectionUtils.isNotEmpty(component.getComponentInstances())) { + for (ComponentInstance instance : component.getComponentInstances()) { + Map<String, List<RequirementDefinition>> instanceRequirements = instance.getRequirements(); + if (MapUtils.isNotEmpty(instanceRequirements)) { + addRequirementsByInstanceId(instance.getUniqueId(), instanceRequirements, component); + } + } + } + } + + private static void addRequirementsByInstanceId(String instanceId, Map<String, List<RequirementDefinition>> instanceRequirementsMap, Component component) { + + if (component.getCapabilities() == null) { + component.setCapabilities(new HashMap<>()); + } + List<RequirementDefinition> instanceRequirements = new ArrayList<>(); + for (List<RequirementDefinition> instRequirements : instanceRequirementsMap.values()) { + instanceRequirements.addAll(instRequirements); + } + component.getRequirements().put(instanceId, instanceRequirements); + } + + private static void convertCapabilities(TopologyTemplate toscaElement, Component component) { + + if (CollectionUtils.isNotEmpty(component.getComponentInstances())) { + for (ComponentInstance instance : component.getComponentInstances()) { + Map<String, List<CapabilityDefinition>> instanceCapabilities = instance.getCapabilities(); + if (MapUtils.isNotEmpty(instanceCapabilities)) { + addCapabilitiesByInstanceId(instance.getUniqueId(), instanceCapabilities, component); + } + } + } + } + + private static void addCapabilitiesByInstanceId(String instanceId, Map<String, List<CapabilityDefinition>> instanceCapabilitiesMap, Component component) { + + if (component.getCapabilities() == null) { + component.setCapabilities(new HashMap<>()); + } + List<CapabilityDefinition> instanceCapabilities = new ArrayList<>(); + for (List<CapabilityDefinition> instCapabilitis : instanceCapabilitiesMap.values()) { + instanceCapabilities.addAll(instCapabilitis); + } + component.getCapabilities().put(instanceId, instanceCapabilities); + } + + @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)); + } + 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 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) { + + 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); + + 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<AttributeDefinition> attributes = component.getAttributes(); + if (attributes != null) { + Map<String, AttributeDataDefinition> attrsByName = attributes.stream().map(AttributeDataDefinition::new).collect(Collectors.toMap(AttributeDataDefinition::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); + } + } + + } + + } + }); + } + + 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 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 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()); + } + 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); + convertRequirements(component, topologyTemplate); + convertRelationsToComposition(component, topologyTemplate); + + return topologyTemplate; + } + + private static void convertServiceSpecificEntities(Service service, TopologyTemplate topologyTemplate) { + convertServiceMetaData(service, topologyTemplate); + convertServiceApiArtifacts(service, topologyTemplate); + } + + private static void convertServiceMetaData(Service service, TopologyTemplate topologyTemplate) { + if (service.getDistributionStatus() != null) { + 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.NAMING_POLICY, service.getNamingPolicy()); + + } + + 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()); + } + 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 boolean isAtomicComponent(Component component) { + ComponentTypeEnum componentType = component.getComponentType(); + if (!componentType.equals(ComponentTypeEnum.RESOURCE)) { + return false; + } + Resource resource = (Resource) component; + ResourceTypeEnum resType = resource.getResourceType(); + if (resType == ResourceTypeEnum.VFC || resType == ResourceTypeEnum.VFCMT || resType == ResourceTypeEnum.VL || resType == ResourceTypeEnum.CP || resType == ResourceTypeEnum.ABSTRACT) { + return true; + } + return false; + } + + 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<ComponentInstanceAttribute>> attributes = new HashMap<>(); + for (Map.Entry<String, MapAttributesDataDefinition> entry : topologyTemplate.getInstAttributes().entrySet()) { + if (entry.getValue() != null && entry.getValue().getMapToscaDataDefinition() != null) { + String key = entry.getKey(); + List<ComponentInstanceAttribute> componentInstanceAttributes = entry.getValue().getMapToscaDataDefinition().entrySet().stream().map(e -> new ComponentInstanceAttribute(new AttributeDefinition(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(); + + 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); + } + } + + private static void setComponentInstancesCapabilitiesToComponentAndCI(TopologyTemplate topologyTemplate, Component component) { + Map<String, MapCapabiltyProperty> 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, 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); + } + if (MapUtils.isEmpty(instancesMap.get(instanceId).getCapabilities())) { + instancesMap.get(instanceId).setCapabilities(new HashMap<>()); + } + instancesMap.get(instanceId).getCapabilities().put(capabilityType, new ArrayList<>(caps)); + } + } + component.setCapabilities(instancesCapabilities); + } + } + + 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); + } + } + } + } + }); + } + } + 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<>()); + MapAttributesDataDefinition attributesMap; + for (Entry<String, List<ComponentInstanceAttribute>> entry : component.getComponentInstancesAttributes().entrySet()) { + attributesMap = new MapAttributesDataDefinition(); + + attributesMap.setMapToscaDataDefinition(entry.getValue().stream().map(e -> new AttributeDataDefinition(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)); + } + return metadata; + } + + public static List<GroupDefinition> convertToGroupDefinitions(Map<String, GroupDataDefinition> groups) { + + List<GroupDefinition> groupDefinitions = null; + if (MapUtils.isNotEmpty(groups)) { + groupDefinitions = groups.values().stream().map(g -> new GroupDefinition(g)).collect(Collectors.toList()); + } + /* + * if (CollectionUtils.isNotEmpty(groupDefinitions) && MapUtils.isNotEmpty(groupsProperties)) { for (GroupDefinition groupDefinition : groupDefinitions) { if (groupsProperties.containsKey(groupDefinition.getName())) { Map<String, + * PropertyDataDefinition> properties = groupsProperties.get(groupDefinition.getName()).getMapToscaDataDefinition(); if (MapUtils.isNotEmpty(properties)) { groupDefinition.setProperties(properties.values().stream().map(p -> new + * GroupProperty(p)).collect(Collectors.toList())); } } } } + */ + return groupDefinitions; + } + +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IAdditionalInformationOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IAdditionalInformationOperation.java index 71167c395f..eb6492fa84 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IAdditionalInformationOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IAdditionalInformationOperation.java @@ -23,8 +23,8 @@ package org.openecomp.sdc.be.model.operations.api; import java.util.List; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.model.AdditionalInfoParameterInfo; import org.openecomp.sdc.be.model.AdditionalInformationDefinition; import org.openecomp.sdc.be.resources.data.AdditionalInfoParameterData; @@ -35,60 +35,42 @@ import fj.data.Either; public interface IAdditionalInformationOperation { - public Either<AdditionalInformationDefinition, TitanOperationStatus> addAdditionalInformationParameter( - NodeTypeEnum nodeType, String resourceId, String key, String value); + public Either<AdditionalInformationDefinition, TitanOperationStatus> addAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String key, String value); - public Either<AdditionalInformationDefinition, TitanOperationStatus> updateAdditionalInformationParameter( - NodeTypeEnum nodeType, String resourceId, String origKey, String key, String value); + public Either<AdditionalInformationDefinition, TitanOperationStatus> updateAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String origKey, String key, String value); - public Either<AdditionalInformationDefinition, TitanOperationStatus> deleteAdditionalInformationParameter( - NodeTypeEnum nodeType, String resourceId, String key); + public Either<AdditionalInformationDefinition, TitanOperationStatus> deleteAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String key); - public Either<AdditionalInfoParameterData, TitanOperationStatus> addAdditionalInformationNode(NodeTypeEnum nodeType, - String resourceUniqueId); + public Either<AdditionalInfoParameterData, TitanOperationStatus> addAdditionalInformationNode(NodeTypeEnum nodeType, String resourceUniqueId); - public Either<AdditionalInformationDefinition, TitanOperationStatus> addAdditionalInformationNode( - NodeTypeEnum nodeType, String componentId, AdditionalInformationDefinition parameters); + public Either<AdditionalInformationDefinition, TitanOperationStatus> addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId, AdditionalInformationDefinition parameters); - public TitanOperationStatus findResourceAllAdditionalInformationRecursively(String uniqueId, - List<AdditionalInformationDefinition> properties); + public TitanOperationStatus findResourceAllAdditionalInformationRecursively(String uniqueId, List<AdditionalInformationDefinition> properties); - public TitanOperationStatus findServiceAllAdditionalInformationRecursively(String uniqueId, - List<AdditionalInformationDefinition> properties); + public TitanOperationStatus findServiceAllAdditionalInformationRecursively(String uniqueId, List<AdditionalInformationDefinition> properties); - public Either<AdditionalInformationDefinition, StorageOperationStatus> createAdditionalInformationParameter( - NodeTypeEnum nodeType, String resourceId, String key, String value, boolean inTransaction); + public Either<AdditionalInformationDefinition, StorageOperationStatus> createAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String key, String value, boolean inTransaction); - public Either<AdditionalInformationDefinition, StorageOperationStatus> updateAdditionalInformationParameter( - NodeTypeEnum nodeType, String resourceId, String id, String key, String value, boolean inTransaction); + public Either<AdditionalInformationDefinition, StorageOperationStatus> updateAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String id, String key, String value, boolean inTransaction); - public Either<AdditionalInformationDefinition, StorageOperationStatus> deleteAdditionalInformationParameter( - NodeTypeEnum nodeType, String resourceId, String id, boolean inTransaction); + public Either<AdditionalInformationDefinition, StorageOperationStatus> deleteAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String id, boolean inTransaction); - public Either<Integer, StorageOperationStatus> getNumberOfAdditionalInformationParameters(NodeTypeEnum nodeType, - String resourceId, boolean inTransaction); + public Either<Integer, StorageOperationStatus> getNumberOfAdditionalInformationParameters(NodeTypeEnum nodeType, String resourceId, boolean inTransaction); public Either<Integer, TitanOperationStatus> getNumberOfParameters(NodeTypeEnum nodeType, String resourceId); - public Either<AdditionalInfoParameterInfo, TitanOperationStatus> getAdditionalInformationParameter( - NodeTypeEnum nodeType, String resourceId, String id); + public Either<AdditionalInfoParameterInfo, TitanOperationStatus> getAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String id); - public Either<AdditionalInfoParameterInfo, StorageOperationStatus> getAdditionalInformationParameter( - NodeTypeEnum nodeType, String resourceId, String id, boolean inTransaction); + public Either<AdditionalInfoParameterInfo, StorageOperationStatus> getAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String id, boolean inTransaction); - public Either<AdditionalInformationDefinition, TitanOperationStatus> getAllAdditionalInformationParameters( - NodeTypeEnum nodeType, String resourceId, boolean ignoreVerification); + public Either<AdditionalInformationDefinition, TitanOperationStatus> getAllAdditionalInformationParameters(NodeTypeEnum nodeType, String resourceId, boolean ignoreVerification); - public Either<AdditionalInformationDefinition, StorageOperationStatus> getAllAdditionalInformationParameters( - NodeTypeEnum nodeType, String resourceId, boolean ignoreVerification, boolean inTransaction); + public Either<AdditionalInformationDefinition, StorageOperationStatus> getAllAdditionalInformationParameters(NodeTypeEnum nodeType, String resourceId, boolean ignoreVerification, boolean inTransaction); - public Either<AdditionalInformationDefinition, StorageOperationStatus> deleteAllAdditionalInformationParameters( - NodeTypeEnum nodeType, String resourceId, boolean inTransaction); + public Either<AdditionalInformationDefinition, StorageOperationStatus> deleteAllAdditionalInformationParameters(NodeTypeEnum nodeType, String resourceId, boolean inTransaction); - public Either<TitanVertex, TitanOperationStatus> addAdditionalInformationNode(NodeTypeEnum nodeType, - String componentId, TitanVertex matadatVertex); + public Either<TitanVertex, TitanOperationStatus> addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId, TitanVertex matadatVertex); - public TitanOperationStatus addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId, - AdditionalInformationDefinition parameters, TitanVertex metadataVertex); + public TitanOperationStatus addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId, AdditionalInformationDefinition parameters, TitanVertex metadataVertex); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IArtifactOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IArtifactOperation.java index 873d05e1ed..5e8a2eb0d5 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IArtifactOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IArtifactOperation.java @@ -23,12 +23,12 @@ package org.openecomp.sdc.be.model.operations.api; import java.util.Map; import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.resources.data.ArtifactData; -import com.thinkaurelius.titan.core.TitanTransaction; import com.thinkaurelius.titan.core.TitanVertex; import fj.data.Either; @@ -51,7 +51,7 @@ public interface IArtifactOperation { public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, boolean inTransaction, String groupType); - Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifactHeat, String parentId, NodeTypeEnum parentType, boolean inTransaction); + Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifactHeat, String parentId, NodeTypeEnum parentType, boolean failIfExist); public void updateUUID(ArtifactDataDefinition artifactData, String oldChecksum, String oldVesrion); @@ -61,10 +61,20 @@ public interface IArtifactOperation { public Either<ArtifactData, StorageOperationStatus> updateToscaArtifactNameOnGraph(ArtifactDefinition artifactInfo, String artifactId, NodeTypeEnum type, String id); + public StorageOperationStatus addArifactToComponent(ArtifactDefinition artifactInfo, String parentId, NodeTypeEnum type, boolean failIfExist, TitanVertex parentVertex); public Either<ArtifactData, StorageOperationStatus> getLatestArtifactDataByArtifactUUID(String artifactUUID, boolean inTransaction); StorageOperationStatus addArifactToComponent(TitanVertex artifactInfo, TitanVertex parentVertex, String label); + public Either<ArtifactData, TitanOperationStatus> removeArtifactOnGraph(String id, String artifactId, NodeTypeEnum type, boolean deleteMandatoryArtifact); + + public Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvPlaceholder(ArtifactDefinition artifactInfo, boolean inTransaction); + + public Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact( String id, ArtifactDefinition artifactEnvInfo, String oldArtifactId, String newArtifactId, NodeTypeEnum type, boolean inTransaction); + + public Either<ArtifactDefinition, StorageOperationStatus> getHeatEnvByGeneratedFromId(String generatedFromId); + + } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityInstanceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityInstanceOperation.java index e50b658121..f8e8c80f12 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityInstanceOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityInstanceOperation.java @@ -37,16 +37,14 @@ import com.thinkaurelius.titan.core.TitanVertex; import fj.data.Either; /** - * public interface ICapabilityInstanceOperation provides methods for CRUD - * operations for CapabilityInstance on component instance level + * public interface ICapabilityInstanceOperation provides methods for CRUD operations for CapabilityInstance on component instance level * * @author ns019t * */ public interface ICapabilityInstanceOperation { /** - * create capability instance of capability with property values for - * resource instance + * create capability instance of capability with property values for resource instance * * @param resourceInstanceId * @param capabilityId @@ -55,8 +53,7 @@ public interface ICapabilityInstanceOperation { * @param capabilityName * @return */ - public Either<Map<CapabilityInstData, List<PropertyValueData>>, TitanOperationStatus> createCapabilityInstanceOfCapabilityWithPropertyValuesForResourceInstance( - String resourceInstanceId, String capabilityId, String capabilityName, + public Either<Map<CapabilityInstData, List<PropertyValueData>>, TitanOperationStatus> createCapabilityInstanceOfCapabilityWithPropertyValuesForResourceInstance(String resourceInstanceId, String capabilityId, String capabilityName, List<ComponentInstanceProperty> propertyValues, boolean validateCapabilityInstExistance); /** @@ -68,8 +65,7 @@ public interface ICapabilityInstanceOperation { * @param validateCapabilityInstExistence * @return */ - public TitanOperationStatus createCapabilityInstanceOfCapabilityWithPropertyValuesForResourceInstance( - TitanVertex resourceInstanceVertex, String resourceInstanceId, String capabilityId, String capabilityName, + public TitanOperationStatus createCapabilityInstanceOfCapabilityWithPropertyValuesForResourceInstance(TitanVertex resourceInstanceVertex, String resourceInstanceId, String capabilityId, String capabilityName, List<ComponentInstanceProperty> propertyValues, boolean validateCapabilityInstExistence); /** @@ -79,8 +75,7 @@ public interface ICapabilityInstanceOperation { * @param capabilityId * @return */ - public Either<Boolean, TitanOperationStatus> validateCapabilityInstExistence(String resourceInstanceId, - String capabilityId); + public Either<Boolean, TitanOperationStatus> validateCapabilityInstExistence(String resourceInstanceId, String capabilityId); /** * delete capability instance from resource instance @@ -89,20 +84,16 @@ public interface ICapabilityInstanceOperation { * @param capabilityInstanceId * @return */ - public Either<CapabilityInstData, TitanOperationStatus> deleteCapabilityInstanceFromResourceInstance( - String resourceInstanceId, String capabilityInstanceId); + public Either<CapabilityInstData, TitanOperationStatus> deleteCapabilityInstanceFromResourceInstance(String resourceInstanceId, String capabilityInstanceId); /** - * get all capability instances for resource instance returns all Capability - * Instances related to Resource Instance as List<CapabilityInstData> or - * TitanOperationStatus if error occurs or if Resource Instance have no any - * related Capability Instance + * get all capability instances for resource instance returns all Capability Instances related to Resource Instance as List<CapabilityInstData> or TitanOperationStatus if error occurs or if Resource Instance have no any related Capability + * Instance * * @param resourceInstanceId * @return Either<List<CapabilityInstData>, TitanOperationStatus> */ - public Either<List<ImmutablePair<CapabilityInstData, GraphEdge>>, TitanOperationStatus> getAllCapabilityInstancesOfResourceInstance( - String resourceInstanceId); + public Either<List<ImmutablePair<CapabilityInstData, GraphEdge>>, TitanOperationStatus> getAllCapabilityInstancesOfResourceInstance(String resourceInstanceId); /** * get capability instance of capability for resource instance @@ -111,8 +102,7 @@ public interface ICapabilityInstanceOperation { * @param capabilityId * @return */ - public Either<CapabilityInstData, TitanOperationStatus> getCapabilityInstanceOfCapabilityOfResourceInstance( - String resourceInstanceId, String capabilityId); + public Either<CapabilityInstData, TitanOperationStatus> getCapabilityInstanceOfCapabilityOfResourceInstance(String resourceInstanceId, String capabilityId); /** * update capability property values @@ -123,8 +113,7 @@ public interface ICapabilityInstanceOperation { * @param capabilityId * @return */ - public Either<List<PropertyValueData>, TitanOperationStatus> updateCapabilityPropertyValues( - String resourceInstanceId, String capabilityId, List<ComponentInstanceProperty> propertyValues); + public Either<List<PropertyValueData>, TitanOperationStatus> updateCapabilityPropertyValues(String resourceInstanceId, String capabilityId, List<ComponentInstanceProperty> propertyValues); /** * clone and associate capability instance with property values @@ -134,10 +123,8 @@ public interface ICapabilityInstanceOperation { * @param capabilityInstPair * @return */ - public Either<ImmutablePair<CapabilityInstData, List<PropertyValueData>>, TitanOperationStatus> cloneAssociateCapabilityInstanceWithPropertyValues( - ComponentInstanceData createdComponentInstance, CapabilityDefinition capability, + public Either<ImmutablePair<CapabilityInstData, List<PropertyValueData>>, TitanOperationStatus> cloneAssociateCapabilityInstanceWithPropertyValues(ComponentInstanceData createdComponentInstance, CapabilityDefinition capability, ImmutablePair<CapabilityInstData, GraphEdge> capabilityInstPair); - Either<Boolean, TitanOperationStatus> validateCapabilityInstExistence(TitanVertex instanceVertex, - String resourceInstanceId, String capabilityId); + Either<Boolean, TitanOperationStatus> validateCapabilityInstExistence(TitanVertex instanceVertex, String resourceInstanceId, String capabilityId); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityOperation.java index 3b692b9607..b3be2bd6ee 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityOperation.java @@ -29,6 +29,7 @@ import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.model.CapabilityDefinition; import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.resources.data.CapabilityData; +import org.openecomp.sdc.be.resources.data.CapabilityTypeData; import org.openecomp.sdc.be.resources.data.PropertyData; import com.thinkaurelius.titan.core.TitanVertex; @@ -37,11 +38,9 @@ import fj.data.Either; public interface ICapabilityOperation { - public Either<CapabilityDefinition, StorageOperationStatus> addCapability(String resourceId, String capabilityName, - CapabilityDefinition capabilityDefinition); + public Either<CapabilityDefinition, StorageOperationStatus> addCapability(String resourceId, String capabilityName, CapabilityDefinition capabilityDefinition); - public Either<CapabilityDefinition, StorageOperationStatus> addCapability(String resourceId, String capabilityName, - CapabilityDefinition capabilityDefinition, boolean inTransaction); + public Either<CapabilityDefinition, StorageOperationStatus> addCapability(String resourceId, String capabilityName, CapabilityDefinition capabilityDefinition, boolean inTransaction); /** * @param uniqueId @@ -53,27 +52,22 @@ public interface ICapabilityOperation { public Either<CapabilityDefinition, StorageOperationStatus> getCapability(String capabilityName, String resourceId); - public Either<CapabilityDefinition, StorageOperationStatus> getCapability(String capabilityName, String resourceId, - boolean inTransaction); + public Either<CapabilityDefinition, StorageOperationStatus> getCapability(String capabilityName, String resourceId, boolean inTransaction); - public Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> getAllCapabilitiesPairs( - String resourceId); + public Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> getAllCapabilitiesPairs(String resourceId); - public Either<Map<String, CapabilityDefinition>, StorageOperationStatus> deleteAllCapabilities(String resourceId, - boolean inTransaction); + public Either<Map<String, CapabilityDefinition>, StorageOperationStatus> deleteAllCapabilities(String resourceId, boolean inTransaction); - public Either<CapabilityDefinition, TitanOperationStatus> getCapabilityByCapabilityData( - CapabilityData capabilityData); + public Either<CapabilityDefinition, TitanOperationStatus> getCapabilityByCapabilityData(CapabilityData capabilityData); public TitanOperationStatus getCapabilitySourcesList(String resourceId, List<String> derivedFromList); - public Either<Map<String, PropertyData>, StorageOperationStatus> updatePropertiesOfCapability(String uniqueId, - String capabilityType, List<PropertyDefinition> newProperties); + public Either<Map<String, PropertyData>, StorageOperationStatus> updatePropertiesOfCapability(String uniqueId, String capabilityType, List<PropertyDefinition> newProperties); - public Either<Map<String, PropertyData>, StorageOperationStatus> updatePropertiesOfCapability(String uniqueId, - String capabilityType, List<PropertyDefinition> newProperties, boolean inTransaction); + public Either<Map<String, PropertyData>, StorageOperationStatus> updatePropertiesOfCapability(String uniqueId, String capabilityType, List<PropertyDefinition> newProperties, boolean inTransaction); - StorageOperationStatus addCapability(TitanVertex metadataVertex, String resourceId, String capabilityName, - CapabilityDefinition capabilityDefinition, boolean inTransaction); + StorageOperationStatus addCapability(TitanVertex metadataVertex, String resourceId, String capabilityName, CapabilityDefinition capabilityDefinition, boolean inTransaction); + + Either<CapabilityTypeData, TitanOperationStatus> getCapabilityTypeOfCapability(String uniqueId); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityTypeOperation.java index 6f0b5b8d13..fa06b468db 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityTypeOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ICapabilityTypeOperation.java @@ -30,11 +30,9 @@ public interface ICapabilityTypeOperation { * @param capabilityTypeDefinition * @return */ - public Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType( - CapabilityTypeDefinition capabilityTypeDefinition); + public Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType(CapabilityTypeDefinition capabilityTypeDefinition); - public Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType( - CapabilityTypeDefinition capabilityTypeDefinition, boolean inTransaction); + public Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType(CapabilityTypeDefinition capabilityTypeDefinition, boolean inTransaction); /** * @param uniqueId @@ -42,6 +40,5 @@ public interface ICapabilityTypeOperation { */ public Either<CapabilityTypeDefinition, StorageOperationStatus> getCapabilityType(String uniqueId); - public Either<CapabilityTypeDefinition, StorageOperationStatus> getCapabilityType(String uniqueId, - boolean inTransaction); + public Either<CapabilityTypeDefinition, StorageOperationStatus> getCapabilityType(String uniqueId, boolean inTransaction); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IComponentInstanceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IComponentInstanceOperation.java index e51e077906..28e70ad127 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IComponentInstanceOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IComponentInstanceOperation.java @@ -24,6 +24,7 @@ import java.util.List; import java.util.Map; import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; @@ -34,8 +35,12 @@ import org.openecomp.sdc.be.model.ComponentInstanceInput; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.RequirementAndRelationshipPair; import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; +import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.resources.data.AttributeValueData; +import org.openecomp.sdc.be.resources.data.CapabilityData; import org.openecomp.sdc.be.resources.data.ComponentInstanceData; +import org.openecomp.sdc.be.resources.data.RequirementData; +import org.openecomp.sdc.exception.ResponseFormat; import fj.data.Either; @@ -52,9 +57,8 @@ public interface IComponentInstanceOperation { * @param inTransaction * @return */ - public Either<ComponentInstance, StorageOperationStatus> createComponentInstance(String containerComponentId, - NodeTypeEnum containerNodeType, String instanceNumber, ComponentInstance componentInstance, - NodeTypeEnum instNodeType, boolean inTransaction); + public Either<ComponentInstance, StorageOperationStatus> createComponentInstance(String containerComponentId, NodeTypeEnum containerNodeType, String instanceNumber, ComponentInstance componentInstance, NodeTypeEnum instNodeType, + boolean inTransaction); /** * add resource instance to service with internal transaction @@ -64,9 +68,7 @@ public interface IComponentInstanceOperation { * @param componentInstance * @return */ - public Either<ComponentInstance, StorageOperationStatus> createComponentInstance(String containerComponentId, - NodeTypeEnum containerNodeType, String instanceNumber, ComponentInstance componentInstance, - NodeTypeEnum instNodeType); + public Either<ComponentInstance, StorageOperationStatus> createComponentInstance(String containerComponentId, NodeTypeEnum containerNodeType, String instanceNumber, ComponentInstance componentInstance, NodeTypeEnum instNodeType); /** * delete resource instance from component @@ -78,11 +80,9 @@ public interface IComponentInstanceOperation { * @param inTransaction * @return */ - public Either<ComponentInstance, StorageOperationStatus> deleteComponentInstance(NodeTypeEnum containerNodeType, - String containerComponentId, String resourceInstUid, boolean inTransaction); + public Either<ComponentInstance, StorageOperationStatus> deleteComponentInstance(NodeTypeEnum containerNodeType, String containerComponentId, String resourceInstUid, boolean inTransaction); - public Either<ComponentInstance, StorageOperationStatus> deleteComponentInstance(NodeTypeEnum containerNodeType, - String containerComponentId, String resourceInstUid); + public Either<ComponentInstance, StorageOperationStatus> deleteComponentInstance(NodeTypeEnum containerNodeType, String containerComponentId, String resourceInstUid); /** * associate 2 resource instances for a given requirement @@ -106,16 +106,13 @@ public interface IComponentInstanceOperation { // String serviceId, NodeTypeEnum nodeType, String fromResInstanceUid, // String toResInstanceUid, String requirement, String relationship); - public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String serviceId, - NodeTypeEnum nodeType, RequirementCapabilityRelDef relation, boolean inTransaction); + public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String serviceId, NodeTypeEnum nodeType, RequirementCapabilityRelDef relation, boolean inTransaction, boolean isClone); - public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String serviceId, - NodeTypeEnum nodeType, RequirementCapabilityRelDef relation); + public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String serviceId, NodeTypeEnum nodeType, RequirementCapabilityRelDef relation); /** * - * dissociate the relation between 2 resource instances for a given - * requirement + * dissociate the relation between 2 resource instances for a given requirement * * @param serviceId * @param fromResInstanceUid @@ -124,11 +121,9 @@ public interface IComponentInstanceOperation { * @param inTransaction * @return */ - public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String serviceId, - NodeTypeEnum nodeType, RequirementCapabilityRelDef requirementDef, boolean inTransaction); + public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String serviceId, NodeTypeEnum nodeType, RequirementCapabilityRelDef requirementDef, boolean inTransaction); - public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String serviceId, - NodeTypeEnum nodeType, RequirementCapabilityRelDef requirementDef); + public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String serviceId, NodeTypeEnum nodeType, RequirementCapabilityRelDef requirementDef); /** * update the properties of a given resource instance @@ -139,30 +134,31 @@ public interface IComponentInstanceOperation { * @param inTransaction * @return */ - public Either<ComponentInstance, StorageOperationStatus> updateResourceInstance(String serviceId, - NodeTypeEnum nodeType, String resourceInstanceName, ComponentInstance resourceInstance, - boolean inTransaction); + public Either<ComponentInstance, StorageOperationStatus> updateResourceInstance(String serviceId, NodeTypeEnum nodeType, String resourceInstanceName, ComponentInstance resourceInstance, boolean inTransaction); - public Either<ComponentInstance, StorageOperationStatus> updateResourceInstance(String serviceId, - NodeTypeEnum nodeType, String resourceInstanceName, ComponentInstance resourceInstance); + public Either<ComponentInstance, StorageOperationStatus> updateResourceInstance(String serviceId, NodeTypeEnum nodeType, String resourceInstanceName, ComponentInstance resourceInstance); /** - * get all resource instances of a given service and the relations between - * the resource instances + * get all resource instances of a given service and the relations between the resource instances * * @param serviceId * @param inTransaction * @return */ - public Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, StorageOperationStatus> getAllComponentInstances( - String componentId, NodeTypeEnum containerNodeType, NodeTypeEnum compInstNodeType, boolean inTransaction); - - public Either<List<String>, StorageOperationStatus> getAllComponentInstancesNames(String componentId, - NodeTypeEnum nodeType, boolean inTransaction); + public Either<ImmutablePair<List<ComponentInstance>, List<RequirementCapabilityRelDef>>, StorageOperationStatus> getAllComponentInstances(String componentId, NodeTypeEnum containerNodeType, NodeTypeEnum compInstNodeType, boolean inTransaction); - public Either<List<String>, StorageOperationStatus> getAllComponentInstancesNames(String componentId, - NodeTypeEnum nodeType); + public Either<List<String>, StorageOperationStatus> getAllComponentInstancesNames(String componentId, NodeTypeEnum nodeType, boolean inTransaction); + public Either<List<String>, StorageOperationStatus> getAllComponentInstancesNames(String componentId, NodeTypeEnum nodeType); + + /** + * get all component instance properties and values from graph + * @param resourceInstance + * @return + */ + public Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstancesPropertiesAndValuesFromGraph( + ComponentInstance resourceInstance); + /** * get resource instance from id * @@ -171,54 +167,38 @@ public interface IComponentInstanceOperation { */ public Either<ComponentInstance, StorageOperationStatus> getResourceInstanceById(String resourceId); - public Either<List<ComponentInstance>, StorageOperationStatus> deleteAllComponentInstances(String serviceId, - NodeTypeEnum nodeType, boolean inTransaction); + public Either<List<ComponentInstance>, StorageOperationStatus> deleteAllComponentInstances(String serviceId, NodeTypeEnum nodeType, boolean inTransaction); - public Either<List<ComponentInstance>, StorageOperationStatus> deleteAllComponentInstances(String serviceId, - NodeTypeEnum nodeType); + public Either<List<ComponentInstance>, StorageOperationStatus> deleteAllComponentInstances(String serviceId, NodeTypeEnum nodeType); - public Either<Integer, StorageOperationStatus> increaseAndGetResourceInstanceSpecificCounter( - String resourceInstanceId, GraphPropertiesDictionary counterType, boolean inTransaction); + public Either<Integer, StorageOperationStatus> increaseAndGetResourceInstanceSpecificCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, boolean inTransaction); public String createComponentInstLogicalName(String instanceNumber, String componentInstanceName); - public Either<Boolean, StorageOperationStatus> isComponentInstanceNameExist(String parentComponentId, - NodeTypeEnum parentNodeType, String compInstId, String componentInstName); + public Either<Boolean, StorageOperationStatus> isComponentInstanceNameExist(String parentComponentId, NodeTypeEnum parentNodeType, String compInstId, String componentInstName); - public Either<Boolean, StorageOperationStatus> validateParent(String parentId, String uniqId, - boolean inTransaction); + public Either<Boolean, StorageOperationStatus> validateParent(String parentId, String uniqId, boolean inTransaction); - public Either<ComponentInstance, StorageOperationStatus> getFullComponentInstance( - ComponentInstance componentInstance, NodeTypeEnum compInstNodeType); + public Either<ComponentInstance, StorageOperationStatus> getFullComponentInstance(ComponentInstance componentInstance, NodeTypeEnum compInstNodeType); - public Either<Boolean, StorageOperationStatus> isAvailableRequirement(ComponentInstance fromResInstance, - RequirementAndRelationshipPair relationPair); + public Either<Boolean, StorageOperationStatus> isAvailableRequirement(ComponentInstance fromResInstance, RequirementAndRelationshipPair relationPair); - public Either<Boolean, StorageOperationStatus> isAvailableCapabilty(ComponentInstance toResInstance, - RequirementAndRelationshipPair relationPair); + public Either<Boolean, StorageOperationStatus> isAvailableCapabilty(ComponentInstance toResInstance, RequirementAndRelationshipPair relationPair); - public Either<ComponentInstanceProperty, StorageOperationStatus> addPropertyValueToResourceInstance( - ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, Integer index, - boolean inTransaction); + public Either<ComponentInstanceProperty, StorageOperationStatus> addPropertyValueToResourceInstance(ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, Integer index, boolean inTransaction); - public Either<ComponentInstanceProperty, StorageOperationStatus> addPropertyValueToResourceInstance( - ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, boolean isvalidate, - Integer index, boolean inTransaction); + public Either<ComponentInstanceProperty, StorageOperationStatus> addPropertyValueToResourceInstance(ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, boolean isvalidate, Integer index, boolean inTransaction); /** * Adds Attribute to resource instance * * @param resourceInstanceAttribute - * * @param resourceInstanceId * @param index * @param - * inTransaction + * * @param resourceInstanceId * @param index * @param inTransaction * @return **/ - public Either<ComponentInstanceAttribute, StorageOperationStatus> addAttributeValueToResourceInstance( - ComponentInstanceAttribute resourceInstanceAttribute, String resourceInstanceId, Integer index, - boolean inTransaction); + public Either<ComponentInstanceAttribute, StorageOperationStatus> addAttributeValueToResourceInstance(ComponentInstanceAttribute resourceInstanceAttribute, String resourceInstanceId, Integer index, boolean inTransaction); - public Either<ComponentInstanceProperty, StorageOperationStatus> updatePropertyValueInResourceInstance( - ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, boolean inTransaction); + public Either<ComponentInstanceProperty, StorageOperationStatus> updatePropertyValueInResourceInstance(ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, boolean inTransaction); /** * Updates Attribute on resource instance @@ -228,19 +208,32 @@ public interface IComponentInstanceOperation { * @param inTransaction * @return */ - public Either<ComponentInstanceAttribute, StorageOperationStatus> updateAttributeValueInResourceInstance( - ComponentInstanceAttribute attribute, String resourceInstanceId, boolean inTransaction); + public Either<ComponentInstanceAttribute, StorageOperationStatus> updateAttributeValueInResourceInstance(ComponentInstanceAttribute attribute, String resourceInstanceId, boolean inTransaction); - public Either<AttributeValueData, TitanOperationStatus> createOrUpdateAttributeOfResourceInstance( - ComponentInstanceAttribute attributeInstanceProperty, String resourceInstanceId); + public Either<AttributeValueData, TitanOperationStatus> createOrUpdateAttributeOfResourceInstance(ComponentInstanceAttribute attributeInstanceProperty, String resourceInstanceId); + + public Either<ComponentInstanceInput, StorageOperationStatus> addInputValueToResourceInstance(ComponentInstanceInput input, String resourceInstanceId, Integer innerElement, boolean b); + + public Either<ComponentInstanceInput, StorageOperationStatus> updateInputValueInResourceInstance(ComponentInstanceInput input, String resourceInstanceId, boolean b); + + public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> fetchCIEnvArtifacts(String componentInstanceId); + + public StorageOperationStatus updateCustomizationUUID(String componentInstanceId); + /** + * updates componentInstance modificationTime on graph node + * @param componentInstance + * @param componentInstanceType + * @param modificationTime + * @param inTransaction + * @return + */ + public Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction); - public Either<ComponentInstanceInput, StorageOperationStatus> addInputValueToResourceInstance( - ComponentInstanceInput input, String resourceInstanceId, Integer innerElement, boolean b); + Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> getCapabilities(ComponentInstance compInstance, NodeTypeEnum nodeTypeEnum); - public Either<ComponentInstanceInput, StorageOperationStatus> updateInputValueInResourceInstance( - ComponentInstanceInput input, String resourceInstanceId, boolean b); + Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> getRequirements(ComponentInstance compInstance, NodeTypeEnum nodeTypeEnum); - public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> fetchCIEnvArtifacts( - String componentInstanceId); + Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> getFulfilledCapabilities(ComponentInstance compInstance, NodeTypeEnum nodeTypeEnum); + Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> getFulfilledRequirements(ComponentInstance compInstance, NodeTypeEnum nodeTypeEnum); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IComponentOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IComponentOperation.java index e7eff13a9d..3eef59fa69 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IComponentOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IComponentOperation.java @@ -28,23 +28,23 @@ import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentParametersView; import fj.data.Either; public interface IComponentOperation { public <T extends Component> Either<T, StorageOperationStatus> getComponent(String id, Class<T> clazz); - public Either<List<ArtifactDefinition>, StorageOperationStatus> getComponentArtifactsForDelete(String parentId, - NodeTypeEnum parentType, boolean inTransacton); + public Either<List<ArtifactDefinition>, StorageOperationStatus> getComponentArtifactsForDelete(String parentId, NodeTypeEnum parentType, boolean inTransacton); public <T> Either<T, StorageOperationStatus> getLightComponent(String id, boolean inTransaction); public <T> Either<T, StorageOperationStatus> getComponent(String id, boolean inTransaction); + + public <T> Either<T, StorageOperationStatus> getComponent(String id, ComponentParametersView componentParametersView, boolean inTransaction); - public <T> Either<List<T>, StorageOperationStatus> getFilteredComponents(Map<FilterKeyEnum, String> filters, - boolean inTranscation); + public <T> Either<List<T>, StorageOperationStatus> getFilteredComponents(Map<FilterKeyEnum, String> filters, boolean inTranscation); - public <T extends GraphNode> Either<T, StorageOperationStatus> getComponentByLabelAndId(String uniqueId, - NodeTypeEnum nodeType, Class<T> clazz); + public <T extends GraphNode> Either<T, StorageOperationStatus> getComponentByLabelAndId(String uniqueId, NodeTypeEnum nodeType, Class<T> clazz); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IConsumerOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IConsumerOperation.java index 290552b382..ed43b7ce1f 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IConsumerOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IConsumerOperation.java @@ -32,9 +32,7 @@ public interface IConsumerOperation { * @param consumerData * the object we want to store * @param inTransaction - * inTransaction is the operation part of a transaction, in case - * the value is false the action will be committed in the end of - * the method + * inTransaction is the operation part of a transaction, in case the value is false the action will be committed in the end of the method * @return the updated object returned from the graph */ Either<ConsumerData, StorageOperationStatus> updateCredentials(ConsumerData consumerData, boolean inTransaction); @@ -52,12 +50,9 @@ public interface IConsumerOperation { * the method deletes the node with the given unique id * * @param consumerName - * the unique id by witch we will look up the credential we want - * to delete + * the unique id by witch we will look up the credential we want to delete * @param inTransaction - * inTransaction is the operation part of a transaction, in case - * the value is false the action will be committed in the end of - * the method + * inTransaction is the operation part of a transaction, in case the value is false the action will be committed in the end of the method * @return the deleted object returned from the graph */ Either<ConsumerData, StorageOperationStatus> deleteCredentials(String consumerName, boolean inTransaction); @@ -66,28 +61,24 @@ public interface IConsumerOperation { * the method deletes the node with the given unique id * * @param consumerName - * the unique id by witch we will look up the credential we want - * to delete + * the unique id by witch we will look up the credential we want to delete * @return the deleted object returned from the graph */ Either<ConsumerData, StorageOperationStatus> deleteCredentials(String consumerName); /** - * the method creates a new nod in the grape representing the supplied - * credential object + * the method creates a new nod in the grape representing the supplied credential object * * @param consumerData * the object we want to store * @param inTransaction - * is the operation part of a transaction, in case the value is - * false the action will be committed in the end of the method + * is the operation part of a transaction, in case the value is false the action will be committed in the end of the method * @return the newly stored object returned from the graph */ Either<ConsumerData, StorageOperationStatus> createCredentials(ConsumerData consumerData, boolean inTransaction); /** - * the method creates a new nod in the grape representing the supplied - * credential object + * the method creates a new nod in the grape representing the supplied credential object * * @param consumerData * the object we want to store diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IDataTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IDataTypeOperation.java index b7f1882b45..9377abbb76 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IDataTypeOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IDataTypeOperation.java @@ -32,8 +32,7 @@ public interface IDataTypeOperation { */ public Either<DataTypeDefinition, StorageOperationStatus> addDataType(DataTypeDefinition dataTypeDefinition); - public Either<DataTypeDefinition, StorageOperationStatus> addDataType(DataTypeDefinition dataTypeDefinition, - boolean inTransaction); + public Either<DataTypeDefinition, StorageOperationStatus> addDataType(DataTypeDefinition dataTypeDefinition, boolean inTransaction); /** * @param name diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IElementOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IElementOperation.java index a21c194060..0a82be8465 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IElementOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IElementOperation.java @@ -54,18 +54,15 @@ public interface IElementOperation { public Either<Integer, ActionStatus> getDefaultHeatTimeout(); - public <T extends GraphNode> Either<CategoryData, StorageOperationStatus> getCategoryData(String name, - NodeTypeEnum type, Class<T> clazz); + public <T extends GraphNode> Either<CategoryData, StorageOperationStatus> getCategoryData(String name, NodeTypeEnum type, Class<T> clazz); - public <T extends GraphNode> Either<org.openecomp.sdc.be.resources.data.category.CategoryData, StorageOperationStatus> getNewCategoryData( - String name, NodeTypeEnum type, Class<T> clazz); + public <T extends GraphNode> Either<org.openecomp.sdc.be.resources.data.category.CategoryData, StorageOperationStatus> getNewCategoryData(String name, NodeTypeEnum type, Class<T> clazz); public Either<Map<String, String>, ActionStatus> getResourceTypesMap(); Either<CategoryDefinition, ActionStatus> createCategory(CategoryDefinition category, NodeTypeEnum nodeType); - Either<CategoryDefinition, ActionStatus> createCategory(CategoryDefinition category, NodeTypeEnum nodeType, - boolean inTransaction); + Either<CategoryDefinition, ActionStatus> createCategory(CategoryDefinition category, NodeTypeEnum nodeType, boolean inTransaction); Either<CategoryDefinition, ActionStatus> deleteCategory(NodeTypeEnum nodeType, String categoryId); @@ -73,32 +70,25 @@ public interface IElementOperation { Either<Boolean, ActionStatus> isCategoryUniqueForType(NodeTypeEnum nodeType, String normalizedName); - Either<SubCategoryDefinition, ActionStatus> createSubCategory(String categoryId, SubCategoryDefinition subCategory, - NodeTypeEnum nodeType); + Either<SubCategoryDefinition, ActionStatus> createSubCategory(String categoryId, SubCategoryDefinition subCategory, NodeTypeEnum nodeType); - Either<SubCategoryDefinition, ActionStatus> createSubCategory(String categoryId, SubCategoryDefinition subCategory, - NodeTypeEnum nodeType, boolean inTransaction); + Either<SubCategoryDefinition, ActionStatus> createSubCategory(String categoryId, SubCategoryDefinition subCategory, NodeTypeEnum nodeType, boolean inTransaction); Either<List<CategoryDefinition>, ActionStatus> getAllCategories(NodeTypeEnum nodeType, boolean inTransaction); Either<CategoryDefinition, ActionStatus> getCategory(NodeTypeEnum nodeType, String categoryId); - Either<SubCategoryDefinition, ActionStatus> getSubCategoryUniqueForType(NodeTypeEnum nodeType, - String normalizedName); + Either<SubCategoryDefinition, ActionStatus> getSubCategoryUniqueForType(NodeTypeEnum nodeType, String normalizedName); - Either<Boolean, ActionStatus> isSubCategoryUniqueForCategory(NodeTypeEnum nodeType, String subCategoryNormName, - String parentCategoryId); + Either<Boolean, ActionStatus> isSubCategoryUniqueForCategory(NodeTypeEnum nodeType, String subCategoryNormName, String parentCategoryId); - Either<GroupingDefinition, ActionStatus> createGrouping(String subCategoryId, GroupingDefinition grouping, - NodeTypeEnum nodeType); + Either<GroupingDefinition, ActionStatus> createGrouping(String subCategoryId, GroupingDefinition grouping, NodeTypeEnum nodeType); Either<GroupingDefinition, ActionStatus> deleteGrouping(NodeTypeEnum nodeType, String groupingId); Either<SubCategoryDefinition, ActionStatus> getSubCategory(NodeTypeEnum nodeType, String subCategoryId); - Either<Boolean, ActionStatus> isGroupingUniqueForSubCategory(NodeTypeEnum nodeType, String groupingNormName, - String parentSubCategoryId); + Either<Boolean, ActionStatus> isGroupingUniqueForSubCategory(NodeTypeEnum nodeType, String groupingNormName, String parentSubCategoryId); - Either<GroupingDefinition, ActionStatus> getGroupingUniqueForType(NodeTypeEnum nodeType, - String groupingNormalizedName); + Either<GroupingDefinition, ActionStatus> getGroupingUniqueForType(NodeTypeEnum nodeType, String groupingNormalizedName); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGraphLockOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGraphLockOperation.java index d065ce0b09..29da56205a 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGraphLockOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGraphLockOperation.java @@ -30,7 +30,6 @@ public interface IGraphLockOperation { public abstract StorageOperationStatus lockComponentByName(String name, NodeTypeEnum nodeType); - public abstract StorageOperationStatus unlockComponentByName(String name, String componentId, - NodeTypeEnum nodeType); + public abstract StorageOperationStatus unlockComponentByName(String name, String componentId, NodeTypeEnum nodeType); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupInstanceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupInstanceOperation.java new file mode 100644 index 0000000000..8fd88f704f --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupInstanceOperation.java @@ -0,0 +1,101 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.operations.api; + + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.model.ArtifactDefinition; + +import org.openecomp.sdc.be.model.ComponentInstance; + +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +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.resources.data.ArtifactData; +import org.openecomp.sdc.exception.ResponseFormat; + +import com.thinkaurelius.titan.core.TitanVertex; + +import fj.data.Either; + +public interface IGroupInstanceOperation { + + public Either<GroupInstance, StorageOperationStatus> createGroupInstance(String ComponentInstId, GroupInstance groupInstance, boolean isCreateLogicalName); + + public Either<GroupInstance, StorageOperationStatus> createGroupInstance(TitanVertex ciVertex, String componentInstId, GroupInstance groupInstance, boolean isCreateLogicalName); + + public Either<GroupInstance, StorageOperationStatus> deleteGroupInstanceInstance(NodeTypeEnum containerNodeType, String containerComponentId, String groupInstUid); + + public Either<GroupInstance, StorageOperationStatus> updateGroupInstance(String serviceId, NodeTypeEnum nodeType, String resourceInstanceName, ComponentInstance resourceInstance); + + public Either<List<GroupInstance>, StorageOperationStatus> getAllGroupInstances(String componentInstId, NodeTypeEnum compInstNodeType); + + public Either<GroupInstance, TitanOperationStatus> getGroupInstanceById(String groupResourceId); + + public TitanOperationStatus deleteAllGroupInstances(String componentInstId); + + public Either<Integer, StorageOperationStatus> increaseAndGetGroupInstancePropertyCounter(String groupInstanceId); + + public Either<Boolean, StorageOperationStatus> isGroupInstanceNameExist(String parentComponentId, NodeTypeEnum parentNodeType, String compInstId, String componentInstName); + + public Either<ComponentInstance, StorageOperationStatus> getFullGroupInstance(ComponentInstance componentInstance, NodeTypeEnum compInstNodeType); + + public Either<ComponentInstanceProperty, StorageOperationStatus> addPropertyValueToGroupInstance(ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, Integer index, boolean inTransaction); + + public Either<ComponentInstanceProperty, StorageOperationStatus> addPropertyValueToGroupInstance(ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, boolean isvalidate, Integer index, boolean inTransaction); + + public Either<ComponentInstanceProperty, StorageOperationStatus> updatePropertyValueInGroupInstance(ComponentInstanceProperty gropuInstanceProperty, String groupInstanceId, boolean inTransaction); + + public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> fetchCIEnvArtifacts(String componentInstanceId); + + public StorageOperationStatus updateCustomizationUUID(String componentInstanceId); + + public String createGroupInstLogicalName(String instanceNumber, String groupInstanceName); + + public Either<GroupInstance, StorageOperationStatus> associateArtifactsToGroupInstance(String groupId, List<String> artifactsId); + + StorageOperationStatus dissociateAndAssociateGroupsInstanceFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact); + + StorageOperationStatus dissociateAndAssociateGroupsInstanceFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact); + /** + * updates group instance property values + * @param value + * @param newProperties + * @return + */ + public Either<GroupInstance, StorageOperationStatus> updateGroupInstancePropertyValues(GroupInstance value, List<GroupInstanceProperty> newProperties); + /** + * updates group instance property values + * @param oldGroupInstance + * @param newProperties + * @param inTransaction + * @return + */ + public Either<GroupInstance, StorageOperationStatus> updateGroupInstancePropertyValues(GroupInstance oldGroupInstance, List<GroupInstanceProperty> newProperties, Boolean inTransaction); + +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupOperation.java index 4252ec0622..3295adfe56 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupOperation.java @@ -26,6 +26,7 @@ import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.GroupProperty; import org.openecomp.sdc.be.resources.data.ArtifactData; import org.openecomp.sdc.be.resources.data.GroupData; @@ -34,17 +35,13 @@ import fj.data.Either; public interface IGroupOperation { // add full group to component - public Either<GroupData, TitanOperationStatus> addGroupToGraph(NodeTypeEnum nodeTypeEnum, String componentId, - GroupDefinition groupDefinition); + public Either<GroupData, TitanOperationStatus> addGroupToGraph(NodeTypeEnum nodeTypeEnum, String componentId, GroupDefinition groupDefinition); - public Either<GroupDefinition, StorageOperationStatus> addGroup(NodeTypeEnum nodeTypeEnum, String componentId, - GroupDefinition groupDefinition); + public Either<GroupDefinition, StorageOperationStatus> addGroup(NodeTypeEnum nodeTypeEnum, String componentId, GroupDefinition groupDefinition); - public Either<GroupDefinition, StorageOperationStatus> addGroup(NodeTypeEnum nodeTypeEnum, String componentId, - GroupDefinition groupDefinition, boolean inTransaction); + public Either<GroupDefinition, StorageOperationStatus> addGroup(NodeTypeEnum nodeTypeEnum, String componentId, GroupDefinition groupDefinition, boolean inTransaction); - public Either<List<GroupDefinition>, StorageOperationStatus> addGroups(NodeTypeEnum nodeTypeEnum, - String componentId, List<GroupDefinition> groups, boolean inTransaction); + public Either<List<GroupDefinition>, StorageOperationStatus> addGroups(NodeTypeEnum nodeTypeEnum, String componentId, List<GroupDefinition> groups, boolean inTransaction); // get group public Either<GroupDefinition, TitanOperationStatus> getGroupFromGraph(String uniqueId); @@ -54,61 +51,55 @@ public interface IGroupOperation { public Either<GroupDefinition, StorageOperationStatus> getGroup(String uniqueId, boolean inTransaction); // get all groups under component - public Either<List<GroupDefinition>, TitanOperationStatus> getAllGroupsFromGraph(String componentId, - NodeTypeEnum componentTypeEnum); + public Either<List<GroupDefinition>, TitanOperationStatus> getAllGroupsFromGraph(String componentId, NodeTypeEnum componentTypeEnum); - public Either<List<GroupDefinition>, StorageOperationStatus> getAllGroups(String componentId, - NodeTypeEnum compTypeEnum, boolean inTransaction); + public Either<List<GroupDefinition>, StorageOperationStatus> getAllGroups(String componentId, NodeTypeEnum compTypeEnum, boolean inTransaction); - public Either<List<GroupDefinition>, StorageOperationStatus> getAllGroups(String componentId, - NodeTypeEnum compTypeEnum); + public Either<List<GroupDefinition>, StorageOperationStatus> getAllGroups(String componentId, NodeTypeEnum compTypeEnum); // delete all groups under component - public Either<List<GroupDefinition>, TitanOperationStatus> deleteAllGroupsFromGraph(String componentId, - NodeTypeEnum compTypeEnum); + public Either<List<GroupDefinition>, TitanOperationStatus> deleteAllGroupsFromGraph(String componentId, NodeTypeEnum compTypeEnum); - public Either<List<GroupDefinition>, StorageOperationStatus> deleteAllGroups(String componentId, - NodeTypeEnum compTypeEnum, boolean inTransaction); + public Either<List<GroupDefinition>, StorageOperationStatus> deleteAllGroups(String componentId, NodeTypeEnum compTypeEnum, boolean inTransaction); - public Either<List<GroupDefinition>, StorageOperationStatus> deleteAllGroups(String componentId, - NodeTypeEnum compTypeEnum); + public Either<List<GroupDefinition>, StorageOperationStatus> deleteAllGroups(String componentId, NodeTypeEnum compTypeEnum); // Association - public Either<List<String>, StorageOperationStatus> getAssociatedGroupsToComponentInstance( - String componentInstanceId, boolean inTransaction); + public Either<List<String>, StorageOperationStatus> getAssociatedGroupsToComponentInstance(String componentInstanceId, boolean inTransaction); - public Either<List<String>, StorageOperationStatus> getAssociatedGroupsToComponentInstance( - String componentInstanceId); + public Either<List<String>, StorageOperationStatus> getAssociatedGroupsToComponentInstance(String componentInstanceId); - public Either<List<String>, TitanOperationStatus> getAssociatedGroupsToComponentInstanceFromGraph( - String componentInstanceId); + public Either<List<String>, TitanOperationStatus> getAssociatedGroupsToComponentInstanceFromGraph(String componentInstanceId); - public StorageOperationStatus associateGroupsToComponentInstance(List<String> groups, String componentInstanceId, - String compInstName, boolean inTransaction); + public StorageOperationStatus associateGroupsToComponentInstance(List<String> groups, String componentInstanceId, String compInstName, boolean inTransaction); - public StorageOperationStatus associateGroupsToComponentInstance(List<String> groups, String componentInstanceId, - String compInstName); + public StorageOperationStatus associateGroupsToComponentInstance(List<String> groups, String componentInstanceId, String compInstName); - public Either<List<GraphRelation>, TitanOperationStatus> associateGroupsToComponentInstanceOnGraph( - List<String> groups, String componentInstanceId, String compInstName); + public Either<List<GraphRelation>, TitanOperationStatus> associateGroupsToComponentInstanceOnGraph(List<String> groups, String componentInstanceId, String compInstName); - public Either<List<GraphRelation>, TitanOperationStatus> dissociateAllGroupsFromArtifactOnGraph(String componentId, - NodeTypeEnum componentTypeEnum, String artifactId); + public Either<List<GraphRelation>, TitanOperationStatus> dissociateAllGroupsFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String artifactId); - public StorageOperationStatus dissociateAllGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, - String artifactId, boolean inTransaction); + public StorageOperationStatus dissociateAllGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String artifactId, boolean inTransaction); - public StorageOperationStatus dissociateAllGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, - String artifactId); + public StorageOperationStatus dissociateAllGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String artifactId); - public TitanOperationStatus dissociateAndAssociateGroupsFromArtifactOnGraph(String componentId, - NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact); + public TitanOperationStatus dissociateAndAssociateGroupsFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact); - public StorageOperationStatus dissociateAndAssociateGroupsFromArtifact(String componentId, - NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact, boolean inTransaction); + public StorageOperationStatus dissociateAndAssociateGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact, boolean inTransaction); - public StorageOperationStatus dissociateAndAssociateGroupsFromArtifact(String componentId, - NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact); + public StorageOperationStatus dissociateAndAssociateGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact); public boolean isGroupExist(String groupName, boolean inTransaction); + /** + * Updates Group Metadata (name and properties) + * @param groupToUpdateFromUniqueId + * @param newName + * @param groupToUpdateTo + * @param inTransaction + * @return + */ + public Either<GroupDefinition, StorageOperationStatus> updateGroupName(String groupToUpdateFromUniqueId, + String newName, GroupDefinition groupToUpdateTo, boolean inTransaction); + + public StorageOperationStatus validateAndUpdatePropertyValue(GroupProperty property); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupTypeOperation.java index 2b612579b6..87a0dccfab 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupTypeOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IGroupTypeOperation.java @@ -34,8 +34,7 @@ public interface IGroupTypeOperation { */ public Either<GroupTypeDefinition, StorageOperationStatus> addGroupType(GroupTypeDefinition groupTypeDefinition); - public Either<GroupTypeDefinition, StorageOperationStatus> addGroupType(GroupTypeDefinition groupTypeDefinition, - boolean inTransaction); + public Either<GroupTypeDefinition, StorageOperationStatus> addGroupType(GroupTypeDefinition groupTypeDefinition, boolean inTransaction); /** * @param uniqueId @@ -47,14 +46,11 @@ public interface IGroupTypeOperation { public Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeByType(String name); - public Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeByType(String name, - boolean inTransaction); + public Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeByType(String name, boolean inTransaction); - public Either<GroupTypeDefinition, StorageOperationStatus> getGroupTypeByTypeAndVersion(String name, - String version); + public Either<GroupTypeDefinition, StorageOperationStatus> getGroupTypeByTypeAndVersion(String name, String version); - public Either<GroupTypeDefinition, StorageOperationStatus> getGroupTypeByTypeAndVersion(String name, String version, - boolean inTransaction); + public Either<GroupTypeDefinition, StorageOperationStatus> getGroupTypeByTypeAndVersion(String name, String version, boolean inTransaction); public Either<GroupTypeData, TitanOperationStatus> getLatestGroupTypeByNameFromGraph(String name); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInputsOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInputsOperation.java index 2f1f2a70cf..386864a8b0 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInputsOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInputsOperation.java @@ -39,43 +39,33 @@ import fj.data.Either; public interface IInputsOperation { - Either<String, StorageOperationStatus> deleteInput(String inputId); + Either<InputDefinition, StorageOperationStatus> deleteInput(String inputId); - Either<List<InputDefinition>, TitanOperationStatus> addInputsToGraph(String componentId, NodeTypeEnum nodeType, - Map<String, InputDefinition> inputs, Map<String, DataTypeDefinition> dataTypes); + Either<List<InputDefinition>, TitanOperationStatus> addInputsToGraph(String componentId, NodeTypeEnum nodeType, Map<String, InputDefinition> inputs, Map<String, DataTypeDefinition> dataTypes); - Either<List<InputDefinition>, StorageOperationStatus> addInputsToComponent(String resourceId, NodeTypeEnum nodeType, - ComponentInstInputsMap componentInsInputs, Map<String, DataTypeDefinition> dataTypes); + Either<List<InputDefinition>, StorageOperationStatus> addInputsToComponent(String resourceId, NodeTypeEnum nodeType, ComponentInstInputsMap componentInsInputs, Map<String, DataTypeDefinition> dataTypes); TitanOperationStatus findNodeNonInheretedInputs(String uniqueId, List<InputDefinition> inputs); - Either<List<InputDefinition>, StorageOperationStatus> getInputsOfComponent(String compId, String fromName, - int amount); + Either<List<InputDefinition>, StorageOperationStatus> getInputsOfComponent(String compId, String fromName, int amount); - Either<List<ComponentInstanceInput>, TitanOperationStatus> getAllInputsOfResourceInstance( - ComponentInstance compInstance); + Either<List<ComponentInstanceInput>, TitanOperationStatus> getAllInputsOfResourceInstance(ComponentInstance compInstance); - Either<Map<String, InputDefinition>, StorageOperationStatus> deleteAllInputsAssociatedToNode(NodeTypeEnum nodeType, - String uniqueId); + Either<Map<String, InputDefinition>, StorageOperationStatus> deleteAllInputsAssociatedToNode(NodeTypeEnum nodeType, String uniqueId); // TitanOperationStatus findNodeNonInheretedAttribues(String uniqueId, // NodeTypeEnum nodeType, List<AttributeDefinition> attributes); - Either<InputsData, StorageOperationStatus> addInput(String inputName, InputDefinition inputDefinition, - String componentId, NodeTypeEnum nodeType); + Either<InputsData, StorageOperationStatus> addInput(String inputName, InputDefinition inputDefinition, String componentId, NodeTypeEnum nodeType); - Either<InputsData, TitanOperationStatus> addInputToGraph(String propertyName, InputDefinition inputDefinition, - String componentId, NodeTypeEnum nodeType); + Either<InputsData, TitanOperationStatus> addInputToGraph(String propertyName, InputDefinition inputDefinition, String componentId, NodeTypeEnum nodeType); - Either<AttributeData, StorageOperationStatus> updateInput(String inputId, InputDefinition newInDef, - Map<String, DataTypeDefinition> dataTypes); + Either<AttributeData, StorageOperationStatus> updateInput(String inputId, InputDefinition newInDef, Map<String, DataTypeDefinition> dataTypes); TitanOperationStatus findAllResourceInputs(String uniqueId, List<InputDefinition> inputs); - Either<InputDefinition, StorageOperationStatus> getInputById(String uniqueId, boolean skipProperties, - boolean skipinputsValue); + Either<InputDefinition, StorageOperationStatus> getInputById(String uniqueId, boolean skipProperties, boolean skipinputsValue); - TitanOperationStatus addInputsToGraph(TitanVertex metadata, String componentId, Map<String, InputDefinition> inputs, - Map<String, DataTypeDefinition> dataTypes); + TitanOperationStatus addInputsToGraph(TitanVertex metadata, String componentId, Map<String, InputDefinition> inputs, Map<String, DataTypeDefinition> dataTypes); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInterfaceLifecycleOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInterfaceLifecycleOperation.java index bbcb61fea8..e46460a502 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInterfaceLifecycleOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IInterfaceLifecycleOperation.java @@ -33,17 +33,13 @@ import fj.data.Either; public interface IInterfaceLifecycleOperation { - public Either<InterfaceDefinition, StorageOperationStatus> createInterfaceOnResource(InterfaceDefinition interf, - String resourceId, String interfaceName, boolean failIfExist, boolean inTransaction); + public Either<InterfaceDefinition, StorageOperationStatus> createInterfaceOnResource(InterfaceDefinition interf, String resourceId, String interfaceName, boolean failIfExist, boolean inTransaction); - public StorageOperationStatus createInterfaceOnResource(InterfaceDefinition interf, String resourceId, - String interfaceName, boolean failIfExist, boolean inTransaction, TitanVertex metadataVertex); + public StorageOperationStatus createInterfaceOnResource(InterfaceDefinition interf, String resourceId, String interfaceName, boolean failIfExist, boolean inTransaction, TitanVertex metadataVertex); - public Either<InterfaceDefinition, StorageOperationStatus> addInterfaceToResource(InterfaceDefinition interf, - String resourceId, String interfaceName); + public Either<InterfaceDefinition, StorageOperationStatus> addInterfaceToResource(InterfaceDefinition interf, String resourceId, String interfaceName); - public Either<InterfaceDefinition, StorageOperationStatus> addInterfaceToResource(InterfaceDefinition interf, - String resourceId, String interfaceName, boolean inTransaction); + public Either<InterfaceDefinition, StorageOperationStatus> addInterfaceToResource(InterfaceDefinition interf, String resourceId, String interfaceName, boolean inTransaction); // public Either<InterfaceDefinition, StorageOperationStatus> // getInterface(String interfaceId); @@ -51,42 +47,31 @@ public interface IInterfaceLifecycleOperation { // public Either<InterfaceDefinition, StorageOperationStatus> // getInterface(String interfaceId, boolean inTransaction); - public Either<Operation, StorageOperationStatus> updateInterfaceOperation(String resourceId, String interfaceName, - String operationName, Operation interf); + public Either<Operation, StorageOperationStatus> updateInterfaceOperation(String resourceId, String interfaceName, String operationName, Operation interf); - public Either<Operation, StorageOperationStatus> updateInterfaceOperation(String resourceId, String interfaceName, - String operationName, Operation interf, boolean inTransaction); + public Either<Operation, StorageOperationStatus> updateInterfaceOperation(String resourceId, String interfaceName, String operationName, Operation interf, boolean inTransaction); - public Either<Operation, StorageOperationStatus> deleteInterfaceOperation(String resourceId, String interfaceName, - String operationName); + public Either<Operation, StorageOperationStatus> deleteInterfaceOperation(String resourceId, String interfaceName, String operationName); - public Either<Operation, StorageOperationStatus> deleteInterfaceOperation(String resourceId, String interfaceName, - String operationName, boolean inTransaction); + public Either<Operation, StorageOperationStatus> deleteInterfaceOperation(String resourceId, String interfaceName, String operationName, boolean inTransaction); - public Either<Map<String, InterfaceDefinition>, StorageOperationStatus> getAllInterfacesOfResource( - String resourceId, boolean recursively, boolean inTransaction); + public Either<Map<String, InterfaceDefinition>, StorageOperationStatus> getAllInterfacesOfResource(String resourceId, boolean recursively, boolean inTransaction); - public Either<Map<String, InterfaceDefinition>, StorageOperationStatus> getAllInterfacesOfResource( - String resourceId, boolean recursively); + public Either<Map<String, InterfaceDefinition>, StorageOperationStatus> getAllInterfacesOfResource(String resourceId, boolean recursively); - public Either<InterfaceDefinition, StorageOperationStatus> deleteInterfaceOfResourceOnGraph(String resourceId, - InterfaceDefinition interfaceDef, boolean inTransaction); + public Either<InterfaceDefinition, StorageOperationStatus> deleteInterfaceOfResourceOnGraph(String resourceId, InterfaceDefinition interfaceDef, boolean inTransaction); public Either<InterfaceDefinition, StorageOperationStatus> createInterfaceType(InterfaceDefinition interf); - public Either<InterfaceDefinition, StorageOperationStatus> createInterfaceType(InterfaceDefinition interf, - boolean inTransaction); + public Either<InterfaceDefinition, StorageOperationStatus> createInterfaceType(InterfaceDefinition interf, boolean inTransaction); public Either<InterfaceDefinition, StorageOperationStatus> getInterface(String interfaceId); - public StorageOperationStatus associateInterfaceToNode(GraphNode node, InterfaceDefinition interfaceDefinition, - TitanVertex metadataVertex); + public StorageOperationStatus associateInterfaceToNode(GraphNode node, InterfaceDefinition interfaceDefinition, TitanVertex metadataVertex); - public Either<Operation, StorageOperationStatus> getSpecificOperation(String resourceId, String interfaceType, - String operationName); + public Either<Operation, StorageOperationStatus> getSpecificOperation(String resourceId, String interfaceType, String operationName); - public Either<InterfaceDefinition, StorageOperationStatus> dissociateInterfaceFromNode(GraphNode node, - InterfaceDefinition interfaceDefinition); + public Either<InterfaceDefinition, StorageOperationStatus> dissociateInterfaceFromNode(GraphNode node, InterfaceDefinition interfaceDefinition); public String getShortInterfaceName(InterfaceDataDefinition interfaceDefinition); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ILifecycleOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ILifecycleOperation.java index 3b82eb692c..ab99f20d4c 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ILifecycleOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ILifecycleOperation.java @@ -33,32 +33,23 @@ public interface ILifecycleOperation { public ResourceOperation getResourceOperation(); - public Either<User, StorageOperationStatus> getComponentOwner(String resourceId, NodeTypeEnum nodeType, - boolean inTransaction); + public Either<User, StorageOperationStatus> getComponentOwner(String resourceId, NodeTypeEnum nodeType, boolean inTransaction); - public Either<? extends Component, StorageOperationStatus> checkinComponent(NodeTypeEnum nodeType, - Component component, User modifier, User owner, boolean inTransaction); + public Either<? extends Component, StorageOperationStatus> checkinComponent(NodeTypeEnum nodeType, Component component, User modifier, User owner, boolean inTransaction); - public Either<? extends Component, StorageOperationStatus> requestCertificationComponent(NodeTypeEnum nodeType, - Component component, User modifier, User owner, boolean inTransaction); + public Either<? extends Component, StorageOperationStatus> requestCertificationComponent(NodeTypeEnum nodeType, Component component, User modifier, User owner, boolean inTransaction); - public Either<? extends Component, StorageOperationStatus> startComponentCertification(NodeTypeEnum nodeType, - Component component, User modifier, User owner, boolean inTransaction); + public Either<? extends Component, StorageOperationStatus> startComponentCertification(NodeTypeEnum nodeType, Component component, User modifier, User owner, boolean inTransaction); - public Either<? extends Component, StorageOperationStatus> checkoutComponent(NodeTypeEnum nodeType, - Component component, User modifier, User currentOwner, boolean inTransaction); + public Either<? extends Component, StorageOperationStatus> checkoutComponent(NodeTypeEnum nodeType, Component component, User modifier, User currentOwner, boolean inTransaction); - public Either<? extends Component, StorageOperationStatus> certifyComponent(NodeTypeEnum nodeType, - Component component, User modifier, User currentOwner, boolean inTransaction); + public Either<? extends Component, StorageOperationStatus> certifyComponent(NodeTypeEnum nodeType, Component component, User modifier, User currentOwner, boolean inTransaction); - public Either<? extends Component, StorageOperationStatus> cancelOrFailCertification(NodeTypeEnum nodeType, - Component component, User modifier, User owner, LifecycleStateEnum nextState, boolean b); + public Either<? extends Component, StorageOperationStatus> cancelOrFailCertification(NodeTypeEnum nodeType, Component component, User modifier, User owner, LifecycleStateEnum nextState, boolean b); - public Either<Boolean, StorageOperationStatus> deleteOldComponentVersions(NodeTypeEnum nodeType, - String componentName, String uuid, boolean inTransaction); + public Either<Boolean, StorageOperationStatus> deleteOldComponentVersions(NodeTypeEnum nodeType, String componentName, String uuid, boolean inTransaction); - public Either<? extends Component, StorageOperationStatus> undoCheckout(NodeTypeEnum nodeType, Component resource, - User modifier, User currentOwner, boolean inTransaction); + public Either<? extends Component, StorageOperationStatus> undoCheckout(NodeTypeEnum nodeType, Component resource, User modifier, User currentOwner, boolean inTransaction); public ComponentOperation getComponentOperation(NodeTypeEnum componentType); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPolicyTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPolicyTypeOperation.java index fc689c81e2..d25d11331d 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPolicyTypeOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPolicyTypeOperation.java @@ -32,7 +32,6 @@ public interface IPolicyTypeOperation { Either<PolicyTypeDefinition, StorageOperationStatus> getPolicyType(String uniqueId, boolean inTransaction); - Either<PolicyTypeDefinition, StorageOperationStatus> addPolicyType(PolicyTypeDefinition policyType, - boolean inTransaction); + Either<PolicyTypeDefinition, StorageOperationStatus> addPolicyType(PolicyTypeDefinition policyType, boolean inTransaction); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IProductOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IProductOperation.java index bbfea262a7..76f95f3c2b 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IProductOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IProductOperation.java @@ -37,8 +37,7 @@ public interface IProductOperation extends IComponentOperation { public Either<Product, StorageOperationStatus> deleteProduct(String productId, boolean inTransaction); - public Either<List<Product>, StorageOperationStatus> getFollowed(String userId, - Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, boolean inTransaction); + public Either<List<Product>, StorageOperationStatus> getFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, boolean inTransaction); public void rollback(); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPropertyOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPropertyOperation.java index 6309510f6d..f9f960fdbf 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPropertyOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IPropertyOperation.java @@ -41,9 +41,7 @@ public interface IPropertyOperation { * @param id * @return * - * public Either<PropertyDefinition, StorageOperationStatus> - * addPropertyToResource( String propertyName, PropertyDefinition - * propertyDefinition, NodeTypeEnum nodeType, String id); + * public Either<PropertyDefinition, StorageOperationStatus> addPropertyToResource( String propertyName, PropertyDefinition propertyDefinition, NodeTypeEnum nodeType, String id); */ /** @@ -55,8 +53,7 @@ public interface IPropertyOperation { * - resource unique id * @return */ - public Either<PropertyDefinition, StorageOperationStatus> getPropertyOfResource(String propertyName, - String resourceId); + public Either<PropertyDefinition, StorageOperationStatus> getPropertyOfResource(String propertyName, String resourceId); /** * Delete all properties of resource @@ -65,16 +62,13 @@ public interface IPropertyOperation { * @param uniqueId * @return */ - public Either<Map<String, PropertyDefinition>, StorageOperationStatus> deleteAllPropertiesAssociatedToNode( - NodeTypeEnum nodeType, String uniqueId); + public Either<Map<String, PropertyDefinition>, StorageOperationStatus> deleteAllPropertiesAssociatedToNode(NodeTypeEnum nodeType, String uniqueId); - public boolean isPropertyDefaultValueValid(IComplexDefaultValue propertyDefinition, - Map<String, DataTypeDefinition> dataTypes); + public boolean isPropertyDefaultValueValid(IComplexDefaultValue propertyDefinition, Map<String, DataTypeDefinition> dataTypes); public boolean isPropertyTypeValid(IComplexDefaultValue propertyDefinition); - public ImmutablePair<String, Boolean> isPropertyInnerTypeValid(IComplexDefaultValue propertyDefinition, - Map<String, DataTypeDefinition> dataTypes); + public ImmutablePair<String, Boolean> isPropertyInnerTypeValid(IComplexDefaultValue propertyDefinition, Map<String, DataTypeDefinition> dataTypes); /** * @param dataTypeDefinition @@ -82,8 +76,7 @@ public interface IPropertyOperation { */ public Either<DataTypeDefinition, StorageOperationStatus> addDataType(DataTypeDefinition dataTypeDefinition); - public Either<DataTypeDefinition, StorageOperationStatus> addDataType(DataTypeDefinition dataTypeDefinition, - boolean inTransaction); + public Either<DataTypeDefinition, StorageOperationStatus> addDataType(DataTypeDefinition dataTypeDefinition, boolean inTransaction); /** * @param name @@ -93,18 +86,14 @@ public interface IPropertyOperation { public Either<DataTypeDefinition, StorageOperationStatus> getDataTypeByName(String name, boolean inTransaction); - public Either<DataTypeDefinition, StorageOperationStatus> getDataTypeByNameWithoutDerived(String name, - boolean inTransaction); + public Either<DataTypeDefinition, StorageOperationStatus> getDataTypeByNameWithoutDerived(String name, boolean inTransaction); public Either<DataTypeDefinition, StorageOperationStatus> getDataTypeByNameWithoutDerived(String name); - public StorageOperationStatus validateAndUpdateProperty(IComplexDefaultValue propertyDefinition, - Map<String, DataTypeDefinition> dataTypes); + public StorageOperationStatus validateAndUpdateProperty(IComplexDefaultValue propertyDefinition, Map<String, DataTypeDefinition> dataTypes); - public Either<DataTypeDefinition, StorageOperationStatus> updateDataType(DataTypeDefinition newDataTypeDefinition, - DataTypeDefinition oldDataTypeDefinition, boolean inTransaction); + public Either<DataTypeDefinition, StorageOperationStatus> updateDataType(DataTypeDefinition newDataTypeDefinition, DataTypeDefinition oldDataTypeDefinition, boolean inTransaction); - public Either<DataTypeDefinition, StorageOperationStatus> updateDataType(DataTypeDefinition newDataTypeDefinition, - DataTypeDefinition oldDataTypeDefinition); + public Either<DataTypeDefinition, StorageOperationStatus> updateDataType(DataTypeDefinition newDataTypeDefinition, DataTypeDefinition oldDataTypeDefinition); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IRequirementOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IRequirementOperation.java index a7a9bf6013..a2af44cf61 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IRequirementOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IRequirementOperation.java @@ -42,17 +42,13 @@ public interface IRequirementOperation { * @param uniqueId * @return */ - public Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource(String reqName, - RequirementDefinition reqDefinition, String resourceId); + public Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource(String reqName, RequirementDefinition reqDefinition, String resourceId); - public Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource(String reqName, - RequirementDefinition reqDefinition, String resourceId, boolean inTransaction); + public Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource(String reqName, RequirementDefinition reqDefinition, String resourceId, boolean inTransaction); - public Either<RequirementDefinition, StorageOperationStatus> addRequirementImplToResource(String reqName, - RequirementImplDef reqDefinition, String resourceId, String parentReqUniqueId); + public Either<RequirementDefinition, StorageOperationStatus> addRequirementImplToResource(String reqName, RequirementImplDef reqDefinition, String resourceId, String parentReqUniqueId); - public Either<RequirementDefinition, StorageOperationStatus> addRequirementImplToResource(String reqName, - RequirementImplDef reqDefinition, String resourceId, String parentReqUniqueId, boolean inTransaction); + public Either<RequirementDefinition, StorageOperationStatus> addRequirementImplToResource(String reqName, RequirementImplDef reqDefinition, String resourceId, String parentReqUniqueId, boolean inTransaction); /** * get requirement of resource @@ -61,25 +57,19 @@ public interface IRequirementOperation { * @param resourceId * @return */ - public Either<RequirementDefinition, StorageOperationStatus> getRequirementOfResource(String reqName, - String resourceId); + public Either<RequirementDefinition, StorageOperationStatus> getRequirementOfResource(String reqName, String resourceId); - public Either<RequirementDefinition, StorageOperationStatus> getRequirementOfResource(String reqName, - String resourceId, boolean inTransaction); + public Either<RequirementDefinition, StorageOperationStatus> getRequirementOfResource(String reqName, String resourceId, boolean inTransaction); - public Either<Map<String, RequirementDefinition>, StorageOperationStatus> getAllResourceRequirements( - String resourceId, boolean inTransaction); + public Either<Map<String, RequirementDefinition>, StorageOperationStatus> getAllResourceRequirements(String resourceId, boolean inTransaction); - Either<Map<String, List<RequirementDefinition>>, StorageOperationStatus> getAllRequirementsOfResourceOnly( - String resourceId, boolean inTransaction); + Either<Map<String, List<RequirementDefinition>>, StorageOperationStatus> getAllRequirementsOfResourceOnly(String resourceId, boolean inTransaction); public Either<Map<String, RequirementDefinition>, TitanOperationStatus> getResourceRequirements(String resourceId); - public Either<Map<String, RequirementDefinition>, StorageOperationStatus> deleteAllRequirements(String resourceId, - boolean inTransaction); + public Either<Map<String, RequirementDefinition>, StorageOperationStatus> deleteAllRequirements(String resourceId, boolean inTransaction); public Either<RequirementDefinition, TitanOperationStatus> getRequirement(String uniqueId); - StorageOperationStatus addRequirementToResource(TitanVertex metadataVertex, String reqName, - RequirementDefinition reqDefinition, String resourceId, boolean inTransaction); + StorageOperationStatus addRequirementToResource(TitanVertex metadataVertex, String reqName, RequirementDefinition reqDefinition, String resourceId, boolean inTransaction); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IResourceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IResourceOperation.java index 759380c236..01db3a5105 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IResourceOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IResourceOperation.java @@ -51,21 +51,17 @@ public interface IResourceOperation extends IComponentOperation { public Either<Resource, StorageOperationStatus> getResource(String resourceId, boolean inTransaction); /** - * the method retrieves all the certified resources, the returned values are - * only abstract or only none abstract according to the supplied parameters. + * the method retrieves all the certified resources, the returned values are only abstract or only none abstract according to the supplied parameters. * * @param getAbstract - * the value defines which resources to return only abstract or - * only none abstract + * the value defines which resources to return only abstract or only none abstract * @return */ public Either<List<Resource>, StorageOperationStatus> getAllCertifiedResources(boolean getAbstract); - public Either<List<Resource>, StorageOperationStatus> getAllCertifiedResources(boolean getAbstract, - Boolean isHighest); + public Either<List<Resource>, StorageOperationStatus> getAllCertifiedResources(boolean getAbstract, Boolean isHighest); - public Either<Boolean, StorageOperationStatus> validateResourceNameExists(String resourceName, - ResourceTypeEnum resourceType); + public Either<Boolean, StorageOperationStatus> validateResourceNameExists(String resourceName, ResourceTypeEnum resourceType); public Either<Resource, StorageOperationStatus> deleteResource(String resourceId); @@ -80,39 +76,31 @@ public interface IResourceOperation extends IComponentOperation { // public Either<List<ArtifactDefinition>, StorageOperationStatus> // getResourceArtifactsForDelete(Resource resource); - public Either<List<Resource>, StorageOperationStatus> getFollowed(String userId, - Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, boolean inTransaction); + public Either<List<Resource>, StorageOperationStatus> getFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, boolean inTransaction); - public Either<Set<Resource>, StorageOperationStatus> getCatalogData(Map<String, Object> propertiesToMatch, - boolean inTransaction); + public Either<Set<Resource>, StorageOperationStatus> getCatalogData(Map<String, Object> propertiesToMatch, boolean inTransaction); public Either<Resource, StorageOperationStatus> getLatestByName(String resourceName, boolean inTransaction); - public Either<Resource, StorageOperationStatus> overrideResource(Resource resource, Resource resourceSaved, - boolean inTransaction); + public Either<Resource, StorageOperationStatus> overrideResource(Resource resource, Resource resourceSaved, boolean inTransaction); - public Either<List<Resource>, StorageOperationStatus> getTesterFollowed(String userId, - Set<LifecycleStateEnum> lifecycleStates, boolean inTransaction); + public Either<List<Resource>, StorageOperationStatus> getTesterFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, boolean inTransaction); public Either<List<Resource>, StorageOperationStatus> getResourceListByUuid(String uuid, boolean inTransaction); public Either<List<Resource>, StorageOperationStatus> getLatestResourceByUuid(String uuid, boolean inTransaction); - public Either<List<Resource>, StorageOperationStatus> getResourceListBySystemName(String systemName, - boolean inTransaction); + public Either<List<Resource>, StorageOperationStatus> getResourceListBySystemName(String systemName, boolean inTransaction); public Either<List<Resource>, StorageOperationStatus> getResourceCatalogData(boolean inTransaction); - public Either<List<Resource>, StorageOperationStatus> getResourceCatalogDataVFLatestCertifiedAndNonCertified( - boolean inTransaction); + public Either<List<Resource>, StorageOperationStatus> getResourceCatalogDataVFLatestCertifiedAndNonCertified(boolean inTransaction); - public Either<List<Resource>, StorageOperationStatus> getResourceByNameAndVersion(String name, String version, - boolean inTransaction); + public Either<List<Resource>, StorageOperationStatus> getResourceByNameAndVersion(String name, String version, boolean inTransaction); public Either<List<Resource>, StorageOperationStatus> getResourceByNameAndVersion(String name, String version); - public Either<Resource, StorageOperationStatus> getResourceBySystemNameAndVersion(String name, String version, - Map<String, Object> additionalParams, boolean inTransaction); + public Either<Resource, StorageOperationStatus> getResourceBySystemNameAndVersion(String name, String version, Map<String, Object> additionalParams, boolean inTransaction); // public Either<List<Resource>, StorageOperationStatus> // getAllNotCheckoutResources(boolean getAbstract); @@ -124,8 +112,35 @@ public interface IResourceOperation extends IComponentOperation { public Either<Boolean, StorageOperationStatus> isResourceInUse(String resourceToDelete); - public Either<Resource, StorageOperationStatus> getLatestByToscaResourceName(String toscaResourceName, - boolean inTransaction); + public Either<Resource, StorageOperationStatus> getLatestByToscaResourceName(String toscaResourceName, boolean inTransaction); public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExists(String templateName); + + public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends); + + /** + * + * @param resource the resource to look for its derived resources + * @return all resources which derives from the given resource + */ + Either<List<Resource>, StorageOperationStatus> getAllDerivedResources(Resource resource); + + /** + * + * @return all root resources (i.e all normatives with tosca name {@code Resource.ROOT_RESOURCE} + */ + Either<List<Resource>, StorageOperationStatus> getRootResources(); + + /** + * + * @return all resources with type VF + */ + Either<List<Resource>, StorageOperationStatus> getVFResources(); + + /** + * + * @return all resources + */ + Either<List<Resource>, StorageOperationStatus> getAll(); + } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IServiceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IServiceOperation.java index 05eb7c66f6..f08c52e0fa 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IServiceOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IServiceOperation.java @@ -40,8 +40,6 @@ public interface IServiceOperation extends IComponentOperation { public Either<Service, StorageOperationStatus> getService(String uniqueId); public Either<Service, StorageOperationStatus> getService(String uniqueId, boolean inTransaction); - // public Either<Service, StorageOperationStatus> getService_tx(String - // uniqueId, boolean inTransaction); public Either<Service, StorageOperationStatus> deleteService(String uniqueId); @@ -49,40 +47,33 @@ public interface IServiceOperation extends IComponentOperation { public Either<Boolean, StorageOperationStatus> validateServiceNameExists(String serviceName); - public Either<List<Service>, StorageOperationStatus> getFollowed(String userId, - Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, boolean inTransaction); + public Either<List<Service>, StorageOperationStatus> getFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, boolean inTransaction); public Either<Service, StorageOperationStatus> updateService(Service service, boolean inTransaction); - public Either<Set<Service>, StorageOperationStatus> getCatalogData(Map<String, Object> propertiesToMatch, - boolean inTransaction); + public Either<Set<Service>, StorageOperationStatus> getCatalogData(Map<String, Object> propertiesToMatch, boolean inTransaction); - public Either<List<Service>, StorageOperationStatus> getTesterFollowed(String userId, - Set<LifecycleStateEnum> lifecycleStates, boolean inTransaction); + public Either<List<Service>, StorageOperationStatus> getTesterFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, boolean inTransaction); - public Either<Set<Service>, StorageOperationStatus> getCertifiedServicesWithDistStatus( - Map<String, Object> propertiesToMatch, Set<DistributionStatusEnum> distStatus, boolean inTransaction); + public Either<Set<Service>, StorageOperationStatus> getCertifiedServicesWithDistStatus(Map<String, Object> propertiesToMatch, Set<DistributionStatusEnum> distStatus, boolean inTransaction); - public Either<Service, StorageOperationStatus> updateDestributionStatus(Service service, User user, - DistributionStatusEnum distributionStatus); + public Either<Service, StorageOperationStatus> updateDestributionStatus(Service service, User user, DistributionStatusEnum distributionStatus); public Either<List<Service>, StorageOperationStatus> getServiceCatalogData(boolean inTransaction); - public Either<List<Service>, StorageOperationStatus> getServiceCatalogDataLatestCertifiedAndNotCertified( - boolean inTransaction); + public Either<List<Service>, StorageOperationStatus> getServiceCatalogDataLatestCertifiedAndNotCertified(boolean inTransaction); - public Either<Service, StorageOperationStatus> getServiceByNameAndVersion(String name, String version, - Map<String, Object> additionalParams, boolean inTransaction); + public Either<Service, StorageOperationStatus> getServiceByNameAndVersion(String name, String version, Map<String, Object> additionalParams, boolean inTransaction); public Either<Service, StorageOperationStatus> getServiceByNameAndVersion(String name, String version); - public Either<Service, StorageOperationStatus> getServiceBySystemNameAndVersion(String name, String version, - boolean inTransaction); + public Either<Service, StorageOperationStatus> getServiceBySystemNameAndVersion(String name, String version, boolean inTransaction); public Either<List<Service>, StorageOperationStatus> getServiceListByUuid(String uuid, boolean inTransaction); public Either<List<Service>, StorageOperationStatus> getLatestServiceByUuid(String uuid, boolean inTransaction); - public Either<List<Service>, StorageOperationStatus> getServiceListBySystemName(String systemName, - boolean inTransaction); + public Either<List<Service>, StorageOperationStatus> getServiceListBySystemName(String systemName, boolean inTransaction); + + Either<List<Service> , StorageOperationStatus> getAll(); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IUserAdminOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IUserAdminOperation.java index dd9766fc83..84413f7987 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IUserAdminOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IUserAdminOperation.java @@ -48,11 +48,11 @@ public interface IUserAdminOperation { public Either<List<User>, ActionStatus> getAllUsersWithRole(String role, String status); - public Either<List<Edge>, StorageOperationStatus> getUserPandingTasksList(User user, - Map<String, Object> properties); + Either<List<User>, ActionStatus> getAllUsers(); + + public Either<List<Edge>, StorageOperationStatus> getUserPandingTasksList(User user, Map<String, Object> properties); public Either<ImmutablePair<User, FunctionalMenuInfo>, ActionStatus> getUserDataWithFunctionalMenu(String userId); - public Either<FunctionalMenuInfo, TitanOperationStatus> createOrUpdateFunctionalMenu(String userId, - String newFunctionalMenu); + public Either<FunctionalMenuInfo, TitanOperationStatus> createOrUpdateFunctionalMenu(String userId, String newFunctionalMenu); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ToscaDefinitionPathCalculator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ToscaDefinitionPathCalculator.java new file mode 100644 index 0000000000..f64d4c9091 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/ToscaDefinitionPathCalculator.java @@ -0,0 +1,12 @@ +package org.openecomp.sdc.be.model.operations.api; + +import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; +import org.openecomp.sdc.be.model.ComponentInstance; + +import java.util.List; + +public interface ToscaDefinitionPathCalculator { + + List<String> calculateToscaDefinitionPath(ComponentInstance componentInstance, GraphEdge edge); + +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AbstractOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AbstractOperation.java index c4bbaf58f6..0f36f09ca8 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AbstractOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AbstractOperation.java @@ -198,7 +198,7 @@ public abstract class AbstractOperation { if (ctResult.isRight()) { TitanOperationStatus status = ctResult.right().value(); if (status != TitanOperationStatus.NOT_FOUND) { - log.error("Failed to retrieve information on element uniqueId:" + uniqueId + ". status is " + status); + log.error("Failed to retrieve information on element uniqueId: {}. status is {}", uniqueId, status); } result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(ctResult.right().value())); return result; @@ -314,13 +314,13 @@ public abstract class AbstractOperation { ImmutablePair<JsonElement, Boolean> validateResult = dataTypeValidatorConverter.validateAndUpdate(value, dataTypeDefinition, dataTypes); if (validateResult.right.booleanValue() == false) { - log.debug("The value {} of property from type {} is invalid", value, propertyType); + log.debug("The value {} of property from type {} is invalid", propertyType, propertyType); return StorageOperationStatus.INVALID_VALUE; } JsonElement jsonElement = validateResult.left; - log.trace("Going to update value in property definition {} {}", propertyDefinition.getName(), (jsonElement != null ? jsonElement.toString() : null)); + log.trace("Going to update value in property definition {} {}" , propertyDefinition.getName() , (jsonElement != null ? jsonElement.toString() : null)); updateValue(propertyDefinition, jsonElement); @@ -360,7 +360,7 @@ public abstract class AbstractOperation { } PropertyDataDefinition propDef = def.getProperty(); if (propDef == null) { - log.debug("Property in Schema Definition inside property of type {} doesn't exists", type); + log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); } innerType = propDef.getType(); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperation.java index e2c7f369f1..b9a67e5dc6 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperation.java @@ -26,9 +26,6 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; -import com.thinkaurelius.titan.core.TitanTransaction; -import com.thinkaurelius.titan.core.TitanVertex; - import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.openecomp.sdc.be.config.BeEcompErrorManager; @@ -41,8 +38,8 @@ import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.dao.titan.TitanGenericDao; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.model.AdditionalInfoParameterInfo; import org.openecomp.sdc.be.model.AdditionalInformationDefinition; import org.openecomp.sdc.be.model.operations.api.IAdditionalInformationOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; @@ -54,7 +51,9 @@ import org.openecomp.sdc.common.config.EcompErrorName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; -import org.springframework.util.AutoPopulatingList.ElementFactory; + +import com.thinkaurelius.titan.core.TitanTransaction; +import com.thinkaurelius.titan.core.TitanVertex; import fj.data.Either; @@ -62,7 +61,6 @@ import fj.data.Either; public class AdditionalInformationOperation implements IAdditionalInformationOperation { public static final String EMPTY_VALUE = null; - public static final String PROPERTY = "property"; public AdditionalInformationOperation() { super(); @@ -74,18 +72,15 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe private TitanGenericDao titanGenericDao; @Override - public Either<AdditionalInformationDefinition, TitanOperationStatus> addAdditionalInformationParameter( - NodeTypeEnum nodeType, String componentId, String key, String value) { + public Either<AdditionalInformationDefinition, TitanOperationStatus> addAdditionalInformationParameter(NodeTypeEnum nodeType, String componentId, String key, String value) { TitanOperationStatus verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId); if (verifyNodeTypeVsComponent != TitanOperationStatus.OK) { return Either.right(verifyNodeTypeVsComponent); } - Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao - .getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, - GraphEdgeLabels.ADDITIONAL_INFORMATION, NodeTypeEnum.AdditionalInfoParameters, - AdditionalInfoParameterData.class); + Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, GraphEdgeLabels.ADDITIONAL_INFORMATION, + NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class); if (getResult.isRight()) { TitanOperationStatus status = getResult.right().value(); @@ -117,39 +112,31 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe parameters.put(key, value); parameterData.getAdditionalInfoParameterDataDefinition().setLastCreatedCounter(lastCreatedCounter); - Either<AdditionalInfoParameterData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(parameterData, - AdditionalInfoParameterData.class); + Either<AdditionalInfoParameterData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(parameterData, AdditionalInfoParameterData.class); if (updateNode.isRight()) { TitanOperationStatus status = updateNode.right().value(); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedUpdateNodeError, - "UpdateAdditionalInformationParameter", - "additional information of " + nodeType.getName() + " " + componentId, String.valueOf(status)); - BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("UpdateAdditionalInformationParameter", - "additional information of " + nodeType.getName() + " " + componentId, String.valueOf(status)); + BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedUpdateNodeError, "UpdateAdditionalInformationParameter", "additional information of " + nodeType.getName() + " " + componentId, String.valueOf(status)); + BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("UpdateAdditionalInformationParameter", "additional information of " + nodeType.getName() + " " + componentId, String.valueOf(status)); return Either.right(status); } - AdditionalInformationDefinition informationDefinition = createInformationDefinitionFromNode(componentId, - parameters, idToKey, updateNode.left().value()); + AdditionalInformationDefinition informationDefinition = createInformationDefinitionFromNode(componentId, parameters, idToKey, updateNode.left().value()); return Either.left(informationDefinition); } @Override - public Either<AdditionalInformationDefinition, TitanOperationStatus> updateAdditionalInformationParameter( - NodeTypeEnum nodeType, String componentId, String id, String key, String value) { + public Either<AdditionalInformationDefinition, TitanOperationStatus> updateAdditionalInformationParameter(NodeTypeEnum nodeType, String componentId, String id, String key, String value) { TitanOperationStatus verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId); if (verifyNodeTypeVsComponent != TitanOperationStatus.OK) { return Either.right(verifyNodeTypeVsComponent); } - Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao - .getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, - GraphEdgeLabels.ADDITIONAL_INFORMATION, NodeTypeEnum.AdditionalInfoParameters, - AdditionalInfoParameterData.class); + Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, GraphEdgeLabels.ADDITIONAL_INFORMATION, + NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class); if (getResult.isRight()) { TitanOperationStatus status = getResult.right().value(); @@ -172,44 +159,36 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe return Either.right(TitanOperationStatus.ALREADY_EXIST); } String removed = parameters.remove(origKey); - log.trace("The key-value " + origKey + "=" + removed + " was removed from additionalInformation"); + log.trace("The key-value {} = {} was removed from additionalInformation", origKey, removed); } parameters.put(key, value); idToKey.put(id, key); - Either<AdditionalInfoParameterData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(parameterData, - AdditionalInfoParameterData.class); + Either<AdditionalInfoParameterData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(parameterData, AdditionalInfoParameterData.class); if (updateNode.isRight()) { TitanOperationStatus status = updateNode.right().value(); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedUpdateNodeError, - "UpdateAdditionalInformationParameter", "additional information of resource " + componentId, - String.valueOf(status)); - BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("UpdateAdditionalInformationParameter", - "additional information of resource " + componentId, String.valueOf(status)); + BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedUpdateNodeError, "UpdateAdditionalInformationParameter", "additional information of resource " + componentId, String.valueOf(status)); + BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("UpdateAdditionalInformationParameter", "additional information of resource " + componentId, String.valueOf(status)); return Either.right(status); } - AdditionalInformationDefinition informationDefinition = createInformationDefinitionFromNode(componentId, - parameters, idToKey, updateNode.left().value()); + AdditionalInformationDefinition informationDefinition = createInformationDefinitionFromNode(componentId, parameters, idToKey, updateNode.left().value()); return Either.left(informationDefinition); } @Override - public Either<AdditionalInformationDefinition, TitanOperationStatus> deleteAdditionalInformationParameter( - NodeTypeEnum nodeType, String componentId, String id) { + public Either<AdditionalInformationDefinition, TitanOperationStatus> deleteAdditionalInformationParameter(NodeTypeEnum nodeType, String componentId, String id) { TitanOperationStatus verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId); if (verifyNodeTypeVsComponent != TitanOperationStatus.OK) { return Either.right(verifyNodeTypeVsComponent); } - Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao - .getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, - GraphEdgeLabels.ADDITIONAL_INFORMATION, NodeTypeEnum.AdditionalInfoParameters, - AdditionalInfoParameterData.class); + Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, GraphEdgeLabels.ADDITIONAL_INFORMATION, + NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class); if (getResult.isRight()) { TitanOperationStatus status = getResult.right().value(); @@ -228,41 +207,31 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe String key = idToKey.get(id); String removedKey = idToKey.remove(id); String removedValue = parameters.remove(key); - log.trace("The key-value " + removedKey + "=" + removedValue + " was removed from additionalInformation"); + log.trace("The key-value {} = {} was removed from additionalInformation", removedKey, removedValue); - Either<AdditionalInfoParameterData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(parameterData, - AdditionalInfoParameterData.class); + Either<AdditionalInfoParameterData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(parameterData, AdditionalInfoParameterData.class); if (updateNode.isRight()) { TitanOperationStatus status = updateNode.right().value(); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedUpdateNodeError, - "DeleteAdditionalInformationParameter", - "additional information of " + nodeType.getName() + " " + componentId, String.valueOf(status)); - BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("DeleteAdditionalInformationParameter", - "additional information of " + nodeType.getName() + " " + componentId, String.valueOf(status)); + BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedUpdateNodeError, "DeleteAdditionalInformationParameter", "additional information of " + nodeType.getName() + " " + componentId, String.valueOf(status)); + BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("DeleteAdditionalInformationParameter", "additional information of " + nodeType.getName() + " " + componentId, String.valueOf(status)); return Either.right(status); } - AdditionalInformationDefinition informationDefinition = createInformationDefinitionFromNode(componentId, - parameters, idToKey, updateNode.left().value()); + AdditionalInformationDefinition informationDefinition = createInformationDefinitionFromNode(componentId, parameters, idToKey, updateNode.left().value()); return Either.left(informationDefinition); } - private AdditionalInformationDefinition createInformationDefinitionFromNode(String resourceId, - Map<String, String> parameters, Map<String, String> idToKey, - AdditionalInfoParameterData additionalInfoParameterData) { - AdditionalInfoParameterDataDefinition dataDefinition = additionalInfoParameterData - .getAdditionalInfoParameterDataDefinition(); + private AdditionalInformationDefinition createInformationDefinitionFromNode(String resourceId, Map<String, String> parameters, Map<String, String> idToKey, AdditionalInfoParameterData additionalInfoParameterData) { + AdditionalInfoParameterDataDefinition dataDefinition = additionalInfoParameterData.getAdditionalInfoParameterDataDefinition(); - AdditionalInformationDefinition informationDefinition = new AdditionalInformationDefinition(dataDefinition, - resourceId, convertParameters(parameters, idToKey)); + AdditionalInformationDefinition informationDefinition = new AdditionalInformationDefinition(dataDefinition, resourceId, convertParameters(parameters, idToKey)); return informationDefinition; } - private List<AdditionalInfoParameterInfo> convertParameters(Map<String, String> parameters, - Map<String, String> idToKey) { + private List<AdditionalInfoParameterInfo> convertParameters(Map<String, String> parameters, Map<String, String> idToKey) { List<AdditionalInfoParameterInfo> list = new ArrayList<AdditionalInfoParameterInfo>(); @@ -284,8 +253,7 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe } @Override - public Either<AdditionalInfoParameterData, TitanOperationStatus> addAdditionalInformationNode(NodeTypeEnum nodeType, - String componentId) { + public Either<AdditionalInfoParameterData, TitanOperationStatus> addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId) { UniqueIdData from = new UniqueIdData(nodeType, componentId); @@ -293,25 +261,19 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe AdditionalInfoParameterDataDefinition additionalInfoParameterDataDefinition = new AdditionalInfoParameterDataDefinition(); additionalInfoParameterDataDefinition.setUniqueId(uniqueId); - AdditionalInfoParameterData additionalInfoParameterData = new AdditionalInfoParameterData( - additionalInfoParameterDataDefinition, new HashMap<String, String>(), new HashMap<String, String>()); + AdditionalInfoParameterData additionalInfoParameterData = new AdditionalInfoParameterData(additionalInfoParameterDataDefinition, new HashMap<String, String>(), new HashMap<String, String>()); - Either<AdditionalInfoParameterData, TitanOperationStatus> createNode = titanGenericDao - .createNode(additionalInfoParameterData, AdditionalInfoParameterData.class); + Either<AdditionalInfoParameterData, TitanOperationStatus> createNode = titanGenericDao.createNode(additionalInfoParameterData, AdditionalInfoParameterData.class); if (createNode.isRight()) { TitanOperationStatus status = createNode.right().value(); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedCreateNodeError, - "AddAdditionalInformationNode", - "additional information to " + nodeType.getName() + " " + componentId, String.valueOf(status)); - BeEcompErrorManager.getInstance().logBeFailedCreateNodeError("AddAdditionalInformationNode", uniqueId, - String.valueOf(status)); + BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedCreateNodeError, "AddAdditionalInformationNode", "additional information to " + nodeType.getName() + " " + componentId, String.valueOf(status)); + BeEcompErrorManager.getInstance().logBeFailedCreateNodeError("AddAdditionalInformationNode", uniqueId, String.valueOf(status)); return Either.right(status); } AdditionalInfoParameterData to = createNode.left().value(); - Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(from, to, - GraphEdgeLabels.ADDITIONAL_INFORMATION, null); + Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(from, to, GraphEdgeLabels.ADDITIONAL_INFORMATION, null); if (createRelation.isRight()) { TitanOperationStatus status = createRelation.right().value(); return Either.right(status); @@ -321,31 +283,25 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe } @Override - public Either<TitanVertex, TitanOperationStatus> addAdditionalInformationNode(NodeTypeEnum nodeType, - String componentId, TitanVertex metadataVertex) { + public Either<TitanVertex, TitanOperationStatus> addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId, TitanVertex metadataVertex) { String uniqueId = UniqueIdBuilder.buildAdditionalInformationUniqueId(componentId); AdditionalInfoParameterDataDefinition additionalInfoParameterDataDefinition = new AdditionalInfoParameterDataDefinition(); additionalInfoParameterDataDefinition.setUniqueId(uniqueId); - AdditionalInfoParameterData additionalInfoParameterData = new AdditionalInfoParameterData( - additionalInfoParameterDataDefinition, new HashMap<String, String>(), new HashMap<String, String>()); + AdditionalInfoParameterData additionalInfoParameterData = new AdditionalInfoParameterData(additionalInfoParameterDataDefinition, new HashMap<String, String>(), new HashMap<String, String>()); Either<TitanVertex, TitanOperationStatus> createNode = titanGenericDao.createNode(additionalInfoParameterData); if (createNode.isRight()) { TitanOperationStatus status = createNode.right().value(); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedCreateNodeError, - "AddAdditionalInformationNode", - "additional information to " + nodeType.getName() + " " + componentId, String.valueOf(status)); - BeEcompErrorManager.getInstance().logBeFailedCreateNodeError("AddAdditionalInformationNode", uniqueId, - String.valueOf(status)); + BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedCreateNodeError, "AddAdditionalInformationNode", "additional information to " + nodeType.getName() + " " + componentId, String.valueOf(status)); + BeEcompErrorManager.getInstance().logBeFailedCreateNodeError("AddAdditionalInformationNode", uniqueId, String.valueOf(status)); return Either.right(status); } TitanVertex additionalInfoVertex = createNode.left().value(); - TitanOperationStatus createRelation = titanGenericDao.createEdge(metadataVertex, additionalInfoVertex, - GraphEdgeLabels.ADDITIONAL_INFORMATION, null); + TitanOperationStatus createRelation = titanGenericDao.createEdge(metadataVertex, additionalInfoVertex, GraphEdgeLabels.ADDITIONAL_INFORMATION, null); if (!createRelation.equals(TitanOperationStatus.OK)) { return Either.right(createRelation); @@ -353,11 +309,9 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe return Either.left(additionalInfoVertex); } - public Either<AdditionalInformationDefinition, TitanOperationStatus> addAdditionalInformationNode( - NodeTypeEnum nodeType, String componentId, AdditionalInformationDefinition parameters) { + public Either<AdditionalInformationDefinition, TitanOperationStatus> addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId, AdditionalInformationDefinition parameters) { - Either<AdditionalInfoParameterData, TitanOperationStatus> status = this.addAdditionalInformationNode(nodeType, - componentId); + Either<AdditionalInfoParameterData, TitanOperationStatus> status = this.addAdditionalInformationNode(nodeType, componentId); if (status.isRight()) { return Either.right(status.right().value()); @@ -367,24 +321,20 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe populateParameterNodeWithParameters(parameterData, parameters); - Either<AdditionalInfoParameterData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(parameterData, - AdditionalInfoParameterData.class); + Either<AdditionalInfoParameterData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(parameterData, AdditionalInfoParameterData.class); if (updateNode.isRight()) { return Either.right(updateNode.right().value()); } - AdditionalInformationDefinition informationDefinition = convertAdditionalInformationDataToDefinition( - updateNode.left().value(), componentId); + AdditionalInformationDefinition informationDefinition = convertAdditionalInformationDataToDefinition(updateNode.left().value(), componentId); return Either.left(informationDefinition); } - public TitanOperationStatus addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId, - AdditionalInformationDefinition parameters, TitanVertex metadataVertex) { + public TitanOperationStatus addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId, AdditionalInformationDefinition parameters, TitanVertex metadataVertex) { - Either<TitanVertex, TitanOperationStatus> status = this.addAdditionalInformationNode(nodeType, componentId, - metadataVertex); + Either<TitanVertex, TitanOperationStatus> status = this.addAdditionalInformationNode(nodeType, componentId, metadataVertex); if (status.isRight()) { return status.right().value(); @@ -392,9 +342,7 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe TitanVertex additionalInfoVertex = status.left().value(); Map<String, Object> newProp = titanGenericDao.getProperties(additionalInfoVertex); - AdditionalInfoParameterData parameterData = GraphElementFactory.createElement( - NodeTypeEnum.AdditionalInfoParameters.getName(), GraphElementTypeEnum.Node, newProp, - AdditionalInfoParameterData.class); + AdditionalInfoParameterData parameterData = GraphElementFactory.createElement(NodeTypeEnum.AdditionalInfoParameters.getName(), GraphElementTypeEnum.Node, newProp, AdditionalInfoParameterData.class); populateParameterNodeWithParameters(parameterData, parameters); @@ -403,14 +351,13 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe return updateNode; } - private void populateParameterNodeWithParameters(AdditionalInfoParameterData parameterData, - AdditionalInformationDefinition aiDefinition) { + private void populateParameterNodeWithParameters(AdditionalInfoParameterData parameterData, AdditionalInformationDefinition aiDefinition) { if (aiDefinition != null) { Integer lastCreatedCounter = aiDefinition.getLastCreatedCounter(); parameterData.getAdditionalInfoParameterDataDefinition().setLastCreatedCounter(lastCreatedCounter); - log.trace("Set last created counter of additional information to " + lastCreatedCounter); + log.trace("Set last created counter of additional information to {}", lastCreatedCounter); List<AdditionalInfoParameterInfo> parameters = aiDefinition.getParameters(); if (parameters != null) { @@ -435,26 +382,22 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe } @Override - public TitanOperationStatus findResourceAllAdditionalInformationRecursively(String uniqueId, - List<AdditionalInformationDefinition> properties) { + public TitanOperationStatus findResourceAllAdditionalInformationRecursively(String uniqueId, List<AdditionalInformationDefinition> properties) { - log.trace("Going to fetch additional information under resource " + uniqueId); - TitanOperationStatus resourceCapabilitiesStatus = findAdditionalInformationOfNode(NodeTypeEnum.Resource, - uniqueId, properties); + log.trace("Going to fetch additional information under resource {}", uniqueId); + TitanOperationStatus resourceCapabilitiesStatus = findAdditionalInformationOfNode(NodeTypeEnum.Resource, uniqueId, properties); if (!resourceCapabilitiesStatus.equals(TitanOperationStatus.OK)) { return resourceCapabilitiesStatus; } - Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> parentNodes = titanGenericDao - .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), uniqueId, - GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource, ResourceMetadataData.class); + Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> parentNodes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), uniqueId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource, + ResourceMetadataData.class); if (parentNodes.isRight()) { TitanOperationStatus parentNodesStatus = parentNodes.right().value(); if (false == parentNodesStatus.equals(TitanOperationStatus.NOT_FOUND)) { - log.error("Failed to find parent additional information of resource " + uniqueId + ". status is " - + parentNodesStatus); + log.error("Failed to find parent additional information of resource {}. status is {}", uniqueId, parentNodesStatus); return parentNodesStatus; } } @@ -462,11 +405,10 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe if (parentNodes.isLeft()) { ImmutablePair<ResourceMetadataData, GraphEdge> parnetNodePair = parentNodes.left().value(); String parentUniqueId = parnetNodePair.getKey().getMetadataDataDefinition().getUniqueId(); - TitanOperationStatus addParentIntStatus = findResourceAllAdditionalInformationRecursively(parentUniqueId, - properties); + TitanOperationStatus addParentIntStatus = findResourceAllAdditionalInformationRecursively(parentUniqueId, properties); if (addParentIntStatus != TitanOperationStatus.OK) { - log.error("Failed to find all resource additional information of resource " + parentUniqueId); + log.error("Failed to find all resource additional information of resource {}", parentUniqueId); return addParentIntStatus; } } @@ -475,26 +417,22 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe } @Override - public TitanOperationStatus findServiceAllAdditionalInformationRecursively(String uniqueId, - List<AdditionalInformationDefinition> properties) { + public TitanOperationStatus findServiceAllAdditionalInformationRecursively(String uniqueId, List<AdditionalInformationDefinition> properties) { - log.trace("Going to fetch additional information under service " + uniqueId); - TitanOperationStatus resourceCapabilitiesStatus = findAdditionalInformationOfNode(NodeTypeEnum.Service, - uniqueId, properties); + log.trace("Going to fetch additional information under service {}", uniqueId); + TitanOperationStatus resourceCapabilitiesStatus = findAdditionalInformationOfNode(NodeTypeEnum.Service, uniqueId, properties); if (!resourceCapabilitiesStatus.equals(TitanOperationStatus.OK)) { return resourceCapabilitiesStatus; } - Either<ImmutablePair<ServiceMetadataData, GraphEdge>, TitanOperationStatus> parentNodes = titanGenericDao - .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Service), uniqueId, - GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Service, ServiceMetadataData.class); + Either<ImmutablePair<ServiceMetadataData, GraphEdge>, TitanOperationStatus> parentNodes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Service), uniqueId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Service, + ServiceMetadataData.class); if (parentNodes.isRight()) { TitanOperationStatus parentNodesStatus = parentNodes.right().value(); if (false == parentNodesStatus.equals(TitanOperationStatus.NOT_FOUND)) { - log.error("Failed to find parent additional information of resource " + uniqueId + ". status is " - + parentNodesStatus); + log.error("Failed to find parent additional information of resource {}. status is {}", uniqueId, parentNodesStatus); return parentNodesStatus; } } @@ -502,11 +440,10 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe if (parentNodes.isLeft()) { ImmutablePair<ServiceMetadataData, GraphEdge> parnetNodePair = parentNodes.left().value(); String parentUniqueId = parnetNodePair.getKey().getMetadataDataDefinition().getUniqueId(); - TitanOperationStatus addParentIntStatus = findServiceAllAdditionalInformationRecursively(parentUniqueId, - properties); + TitanOperationStatus addParentIntStatus = findServiceAllAdditionalInformationRecursively(parentUniqueId, properties); if (addParentIntStatus != TitanOperationStatus.OK) { - log.error("Failed to find all resource additional information of resource " + parentUniqueId); + log.error("Failed to find all resource additional information of resource {}", parentUniqueId); return addParentIntStatus; } } @@ -514,12 +451,10 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe } - private TitanOperationStatus findAdditionalInformationOfNode(NodeTypeEnum nodeType, String uniqueId, - List<AdditionalInformationDefinition> properties) { + private TitanOperationStatus findAdditionalInformationOfNode(NodeTypeEnum nodeType, String uniqueId, List<AdditionalInformationDefinition> properties) { - Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> childNode = titanGenericDao - .getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, GraphEdgeLabels.ADDITIONAL_INFORMATION, - NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class); + Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> childNode = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, GraphEdgeLabels.ADDITIONAL_INFORMATION, + NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class); if (childNode.isRight()) { TitanOperationStatus status = childNode.right().value(); @@ -534,8 +469,7 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe Map<String, String> parameters = propertyData.getParameters(); if (parameters != null && false == parameters.isEmpty()) { - AdditionalInformationDefinition additionalInfoDef = this - .convertAdditionalInformationDataToDefinition(propertyData, uniqueId); + AdditionalInformationDefinition additionalInfoDef = this.convertAdditionalInformationDataToDefinition(propertyData, uniqueId); properties.add(additionalInfoDef); } @@ -543,36 +477,29 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe } - private AdditionalInformationDefinition convertAdditionalInformationDataToDefinition( - AdditionalInfoParameterData additionalInfoData, String uniqueId) { + private AdditionalInformationDefinition convertAdditionalInformationDataToDefinition(AdditionalInfoParameterData additionalInfoData, String uniqueId) { Map<String, String> parameters = additionalInfoData.getParameters(); Map<String, String> idToKey = additionalInfoData.getIdToKey(); - AdditionalInformationDefinition definition = new AdditionalInformationDefinition( - additionalInfoData.getAdditionalInfoParameterDataDefinition(), uniqueId, - convertParameters(parameters, idToKey)); + AdditionalInformationDefinition definition = new AdditionalInformationDefinition(additionalInfoData.getAdditionalInfoParameterDataDefinition(), uniqueId, convertParameters(parameters, idToKey)); return definition; } @Override - public Either<AdditionalInformationDefinition, StorageOperationStatus> createAdditionalInformationParameter( - NodeTypeEnum nodeType, String resourceId, String key, String value, boolean inTransaction) { + public Either<AdditionalInformationDefinition, StorageOperationStatus> createAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String key, String value, boolean inTransaction) { Either<AdditionalInformationDefinition, StorageOperationStatus> result = null; try { - Either<AdditionalInformationDefinition, TitanOperationStatus> either = this - .addAdditionalInformationParameter(nodeType, resourceId, key, value); + Either<AdditionalInformationDefinition, TitanOperationStatus> either = this.addAdditionalInformationParameter(nodeType, resourceId, key, value); if (either.isRight()) { TitanOperationStatus status = either.right().value(); log.debug("Failed to add additional information property {} to component {}. Status is {}", key, resourceId, status); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedUpdateNodeError, - "additional information of " + nodeType.getName() + " " + resourceId, String.valueOf(status)); - BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("CreateAdditionalInformationParameter", - "additional information of " + nodeType.getName() + " " + resourceId, String.valueOf(status)); + BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedUpdateNodeError, "additional information of " + nodeType.getName() + " " + resourceId, String.valueOf(status)); + BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("CreateAdditionalInformationParameter", "additional information of " + nodeType.getName() + " " + resourceId, String.valueOf(status)); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); } else { AdditionalInformationDefinition additionalInformationDefinition = either.left().value(); @@ -587,18 +514,16 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe } @Override - public Either<AdditionalInformationDefinition, StorageOperationStatus> updateAdditionalInformationParameter( - NodeTypeEnum nodeType, String resourceId, String id, String key, String value, boolean inTransaction) { + public Either<AdditionalInformationDefinition, StorageOperationStatus> updateAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String id, String key, String value, boolean inTransaction) { Either<AdditionalInformationDefinition, StorageOperationStatus> result = null; try { - Either<AdditionalInformationDefinition, TitanOperationStatus> either = this - .updateAdditionalInformationParameter(nodeType, resourceId, id, key, value); + Either<AdditionalInformationDefinition, TitanOperationStatus> either = this.updateAdditionalInformationParameter(nodeType, resourceId, id, key, value); if (either.isRight()) { - log.info("Failed to update additional information property " + key + " to component " + resourceId); + log.info("Failed to update additional information property {} to component {}", key, resourceId); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(either.right().value())); } else { AdditionalInformationDefinition additionalInformationDefinition = either.left().value(); @@ -614,18 +539,16 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe } @Override - public Either<AdditionalInformationDefinition, StorageOperationStatus> deleteAdditionalInformationParameter( - NodeTypeEnum nodeType, String resourceId, String id, boolean inTransaction) { + public Either<AdditionalInformationDefinition, StorageOperationStatus> deleteAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String id, boolean inTransaction) { Either<AdditionalInformationDefinition, StorageOperationStatus> result = null; try { - Either<AdditionalInformationDefinition, TitanOperationStatus> either = this - .deleteAdditionalInformationParameter(nodeType, resourceId, id); + Either<AdditionalInformationDefinition, TitanOperationStatus> either = this.deleteAdditionalInformationParameter(nodeType, resourceId, id); if (either.isRight()) { - log.error("Failed to delete additional information id " + id + " to component " + resourceId); + log.error("Failed to delete additional information id {} to component {}", id, resourceId); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(either.right().value())); } else { AdditionalInformationDefinition additionalInformationDefinition = either.left().value(); @@ -641,8 +564,7 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe } @Override - public Either<Integer, StorageOperationStatus> getNumberOfAdditionalInformationParameters(NodeTypeEnum nodeType, - String resourceId, boolean inTransaction) { + public Either<Integer, StorageOperationStatus> getNumberOfAdditionalInformationParameters(NodeTypeEnum nodeType, String resourceId, boolean inTransaction) { Either<Integer, StorageOperationStatus> result = null; @@ -651,7 +573,7 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe Either<Integer, TitanOperationStatus> either = this.getNumberOfParameters(nodeType, resourceId); if (either.isRight()) { - log.error("Failed to get the number of additional information properties in component " + resourceId); + log.error("Failed to get the number of additional information properties in component {}", resourceId); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(either.right().value())); } else { Integer counter = either.left().value(); @@ -676,10 +598,8 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe @Override public Either<Integer, TitanOperationStatus> getNumberOfParameters(NodeTypeEnum nodeType, String resourceId) { - Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao - .getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), resourceId, - GraphEdgeLabels.ADDITIONAL_INFORMATION, NodeTypeEnum.AdditionalInfoParameters, - AdditionalInfoParameterData.class); + Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), resourceId, GraphEdgeLabels.ADDITIONAL_INFORMATION, + NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class); if (getResult.isRight()) { TitanOperationStatus status = getResult.right().value(); @@ -700,18 +620,15 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe } @Override - public Either<AdditionalInfoParameterInfo, TitanOperationStatus> getAdditionalInformationParameter( - NodeTypeEnum nodeType, String componentId, String id) { + public Either<AdditionalInfoParameterInfo, TitanOperationStatus> getAdditionalInformationParameter(NodeTypeEnum nodeType, String componentId, String id) { TitanOperationStatus verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId); if (verifyNodeTypeVsComponent != TitanOperationStatus.OK) { return Either.right(verifyNodeTypeVsComponent); } - Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao - .getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, - GraphEdgeLabels.ADDITIONAL_INFORMATION, NodeTypeEnum.AdditionalInfoParameters, - AdditionalInfoParameterData.class); + Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, GraphEdgeLabels.ADDITIONAL_INFORMATION, + NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class); if (getResult.isRight()) { TitanOperationStatus status = getResult.right().value(); @@ -730,19 +647,15 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe String key = idToKey.get(id); String value = parameters.get(key); - log.trace("The key-value " + key + "=" + value + " was retrieved for id " + id); + log.trace("The key-value {} = {} was retrieved for id {}", key, value, id); - Either<AdditionalInfoParameterData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(parameterData, - AdditionalInfoParameterData.class); + Either<AdditionalInfoParameterData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(parameterData, AdditionalInfoParameterData.class); if (updateNode.isRight()) { TitanOperationStatus status = updateNode.right().value(); if (status != TitanOperationStatus.NOT_FOUND) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedRetrieveNodeError, - "GetAdditionnalInformationParameter", - "additional information of " + nodeType.getName() + " " + componentId, String.valueOf(status)); - BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("GetAdditionnalInformationParameter", - "additional information of " + nodeType.getName() + " " + componentId, String.valueOf(status)); + BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedRetrieveNodeError, "GetAdditionnalInformationParameter", "additional information of " + nodeType.getName() + " " + componentId, String.valueOf(status)); + BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("GetAdditionnalInformationParameter", "additional information of " + nodeType.getName() + " " + componentId, String.valueOf(status)); } return Either.right(status); } @@ -754,8 +667,7 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe } @Override - public Either<AdditionalInformationDefinition, TitanOperationStatus> getAllAdditionalInformationParameters( - NodeTypeEnum nodeType, String componentId, boolean ignoreVerification) { + public Either<AdditionalInformationDefinition, TitanOperationStatus> getAllAdditionalInformationParameters(NodeTypeEnum nodeType, String componentId, boolean ignoreVerification) { if (false == ignoreVerification) { TitanOperationStatus verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId); @@ -764,19 +676,14 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe } } - Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao - .getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, - GraphEdgeLabels.ADDITIONAL_INFORMATION, NodeTypeEnum.AdditionalInfoParameters, - AdditionalInfoParameterData.class); + Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, GraphEdgeLabels.ADDITIONAL_INFORMATION, + NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class); if (getResult.isRight()) { TitanOperationStatus status = getResult.right().value(); if (status != TitanOperationStatus.NOT_FOUND) { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedRetrieveNodeError, - "GetAdditionnalInformationParameters", - "additional information of " + nodeType.getName() + " " + componentId, String.valueOf(status)); - BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("GetAdditionnalInformationParameters", - "additional information of " + nodeType.getName() + " " + componentId, String.valueOf(status)); + BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedRetrieveNodeError, "GetAdditionnalInformationParameters", "additional information of " + nodeType.getName() + " " + componentId, String.valueOf(status)); + BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("GetAdditionnalInformationParameters", "additional information of " + nodeType.getName() + " " + componentId, String.valueOf(status)); } return Either.right(status); } @@ -786,23 +693,20 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe Map<String, String> parameters = parameterData.getParameters(); Map<String, String> idToKey = parameterData.getIdToKey(); - AdditionalInformationDefinition informationDefinition = createInformationDefinitionFromNode(componentId, - parameters, idToKey, parameterData); + AdditionalInformationDefinition informationDefinition = createInformationDefinitionFromNode(componentId, parameters, idToKey, parameterData); return Either.left(informationDefinition); } @Override - public Either<AdditionalInformationDefinition, StorageOperationStatus> getAllAdditionalInformationParameters( - NodeTypeEnum nodeType, String resourceId, boolean ignoreVerification, boolean inTransaction) { + public Either<AdditionalInformationDefinition, StorageOperationStatus> getAllAdditionalInformationParameters(NodeTypeEnum nodeType, String resourceId, boolean ignoreVerification, boolean inTransaction) { Either<AdditionalInformationDefinition, StorageOperationStatus> result = null; try { - Either<AdditionalInformationDefinition, TitanOperationStatus> either = this - .getAllAdditionalInformationParameters(nodeType, resourceId, ignoreVerification); + Either<AdditionalInformationDefinition, TitanOperationStatus> either = this.getAllAdditionalInformationParameters(nodeType, resourceId, ignoreVerification); if (either.isRight()) { TitanOperationStatus status = either.right().value(); @@ -833,8 +737,7 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe } } - private void commitOrRollbackTx(TitanTransaction tx, boolean inTransaction, - Either<? extends Object, StorageOperationStatus> result) { + private void commitOrRollbackTx(TitanTransaction tx, boolean inTransaction, Either<? extends Object, StorageOperationStatus> result) { if (false == inTransaction) { if (result == null || result.isRight()) { @@ -848,19 +751,16 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe } @Override - public Either<AdditionalInfoParameterInfo, StorageOperationStatus> getAdditionalInformationParameter( - NodeTypeEnum nodeType, String resourceId, String id, boolean inTransaction) { + public Either<AdditionalInfoParameterInfo, StorageOperationStatus> getAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String id, boolean inTransaction) { Either<AdditionalInfoParameterInfo, StorageOperationStatus> result = null; try { - Either<AdditionalInfoParameterInfo, TitanOperationStatus> either = this - .getAdditionalInformationParameter(nodeType, resourceId, id); + Either<AdditionalInfoParameterInfo, TitanOperationStatus> either = this.getAdditionalInformationParameter(nodeType, resourceId, id); if (either.isRight()) { - log.error("Failed to fetch additional information property with id " + id + " of component " - + resourceId); + log.error("Failed to fetch additional information property with id {} of component {}", id, resourceId); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(either.right().value())); } else { AdditionalInfoParameterInfo additionalInformationDefinition = either.left().value(); @@ -875,30 +775,22 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe } @Override - public Either<AdditionalInformationDefinition, StorageOperationStatus> deleteAllAdditionalInformationParameters( - NodeTypeEnum nodeType, String resourceId, boolean inTransaction) { + public Either<AdditionalInformationDefinition, StorageOperationStatus> deleteAllAdditionalInformationParameters(NodeTypeEnum nodeType, String resourceId, boolean inTransaction) { Either<AdditionalInformationDefinition, StorageOperationStatus> result = null; try { - Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao - .getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), resourceId, - GraphEdgeLabels.ADDITIONAL_INFORMATION, NodeTypeEnum.AdditionalInfoParameters, - AdditionalInfoParameterData.class); + Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), resourceId, GraphEdgeLabels.ADDITIONAL_INFORMATION, + NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class); if (getResult.isRight()) { TitanOperationStatus status = getResult.right().value(); if (status == TitanOperationStatus.NOT_FOUND) { return Either.right(StorageOperationStatus.OK); } else { - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedDeleteNodeError, - "DeleteAdditionalInformationNode", - "additional information of " + nodeType.getName() + " " + resourceId, - String.valueOf(status)); - BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError("DeleteAdditionalInformationNode", - "additional information of " + nodeType.getName() + " " + resourceId, - String.valueOf(status)); + BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedDeleteNodeError, "DeleteAdditionalInformationNode", "additional information of " + nodeType.getName() + " " + resourceId, String.valueOf(status)); + BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError("DeleteAdditionalInformationNode", "additional information of " + nodeType.getName() + " " + resourceId, String.valueOf(status)); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); } return result; @@ -907,21 +799,16 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe ImmutablePair<AdditionalInfoParameterData, GraphEdge> value = getResult.left().value(); AdditionalInfoParameterData parameterData = value.getLeft(); - Either<AdditionalInfoParameterData, TitanOperationStatus> deleteNodeRes = titanGenericDao - .deleteNode(parameterData, AdditionalInfoParameterData.class); + Either<AdditionalInfoParameterData, TitanOperationStatus> deleteNodeRes = titanGenericDao.deleteNode(parameterData, AdditionalInfoParameterData.class); if (deleteNodeRes.isRight()) { TitanOperationStatus status = getResult.right().value(); - BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedDeleteNodeError, - "DeleteAdditionalInformationNode", (String) parameterData.getUniqueId(), - String.valueOf(status)); - BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError("DeleteAdditionalInformationNode", - (String) parameterData.getUniqueId(), String.valueOf(status)); + BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedDeleteNodeError, "DeleteAdditionalInformationNode", (String) parameterData.getUniqueId(), String.valueOf(status)); + BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError("DeleteAdditionalInformationNode", (String) parameterData.getUniqueId(), String.valueOf(status)); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); return result; } - AdditionalInformationDefinition informationDefinition = convertAdditionalInformationDataToDefinition( - deleteNodeRes.left().value(), resourceId); + AdditionalInformationDefinition informationDefinition = convertAdditionalInformationDataToDefinition(deleteNodeRes.left().value(), resourceId); result = Either.left(informationDefinition); @@ -933,8 +820,7 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe } private TitanOperationStatus verifyNodeTypeVsComponent(NodeTypeEnum nodeType, String componentId) { - Either<TitanVertex, TitanOperationStatus> vertexByProperty = titanGenericDao - .getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId); + Either<TitanVertex, TitanOperationStatus> vertexByProperty = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId); if (vertexByProperty.isRight()) { TitanOperationStatus status = vertexByProperty.right().value(); if (status == TitanOperationStatus.NOT_FOUND) { diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperation.java index a4f4bebd5a..1e1c9267e6 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperation.java @@ -28,7 +28,6 @@ import java.util.List; import java.util.Map; import java.util.UUID; -import com.thinkaurelius.titan.core.TitanTransaction; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.tinkerpop.gremlin.structure.Direction; import org.apache.tinkerpop.gremlin.structure.Edge; @@ -81,6 +80,8 @@ public class ArtifactOperation implements IArtifactOperation { @javax.annotation.Resource private GroupOperation groupOperation; + @javax.annotation.Resource + private GroupInstanceOperation groupInstanceOperation; private static Logger log = LoggerFactory.getLogger(ArtifactOperation.class.getName()); @@ -113,7 +114,7 @@ public class ArtifactOperation implements IArtifactOperation { if (false == inTransaction) { titanGenericDao.rollback(); } - log.debug("Failed to add artifact {} to {} {}", artifactInfo.getArtifactName(), type, parentId); + log.debug("Failed to add artifact {} to {} {}", artifactInfo.getArtifactName(), type , parentId); return Either.right(status.right().value()); } else { if (false == inTransaction) { @@ -191,7 +192,7 @@ public class ArtifactOperation implements IArtifactOperation { // add heat parameters if (artifactInfo.getHeatParameters() != null && !artifactInfo.getHeatParameters().isEmpty() && !artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT_ENV.getType())) { - StorageOperationStatus addPropertiesStatus = heatParametersOperation.addPropertiesToGraph(artifactInfo.getHeatParameters(), artifactData.getUniqueId().toString(), NodeTypeEnum.ArtifactRef); + StorageOperationStatus addPropertiesStatus = heatParametersOperation.addPropertiesToGraph(artifactInfo.getListHeatParameters(), artifactData.getUniqueId().toString(), NodeTypeEnum.ArtifactRef); if (addPropertiesStatus != StorageOperationStatus.OK) { log.debug("Failed to create heat parameters on graph for artifact {}", artifactInfo.getArtifactName()); return addPropertiesStatus; @@ -238,7 +239,7 @@ public class ArtifactOperation implements IArtifactOperation { if (existArtifact.isRight()) { if (existArtifact.right().value().equals(TitanOperationStatus.NOT_FOUND)) { // create new node - log.debug("Before adding artifact to graph {}", artifactData); + log.debug("Before adding artifact to graph {}" , artifactData); if (artifactData.getArtifactDataDefinition().getArtifactUUID() == null || artifactData.getArtifactDataDefinition().getArtifactUUID().isEmpty()) updateUUID(artifactData.getArtifactDataDefinition(), null, artifactData.getArtifactDataDefinition().getArtifactVersion()); Either<ArtifactData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(artifactData, ArtifactData.class); @@ -256,7 +257,7 @@ public class ArtifactOperation implements IArtifactOperation { // add heat parameters if (artifactInfo.getHeatParameters() != null && !artifactInfo.getHeatParameters().isEmpty() && !artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT_ENV.getType())) { - StorageOperationStatus addPropertiesStatus = heatParametersOperation.addPropertiesToGraph(artifactInfo.getHeatParameters(), artifactData.getUniqueId().toString(), NodeTypeEnum.ArtifactRef); + StorageOperationStatus addPropertiesStatus = heatParametersOperation.addPropertiesToGraph(artifactInfo.getListHeatParameters(), artifactData.getUniqueId().toString(), NodeTypeEnum.ArtifactRef); if (addPropertiesStatus != StorageOperationStatus.OK) { log.debug("Failed to create heat parameters on graph for artifact {}", artifactInfo.getArtifactName()); return Either.right(addPropertiesStatus); @@ -283,7 +284,7 @@ public class ArtifactOperation implements IArtifactOperation { properties.put(GraphEdgePropertiesDictionary.GROUP_TYPE.getProperty(), artifactInfo.getArtifactGroupType().getType()); Either<GraphRelation, TitanOperationStatus> relation = titanGenericDao.createRelation(parent, artifactData, GraphEdgeLabels.ARTIFACT_REF, properties); if (relation.isRight()) { - log.debug("Failed to create relation in graph for id {} to new artifact", id); + log.debug("Failed to create relation in graph fro id {} to new artifact", id); return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(relation.right().value())); } @@ -300,19 +301,20 @@ public class ArtifactOperation implements IArtifactOperation { isValid = true; break; default: - log.debug("Not supported node type for artifact relation : {}", type); + log.debug("Not supported node type for artifact relation : {} ", type); } return isValid; } - + + protected ArtifactDefinition convertArtifactDataToArtifactDefinition(ArtifactData artifactDefResult) { - log.debug("The object returned after create property is {}", artifactDefResult); + log.debug("The object returned after create property is {}" ,artifactDefResult); ArtifactDefinition propertyDefResult = new ArtifactDefinition(artifactDefResult.getArtifactDataDefinition()); 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); + propertyDefResult.setListHeatParameters(parameters); } return propertyDefResult; } @@ -325,9 +327,35 @@ public class ArtifactOperation implements IArtifactOperation { if (false == inTransaction) { titanGenericDao.rollback(); } - if (log.isDebugEnabled()){ - log.debug("Failed to update artifact {} of {} {}. Status is {}", artifactId, type.getName(), id, status.right().value()); + log.debug("Failed to update artifact {} of {} {}. status is {}", artifactId, type.getName(), id, status.right().value()); + BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedUpdateNodeError, "Failed to update artifact " + artifactId + " of " + type.getName() + " " + id + ". status is" + status.right().value(), artifactId, + String.valueOf(status.right().value())); + BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("Update Artifact", artifactId, String.valueOf(status.right().value())); + return Either.right(status.right().value()); + } else { + if (false == inTransaction) { + titanGenericDao.commit(); } + ArtifactData artifactData = status.left().value(); + + ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(artifactData); + log.debug("The returned ArtifactDefintion is {}", artifactDefResult); + return Either.left(artifactDefResult); + } + } + + @Override + public Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact( String id, ArtifactDefinition artifactEnvInfo, String artifactId, String newArtifactId, NodeTypeEnum type, boolean inTransaction){ + + + Either<ArtifactData, StorageOperationStatus> status = dissociateAndAssociateHeatEnvArtifact(id, artifactEnvInfo, artifactId, newArtifactId, type, inTransaction); + + + if (status.isRight()) { + if (false == inTransaction) { + titanGenericDao.rollback(); + } + log.debug("Failed to update artifact {} of {} {}. status is {}", artifactId, type.getName(), id, status.right().value()); BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedUpdateNodeError, "Failed to update artifact " + artifactId + " of " + type.getName() + " " + id + ". status is" + status.right().value(), artifactId, String.valueOf(status.right().value())); BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("Update Artifact", artifactId, String.valueOf(status.right().value())); @@ -342,6 +370,47 @@ public class ArtifactOperation implements IArtifactOperation { log.debug("The returned ArtifactDefintion is {}", artifactDefResult); return Either.left(artifactDefResult); } + + } + + private Either<ArtifactData, StorageOperationStatus> dissociateAndAssociateHeatEnvArtifact(String id, ArtifactDefinition artifactEnvInfo, String artifactId, String newArtifactId, NodeTypeEnum type, boolean inTransaction) { + + ArtifactDefinition heatEnvArt = artifactEnvInfo; + if(heatEnvArt == null ){ + Either<ArtifactDefinition, StorageOperationStatus> heatEnvEither = getHeatEnvByGeneratedFromId(artifactId); + if (heatEnvEither.isRight()) { + log.error("No heat env artifact node for id = {} ", artifactId); + return Either.right(StorageOperationStatus.NOT_FOUND); + } + heatEnvArt = heatEnvEither.left().value(); + } + + Either<ArtifactData, StorageOperationStatus> status = updateArtifactOnGraph(heatEnvArt, heatEnvArt.getUniqueId(), type, id); + if(status.isRight()){ + log.error("Failed to update heat env. status is {}", status.right().value()); + return status; + } + + UniqueIdData generatedFromArtifactNode = new UniqueIdData(NodeTypeEnum.ArtifactRef, heatEnvArt.getUniqueId()); + UniqueIdData oldArtifactNode = new UniqueIdData(NodeTypeEnum.ArtifactRef, artifactId); + + Either<GraphRelation, TitanOperationStatus> deleteRelation = titanGenericDao.deleteRelation(generatedFromArtifactNode, oldArtifactNode, GraphEdgeLabels.GENERATED_FROM); + if (deleteRelation.isRight()) { + TitanOperationStatus titanStatus = deleteRelation.right().value(); + if (titanStatus == TitanOperationStatus.NOT_FOUND) { + titanStatus = TitanOperationStatus.INVALID_ID; + } + Either.right(titanStatus); + } + + UniqueIdData newArtifactNode = new UniqueIdData(NodeTypeEnum.ArtifactRef, newArtifactId); + + Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(generatedFromArtifactNode, newArtifactNode, GraphEdgeLabels.GENERATED_FROM, null); + if (createRelation.isRight()) { + log.error("Failed to create relation from heat_env {} to heat {}", newArtifactId, generatedFromArtifactNode); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createRelation.right().value())); + } + return status; } @Override @@ -368,6 +437,45 @@ public class ArtifactOperation implements IArtifactOperation { return Either.left(artifactDefResult); } } + + @Override + public Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvPlaceholder(ArtifactDefinition artifactInfo, boolean inTransaction) { + + updateVersionAndDate(artifactInfo, artifactInfo.getArtifactVersion()); + + Either<ArtifactData, TitanOperationStatus> status = updateArifactDataDefinition(artifactInfo); + + if (status.isRight()) { + if (false == inTransaction) { + titanGenericDao.rollback(); + } + log.debug("Failed to update artifact {}", artifactInfo.getUniqueId()); + BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedUpdateNodeError, "Failed to update artifact " + artifactInfo.getUniqueId() + ". status is" + status.right().value(), artifactInfo.getUniqueId(), + String.valueOf(status.right().value())); + BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("Update Artifact", artifactInfo.getUniqueId(), String.valueOf(status.right().value())); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status.right().value())); + } else { + if (false == inTransaction) { + titanGenericDao.commit(); + } + ArtifactData artifactData = status.left().value(); + + ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(artifactData); + log.debug("The returned ArtifactDefintion is {}" , artifactDefResult); + return Either.left(artifactDefResult); + } + } + + @Override + public Either<ArtifactDefinition, StorageOperationStatus> getHeatEnvByGeneratedFromId(String generatedFromId) { + String heatEnvId = generatedFromId.concat("env"); + Either<ArtifactDefinition, StorageOperationStatus> heatEnvEither = getArtifactById(heatEnvId, true); + if (heatEnvEither.isRight()) { + log.error("No heat env artifact node for id = {} ", heatEnvId); + return Either.right(StorageOperationStatus.NOT_FOUND); + } + return heatEnvEither; + } private Either<ArtifactData, TitanOperationStatus> updateArifactDataDefinition(ArtifactDefinition artifactInfo) { Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph(); @@ -388,7 +496,7 @@ public class ArtifactOperation implements IArtifactOperation { @Override public Either<ArtifactDefinition, StorageOperationStatus> removeArifactFromResource(String id, String artifactId, NodeTypeEnum type, boolean deleteMandatoryArtifact, boolean inTransaction) { - Either<ArtifactData, TitanOperationStatus> status = removeArtifactOnGraph(id, artifactId, type, id, deleteMandatoryArtifact); + Either<ArtifactData, TitanOperationStatus> status = removeArtifactOnGraph(id, artifactId, type, deleteMandatoryArtifact); if (status.isRight()) { if (false == inTransaction) { @@ -406,7 +514,7 @@ public class ArtifactOperation implements IArtifactOperation { ArtifactData artifactData = status.left().value(); ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(artifactData); - log.debug("The returned ArtifactDefintion is {}", artifactDefResult); + log.debug("The returned ArtifactDefintion is {}" , artifactDefResult); return Either.left(artifactDefResult); } } @@ -447,12 +555,17 @@ public class ArtifactOperation implements IArtifactOperation { } ++edgeCount; } + + if (isNeedUpdateHeatTime(artifactInfo)) { + artifactInfo.setHeatParamsUpdateDate(System.currentTimeMillis()); + } ArtifactData artifactData = new ArtifactData(artifactInfo); if (edgeFromTo == null) { log.debug("No relation between artifact = {} and node with id = {}", artifactId, id); return Either.right(StorageOperationStatus.GENERAL_ERROR); } + Either<Boolean, StorageOperationStatus> setRelevantHeatParamIdRes = null; if (edgeCount > 1) { // need to remove relation, create new node @@ -477,6 +590,13 @@ public class ArtifactOperation implements IArtifactOperation { BeEcompErrorManager.getInstance().logInternalFlowError("UpdateArtifact", "Failed to reassociate groups to the new artifact", ErrorSeverity.ERROR); return Either.right(reassociateGroupsFromArtifact); } + + StorageOperationStatus reassociateGroupInstancesFromArtifact = groupInstanceOperation.dissociateAndAssociateGroupsInstanceFromArtifact(id, type, artifactId, addedArtifactRes.left().value()); + if (reassociateGroupInstancesFromArtifact != StorageOperationStatus.OK) { + BeEcompErrorManager.getInstance().logInternalFlowError("UpdateArtifact", "Failed to reassociate group instances to the new artifact", ErrorSeverity.ERROR); + return Either.right(reassociateGroupsFromArtifact); + } + // If artifact is heat env if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT_ENV.getType())) { ArtifactData addedArtifact = addedArtifactRes.left().value(); @@ -485,13 +605,13 @@ public class ArtifactOperation implements IArtifactOperation { setRelevantHeatParamIdRes = setRelevantHeatParamId(artifactV, artifactInfo); if (setRelevantHeatParamIdRes.isRight()) { - log.error("Failed to set relevant id to heat parameters for heat env artifact " + artifactInfo.getUniqueId() + ". Status is " + setRelevantHeatParamIdRes.right().value()); + log.error("Failed to set relevant id to heat parameters for heat env artifact {}. Status is {}", artifactInfo.getUniqueId(), setRelevantHeatParamIdRes.right().value()); return Either.right(setRelevantHeatParamIdRes.right().value()); } - for (HeatParameterDefinition heatEnvParam : artifactInfo.getHeatParameters()) { + for (HeatParameterDefinition heatEnvParam : artifactInfo.getListHeatParameters()) { updateResult = heatParametersOperation.updateHeatParameterValue(heatEnvParam, newArtifactUniqueId, id, artifactInfo.getArtifactLabel()); if (updateResult.isRight()) { - log.error("Failed to update heat parameter " + heatEnvParam.getName() + ". Status is " + updateResult.right().value()); + log.error("Failed to update heat parameter {}. Status is {}", heatEnvParam.getName(), updateResult.right().value()); return Either.right(updateResult.right().value()); } } @@ -499,7 +619,7 @@ public class ArtifactOperation implements IArtifactOperation { Iterator<Edge> iterEdgeGeneratedFrom = artifactV.edges(Direction.OUT, GraphEdgeLabels.GENERATED_FROM.getProperty()); if (!iterEdgeGeneratedFrom.hasNext()) { - log.error("No heat artifact node for id = " + artifactId); + log.error("No heat artifact node for id = {}", artifactId); return Either.right(StorageOperationStatus.NOT_FOUND); } Edge edgeToHeat = iterEdgeGeneratedFrom.next(); @@ -508,7 +628,7 @@ public class ArtifactOperation implements IArtifactOperation { UniqueIdData generatedFromArtifactNode = new UniqueIdData(NodeTypeEnum.ArtifactRef, generatedFromArtifactId); Either<GraphRelation, TitanOperationStatus> createRelationToGeneratedFromArtifactRes = titanGenericDao.createRelation(addedArtifact, generatedFromArtifactNode, GraphEdgeLabels.GENERATED_FROM, null); if (createRelationToGeneratedFromArtifactRes.isRight()) { - log.error("Failed to create relation from heat_env " + addedArtifact.getUniqueId() + " to heat " + generatedFromArtifactNode); + log.error("Failed to create relation from heat_env {} to heat {}", addedArtifact.getUniqueId(), generatedFromArtifactNode); return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createRelationToGeneratedFromArtifactRes.right().value())); } } @@ -535,10 +655,10 @@ public class ArtifactOperation implements IArtifactOperation { log.error("Failed to set relevant id to heat parameters for heat env artifact {}. Status is {}", artifactInfo.getUniqueId(), setRelevantHeatParamIdRes.right().value()); return Either.right(setRelevantHeatParamIdRes.right().value()); } - for (HeatParameterDefinition heatEnvParam : artifactInfo.getHeatParameters()) { + for (HeatParameterDefinition heatEnvParam : artifactInfo.getListHeatParameters()) { updateResult = heatParametersOperation.updateHeatParameterValue(heatEnvParam, artifactUniqueId, id, artifactInfo.getArtifactLabel()); if (updateResult.isRight()) { - log.error("Failed to update heat parameter " + heatEnvParam.getName() + ". Status is " + updateResult.right().value()); + log.error("Failed to update heat parameter {}. Status is {}", heatEnvParam.getName(), updateResult.right().value()); return Either.right(updateResult.right().value()); } } @@ -546,7 +666,7 @@ public class ArtifactOperation implements IArtifactOperation { if (artifactData.getArtifactDataDefinition().getArtifactChecksum() == null) { // update heat parameters only if it is not heat env if (artifactInfo.getGeneratedFromId() == null) { - StorageOperationStatus operationStatus = heatParametersOperation.updateHeatParameters(artifactInfo.getHeatParameters()); + StorageOperationStatus operationStatus = heatParametersOperation.updateHeatParameters(artifactInfo.getListHeatParameters()); if (operationStatus != StorageOperationStatus.OK) { return Either.right(operationStatus); } @@ -558,11 +678,12 @@ public class ArtifactOperation implements IArtifactOperation { return Either.right(StorageOperationStatus.GENERAL_ERROR); } - StorageOperationStatus addParameters = heatParametersOperation.addPropertiesToGraph(artifactInfo.getHeatParameters(), artifactId, NodeTypeEnum.ArtifactRef); + StorageOperationStatus addParameters = heatParametersOperation.addPropertiesToGraph(artifactInfo.getListHeatParameters(), artifactId, NodeTypeEnum.ArtifactRef); if (!addParameters.equals(StorageOperationStatus.OK)) { log.debug("failed to update heat parameters for artifact id {}", artifactData.getUniqueId()); return Either.right(StorageOperationStatus.GENERAL_ERROR); } + } } @@ -574,13 +695,20 @@ public class ArtifactOperation implements IArtifactOperation { } } + private boolean isNeedUpdateHeatTime(ArtifactDefinition artifactInfo) { + if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT_NET.getType()) || artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT_VOL.getType())) { + return true; + } + return false; + } + private Either<Boolean, StorageOperationStatus> setRelevantHeatParamId(TitanVertex artifactV, ArtifactDefinition artifactInfo) { Map<String, String> heatParametersHM = new HashMap<String, String>(); Iterator<Edge> iterHeat = artifactV.edges(Direction.OUT, GraphEdgeLabels.GENERATED_FROM.getProperty()); if (!iterHeat.hasNext()) { - log.debug("No edges with label GENERATED_FROM for the node {}", artifactInfo.getUniqueId()); + log.debug("No edges with label GENERATED_FROM for the node {}" , artifactInfo.getUniqueId()); return Either.right(StorageOperationStatus.NOT_FOUND); } Edge heat = iterHeat.next(); @@ -603,7 +731,7 @@ public class ArtifactOperation implements IArtifactOperation { heatParametersHM.put(heatParam.getName(), (String) heatParam.getUniqueId()); } String curName = null; - for (HeatParameterDefinition heatEnvParam : artifactInfo.getHeatParameters()) { + for (HeatParameterDefinition heatEnvParam : artifactInfo.getListHeatParameters()) { curName = heatEnvParam.getName(); if (heatParametersHM.containsKey(curName)) { heatEnvParam.setUniqueId(heatParametersHM.get(curName)); @@ -635,7 +763,7 @@ public class ArtifactOperation implements IArtifactOperation { return Either.left(edgeCount); } - public Either<ArtifactData, TitanOperationStatus> removeArtifactOnGraph(String id, String artifactId, NodeTypeEnum type, String id2, boolean deleteMandatoryArtifact) { + public Either<ArtifactData, TitanOperationStatus> removeArtifactOnGraph(String id, String artifactId, NodeTypeEnum type, boolean deleteMandatoryArtifact) { Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph(); if (graph.isRight()) { return Either.right(graph.right().value()); @@ -675,7 +803,7 @@ public class ArtifactOperation implements IArtifactOperation { ++edgeCount; } if (edgeFromTo == null) { - log.debug("No relation between artifact = {} and node with id = {}", artifactId, id); + log.debug("No relation between artifact = {} and node with id = {}", artifactId, id); return Either.right(TitanOperationStatus.GENERAL_ERROR); } @@ -702,13 +830,13 @@ public class ArtifactOperation implements IArtifactOperation { log.debug("Remove artifactRef node from graph"); Either<List<HeatParameterDefinition>, StorageOperationStatus> deleteStatus = heatParametersOperation.deleteAllHeatParametersAssociatedToNode(NodeTypeEnum.ArtifactRef, artifactId); if (deleteStatus.isRight()) { - log.error("failed to delete heat parameters of artifact " + artifactId); + log.error("failed to delete heat parameters of artifact {}", artifactId); return Either.right(TitanOperationStatus.GENERAL_ERROR); } StorageOperationStatus deleteValuesStatus = heatParametersOperation.deleteAllHeatValuesAssociatedToNode(NodeTypeEnum.ArtifactRef, artifactId); if (!deleteValuesStatus.equals(StorageOperationStatus.OK)) { - log.error("failed to delete heat values of artifact " + artifactId); + log.error("failed to delete heat values of artifact {}", artifactId); return Either.right(TitanOperationStatus.GENERAL_ERROR); } if (!isMandatory) { @@ -764,6 +892,12 @@ public class ArtifactOperation implements IArtifactOperation { if (artifact != null) { ArtifactDefinition artifactDefinition = new ArtifactDefinition(artifact.getArtifactDataDefinition()); + Iterator<Edge> edgesGeneratedFrom = artifactV.edges(Direction.OUT, GraphEdgeLabels.GENERATED_FROM.getProperty()); + if (edgesGeneratedFrom != null && edgesGeneratedFrom.hasNext()) { + TitanVertex inVertex = (TitanVertex) edgesGeneratedFrom.next().inVertex(); + String artifactIdGeneratedFrom = (String) titanGenericDao.getProperty(inVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty()); + artifactDefinition.setGeneratedFromId(artifactIdGeneratedFrom); + } List<HeatParameterDefinition> heatParams = new ArrayList<HeatParameterDefinition>(); StorageOperationStatus heatParametersStatus = heatParametersOperation.getHeatParametersOfNode(NodeTypeEnum.ArtifactRef, artifactDefinition.getUniqueId(), heatParams); if (!heatParametersStatus.equals(StorageOperationStatus.OK)) { @@ -771,7 +905,7 @@ public class ArtifactOperation implements IArtifactOperation { return Either.right(heatParametersStatus); } if (!heatParams.isEmpty()) { - artifactDefinition.setHeatParameters(heatParams); + artifactDefinition.setListHeatParameters(heatParams); } artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); log.debug("Artifact was added to list {}", artifact.getUniqueId()); @@ -867,7 +1001,7 @@ public class ArtifactOperation implements IArtifactOperation { return Either.right(heatParametersStatus); } if (!heatParams.isEmpty()) { - artifactDef.setHeatParameters(heatParams); + artifactDef.setListHeatParameters(heatParams); } Either<ImmutablePair<ArtifactData, GraphEdge>, TitanOperationStatus> generatedFromArtifact = titanGenericDao.getChild(artifactData.getUniqueIdKey(), (String) artifactData.getUniqueId(), GraphEdgeLabels.GENERATED_FROM, @@ -882,7 +1016,7 @@ public class ArtifactOperation implements IArtifactOperation { log.debug("failed to get heat parameters values for heat artifact {}", artifactDef.getUniqueId()); return Either.right(heatParamsForEnv.right().value()); } else { - artifactDef.setHeatParameters(heatParamsForEnv.left().value()); + artifactDef.setListHeatParameters(heatParamsForEnv.left().value()); } } @@ -1003,7 +1137,7 @@ public class ArtifactOperation implements IArtifactOperation { return Either.right(heatParametersStatus); } if (!heatParams.isEmpty()) { - artifactDefinition.setHeatParameters(heatParams); + artifactDefinition.setListHeatParameters(heatParams); } Either<ImmutablePair<ArtifactData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactDefinition.getUniqueId(), GraphEdgeLabels.GENERATED_FROM, @@ -1039,45 +1173,40 @@ public class ArtifactOperation implements IArtifactOperation { } @Override - public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifactHeat, String parentId, NodeTypeEnum parentType, boolean inTransaction) { - - Either<ArtifactDefinition, StorageOperationStatus> result = null; - try { - Either<ArtifactDefinition, StorageOperationStatus> heatArtifactOnGraph = addArifactToComponent(artifactHeatEnv, parentId, parentType, true, true); - - if (heatArtifactOnGraph.isRight()) { - log.debug("failed to create heat env artifact on graph"); - result = heatArtifactOnGraph; - return result; - } - - ArtifactDefinition artifactDefinition = heatArtifactOnGraph.left().value(); + public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifactHeat, String parentId, NodeTypeEnum parentType, boolean failIfExist) { - // add relation from heatEnv to heat - UniqueIdData heatData = new UniqueIdData(NodeTypeEnum.ArtifactRef, artifactHeat.getUniqueId()); - UniqueIdData heatEnvData = new UniqueIdData(NodeTypeEnum.ArtifactRef, artifactDefinition.getUniqueId()); - Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(heatEnvData, heatData, GraphEdgeLabels.GENERATED_FROM, null); - - if (createRelation.isRight()) { - TitanOperationStatus status = createRelation.right().value(); - log.debug("failed to add relation from heat_env artifact to heat artifact. error: {}", status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - artifactDefinition.setGeneratedFromId(artifactHeat.getUniqueId()); - log.trace("heat env artifact added successfuly to resource instance"); - result = Either.left(artifactDefinition); + Either<ArtifactDefinition, StorageOperationStatus> result = null; + Either<ArtifactDefinition, StorageOperationStatus> heatArtifactOnGraph = addArifactToComponent(artifactHeatEnv, parentId, parentType, failIfExist, true); + if (heatArtifactOnGraph.isRight()) { + log.debug("failed to create heat env artifact on graph"); + result = heatArtifactOnGraph; return result; - } finally { - if (inTransaction == false) { - if (result == null || result.isRight()) { - this.titanGenericDao.rollback(); - } else { - this.titanGenericDao.commit(); - } - - } } + + ArtifactDefinition artifactDefinition = heatArtifactOnGraph.left().value(); + // add relation from heatEnv to heat + UniqueIdData heatData = new UniqueIdData(NodeTypeEnum.ArtifactRef, artifactHeat.getUniqueId()); + UniqueIdData heatEnvData = new UniqueIdData(NodeTypeEnum.ArtifactRef, artifactDefinition.getUniqueId()); + + Either<GraphRelation, TitanOperationStatus> relation = titanGenericDao.getRelation(heatEnvData, heatData, GraphEdgeLabels.GENERATED_FROM); + if (relation.isRight()) { + // TODO: add error in case of error + TitanOperationStatus status = relation.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(heatEnvData, heatData, GraphEdgeLabels.GENERATED_FROM, null); + if (createRelation.isRight()) { + status = createRelation.right().value(); + log.debug("failed to add relation from heat_env artifact to heat artifact. error: {}", status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + return result; + } + } + } + + artifactDefinition.setGeneratedFromId(artifactHeat.getUniqueId()); + log.trace("heat env artifact added successfuly to resource instance"); + result = Either.left(artifactDefinition); + return result; } public void updateUUID(ArtifactDataDefinition artifactData, String oldChecksum, String oldVesrion) { @@ -1100,6 +1229,10 @@ public class ArtifactOperation implements IArtifactOperation { UUID uuid = UUID.randomUUID(); artifactData.setArtifactUUID(uuid.toString()); MDC.put("serviceInstanceID", uuid.toString()); + updateVersionAndDate(artifactData, oldVesrion); + } + + private void updateVersionAndDate(ArtifactDataDefinition artifactData, String oldVesrion) { long time = System.currentTimeMillis(); artifactData.setPayloadUpdateDate(time); int newVersion = new Integer(oldVesrion).intValue(); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AttributeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AttributeOperation.java index fc81a9affd..f82a2982b0 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AttributeOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AttributeOperation.java @@ -239,9 +239,9 @@ public class AttributeOperation extends AbstractOperation implements IAttributeO List<ComponentInstanceAttribute> buildAttInstanceFromResource = attributes.stream().map(attDef -> new ComponentInstanceAttribute(attDef, false, null)).collect(Collectors.toList()); // Set Value to be default value in case it is empty - Consumer<ComponentInstanceAttribute> valueSetter = data -> { - if (StringUtils.isEmpty(data.getValue())) { - data.setValue(data.getDefaultValue()); + Consumer<ComponentInstanceAttribute> valueSetter = att -> { + if (StringUtils.isEmpty(att.getValue())) { + att.setValue(att.getDefaultValue()); } }; buildAttInstanceFromResource.stream().forEach(valueSetter); @@ -438,7 +438,7 @@ public class AttributeOperation extends AbstractOperation implements IAttributeO Either<AttributeData, TitanOperationStatus> eitherResult; StorageOperationStatus validateAndUpdateAttribute = propertyOperation.validateAndUpdateProperty(attribute, dataTypes); if (validateAndUpdateAttribute != StorageOperationStatus.OK) { - log.error("Attribute " + attribute + " is invalid. Status is " + validateAndUpdateAttribute); + log.error("Attribute {} is invalid. Status is {}", attribute, validateAndUpdateAttribute); eitherResult = Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); } else { eitherResult = addAttributeToNodeType(attribute, NodeTypeEnum.Resource, resourceId); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CacheMangerOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CacheMangerOperation.java index d05255473d..cadcd32926 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CacheMangerOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CacheMangerOperation.java @@ -31,10 +31,8 @@ import org.openecomp.sdc.be.model.cache.jobs.*; import org.openecomp.sdc.be.model.cache.workers.CacheWorker; import org.openecomp.sdc.be.model.cache.workers.IWorker; import org.openecomp.sdc.be.model.cache.workers.SyncWorker; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation; -import org.openecomp.sdc.be.model.operations.api.IProductOperation; -import org.openecomp.sdc.be.model.operations.api.IResourceOperation; -import org.openecomp.sdc.be.model.operations.api.IServiceOperation; import org.openecomp.sdc.be.workers.Manager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -47,18 +45,12 @@ import java.util.LinkedList; import java.util.concurrent.*; /** - * Created by mlando on 9/5/2016. the class is responsible for handling all - * cache update operations asynchronously including sync between the graph and - * cache and on demand update requests + * Created by mlando on 9/5/2016. the class is responsible for handling all cache update operations asynchronously including sync between the graph and cache and on demand update requests */ @Component("cacheManger-operation") public class CacheMangerOperation implements ICacheMangerOperation { @Autowired - private IResourceOperation iResourceOperation; - @Autowired - private IServiceOperation iServiceOperation; - @Autowired - private IProductOperation iProductOperation; + private ToscaOperationFacade toscaOperationFacade; @Autowired private TitanGenericDao titanGenericDao; @Autowired @@ -76,21 +68,17 @@ public class CacheMangerOperation implements ICacheMangerOperation { * constructor */ public CacheMangerOperation() { - // daoInfo = new DaoInfo(iResourceOperation, iServiceOperation, - // iProductOperation, componentCache); } /** - * the method checks in the cache is enabled, if it is, it initializes all - * the workers according to the configuration values. + * the method checks in the cache is enabled, if it is, it initializes all the workers according to the configuration values. */ @PostConstruct public void init() { - daoInfo = new DaoInfo(iResourceOperation, iServiceOperation, iProductOperation, componentCache); + daoInfo = new DaoInfo(toscaOperationFacade, componentCache); - Configuration.ApplicationL2CacheConfig applicationL2CacheConfig = ConfigurationManager.getConfigurationManager() - .getConfiguration().getApplicationL2Cache(); + Configuration.ApplicationL2CacheConfig applicationL2CacheConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getApplicationL2Cache(); if (applicationL2CacheConfig != null && applicationL2CacheConfig.isEnabled()) { Integer numberOfWorkers = applicationL2CacheConfig.getQueue().getNumberOfCacheWorkers(); this.waitOnShutDownInMinutes = applicationL2CacheConfig.getQueue().getWaitOnShutDownInMinutes(); @@ -122,9 +110,7 @@ public class CacheMangerOperation implements ICacheMangerOperation { } /** - * the method creates a job to check it the given component is in the cach - * and if so is it valid if the value in the cache is not valid it will be - * updated. + * the method creates a job to check it the given component is in the cach and if so is it valid if the value in the cache is not valid it will be updated. * * @param componentId * the uid of the component we want to update @@ -135,24 +121,21 @@ public class CacheMangerOperation implements ICacheMangerOperation { */ @Override public void updateComponentInCache(String componentId, long timestamp, NodeTypeEnum nodeTypeEnum) { - Configuration.ApplicationL2CacheConfig applicationL2CacheConfig = ConfigurationManager.getConfigurationManager() - .getConfiguration().getApplicationL2Cache(); + Configuration.ApplicationL2CacheConfig applicationL2CacheConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getApplicationL2Cache(); if (applicationL2CacheConfig != null && applicationL2CacheConfig.isEnabled()) { this.jobQueue.add(new CheckAndUpdateJob(daoInfo, componentId, nodeTypeEnum, timestamp)); } } public void overideComponentInCache(String componentId, long timestamp, NodeTypeEnum nodeTypeEnum) { - Configuration.ApplicationL2CacheConfig applicationL2CacheConfig = ConfigurationManager.getConfigurationManager() - .getConfiguration().getApplicationL2Cache(); + Configuration.ApplicationL2CacheConfig applicationL2CacheConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getApplicationL2Cache(); if (applicationL2CacheConfig != null && applicationL2CacheConfig.isEnabled()) { this.jobQueue.add(new OverrideJob(daoInfo, componentId, nodeTypeEnum, timestamp)); } } public void deleteComponentInCache(String componentId, long timestamp, NodeTypeEnum nodeTypeEnum) { - Configuration.ApplicationL2CacheConfig applicationL2CacheConfig = ConfigurationManager.getConfigurationManager() - .getConfiguration().getApplicationL2Cache(); + Configuration.ApplicationL2CacheConfig applicationL2CacheConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getApplicationL2Cache(); if (applicationL2CacheConfig != null && applicationL2CacheConfig.isEnabled()) { this.jobQueue.add(new DeleteJob(daoInfo, componentId, nodeTypeEnum, timestamp)); } @@ -168,17 +151,14 @@ public class CacheMangerOperation implements ICacheMangerOperation { */ @Override public void storeComponentInCache(org.openecomp.sdc.be.model.Component component, NodeTypeEnum nodeTypeEnum) { - Configuration.ApplicationL2CacheConfig applicationL2CacheConfig = ConfigurationManager.getConfigurationManager() - .getConfiguration().getApplicationL2Cache(); + Configuration.ApplicationL2CacheConfig applicationL2CacheConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getApplicationL2Cache(); if (applicationL2CacheConfig != null && applicationL2CacheConfig.isEnabled()) { this.jobQueue.add(new StoreJob(daoInfo, component, nodeTypeEnum)); } } /** - * the method shutdown's all the worker's. the method has a pre set of how - * long it will wait for the workers to shutdown. the pre defined value is - * taken from the configuration. + * the method shutdown's all the worker's. the method has a pre set of how long it will wait for the workers to shutdown. the pre defined value is taken from the configuration. */ @PreDestroy public void shutDown() { diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityInstanceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityInstanceOperation.java index 0c4f35fd54..818089feee 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityInstanceOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityInstanceOperation.java @@ -74,24 +74,6 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC private CapabilityOperation capabilityOperation; /** - * String constants for logger - */ - private String statusIs = ". status is "; - private String dot = "."; - private String onGraph = " on graph "; - private String ofRI = " of resource instance "; - private String toCapability = " to capability "; - private String toCI = " to capability instance "; - private String toProperty = " to property "; - private String forRI = " for resource instance "; - private String failedCreateCI = "Failed to create capability instance of capability "; - private String failedAddProperties = "Failed to add properties to capability instance "; - private String ofCI = " of component instance "; - private String failedDeletePropertyValues = "Failed to delete property values of capability instance "; - private String toValue = " to property value "; - private String fromRI = " from resource instance "; - - /** * create capability instance of capability with property values for resource instance * * @param resourceInstanceId @@ -184,13 +166,13 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC private Either<List<PropertyValueData>, TitanOperationStatus> addPropertyValueToCapabilityInstance(String resourceInstanceId, List<ComponentInstanceProperty> propertyValues, Wrapper<TitanOperationStatus> errorWrapper, Either<CapabilityInstData, TitanOperationStatus> createCapabilityRes, Wrapper<Map<String, PropertyDefinition>> defaultPropertiesWrapper, Wrapper<String> createdCapabilityInstanceIdWrapper) { Either<List<PropertyValueData>, TitanOperationStatus> addPropertyValuesRes; - log.debug("Before adding property values to capability instance {} dot", createdCapabilityInstanceIdWrapper.getInnerElement()); + log.debug("Before adding property values to capability instance {}.",createdCapabilityInstanceIdWrapper.getInnerElement()); addPropertyValuesRes = addPropertyValuesToCapabilityInstance(createCapabilityRes.left().value(), propertyValues, defaultPropertiesWrapper.getInnerElement()); if (addPropertyValuesRes.isRight()) { errorWrapper.setInnerElement(addPropertyValuesRes.right().value()); - log.debug("failedAddProperties {} ofRI {} statusIs {} dot", createdCapabilityInstanceIdWrapper.getInnerElement(), resourceInstanceId, errorWrapper.getInnerElement()); + log.debug("Failed to add properties to capability instance {} of resource instance {}. status is {}.", createdCapabilityInstanceIdWrapper.getInnerElement(), resourceInstanceId, errorWrapper.getInnerElement()); } - log.debug("After adding property values to capability instance {} status is {}.", createdCapabilityInstanceIdWrapper.getInnerElement(), errorWrapper.getInnerElement()); + log.debug("After adding property values to capability instance {}. status is {}.", createdCapabilityInstanceIdWrapper.getInnerElement(), errorWrapper.getInnerElement()); return addPropertyValuesRes; } @@ -200,9 +182,9 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC TitanOperationStatus addPropertyValuesRes = addPropertyValuesToCapabilityInstance(createCapabilityRes.left().value(), propertyValues, defaultPropertiesWrapper.getInnerElement()); if (!addPropertyValuesRes.equals(TitanOperationStatus.OK)) { errorWrapper.setInnerElement(addPropertyValuesRes); - log.debug("Failed to add properties to capability instance {} {} {} {} {}", createdCapabilityInstanceIdWrapper.getInnerElement(), ofRI, resourceInstanceId, statusIs, errorWrapper.getInnerElement()); + log.debug("Failed to add properties to capability instance {} of resource instance {}. status is {}", createdCapabilityInstanceIdWrapper.getInnerElement(), resourceInstanceId, errorWrapper.getInnerElement()); } - log.trace("After adding property values to capability instance {} {} {}", createdCapabilityInstanceIdWrapper.getInnerElement(), statusIs, errorWrapper.getInnerElement()); + log.trace("After adding property values to capability instance {}. status is {}", createdCapabilityInstanceIdWrapper.getInnerElement(), errorWrapper.getInnerElement()); return addPropertyValuesRes; } @@ -214,18 +196,19 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC createdCapabilityInstanceIdWrapper.setInnerElement(createdCapabilityInstance.getUniqueId()); Map<String, PropertyDefinition> defaultProperties = overrideCapabilityDefinitionWrapper.getInnerElement().getProperties().stream().collect(Collectors.toMap(PropertyDefinition::getName, Function.identity())); defaultPropertiesWrapper.setInnerElement(defaultProperties); - log.debug("Before validating property values of capability instance {}.", createdCapabilityInstanceIdWrapper.getInnerElement()); + log.debug("Before validating property values of capability instance {}",createdCapabilityInstanceIdWrapper.getInnerElement()); Either<Boolean, TitanOperationStatus> result = validateCapabilityInstanceProperties(defaultProperties, propertyValues); if (result.isRight()) { errorWrapper.setInnerElement(result.right().value()); - log.debug("failedAddProperties {} ofRI {} statusIs {}.", createdCapabilityInstanceIdWrapper.getInnerElement(), resourceInstanceId, errorWrapper.getInnerElement()); + log.debug("Failed to add properties to capability instance {} of resource instance {}. status is {}.", createdCapabilityInstanceIdWrapper.getInnerElement(), resourceInstanceId, errorWrapper.getInnerElement()); } - log.debug("After validating property values of capability instance {} status is {}.", createdCapabilityInstanceIdWrapper.getInnerElement(), errorWrapper.getInnerElement()); + log.debug("After validating property values of capability instance {}. status is {}", createdCapabilityInstanceIdWrapper.getInnerElement(), errorWrapper.getInnerElement()); return createdCapabilityInstance; } private TitanVertex validateCapabilityInstancePropertiesByVertex(String resourceInstanceId, List<ComponentInstanceProperty> propertyValues, Wrapper<TitanOperationStatus> errorWrapper, Wrapper<CapabilityDefinition> overrideCapabilityDefinitionWrapper, TitanVertex createCapabilityRes, Wrapper<Map<String, PropertyDefinition>> defaultPropertiesWrapper, Wrapper<String> createdCapabilityInstanceIdWrapper) { + String id = (String) titanGenericDao.getProperty(createCapabilityRes, GraphPropertiesDictionary.UNIQUE_ID.getProperty()); createdCapabilityInstanceIdWrapper.setInnerElement(id); Map<String, PropertyDefinition> defaultProperties = overrideCapabilityDefinitionWrapper.getInnerElement().getProperties().stream().collect(Collectors.toMap(PropertyDefinition::getName, Function.identity())); @@ -234,9 +217,9 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC Either<Boolean, TitanOperationStatus> result = validateCapabilityInstanceProperties(defaultProperties, propertyValues); if (result.isRight()) { errorWrapper.setInnerElement(result.right().value()); - log.debug("Failed to add properties to capability instance {} {} {} {} {}", createdCapabilityInstanceIdWrapper.getInnerElement(), ofRI, resourceInstanceId, statusIs, errorWrapper.getInnerElement()); + log.debug("Failed to add properties to capability instance {} of resource instance {}, status is {}", createdCapabilityInstanceIdWrapper.getInnerElement(), resourceInstanceId, errorWrapper.getInnerElement()); } - log.trace("After validating property values of capability instance {} {} {}", createdCapabilityInstanceIdWrapper.getInnerElement(), statusIs, errorWrapper.getInnerElement()); + log.trace("After validating property values of capability instance {}, status is {}", createdCapabilityInstanceIdWrapper.getInnerElement(), errorWrapper.getInnerElement()); return createCapabilityRes; } @@ -249,46 +232,46 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC createCapabilityRes = createCapabilityInstanceOnGraph(resourceInstanceId, overrideCapabilityDataWrapper.getInnerElement(), capabilityInstance); if (createCapabilityRes.isRight()) { errorWrapper.setInnerElement(createCapabilityRes.right().value()); - log.debug("failedCreateCI {} ofRI {} statusIs {}.", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); + log.debug("Failed to create capability instance of capability {} of resource instance {}, status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); } - log.debug("After creating capability instance of capability {} on graph. Status is {}", capabilityId, errorWrapper.getInnerElement()); + log.debug("After creating capability instance of capability {} on graph, status is {}", capabilityId, errorWrapper.getInnerElement()); return createCapabilityRes; } private Either<TitanVertex, TitanOperationStatus> createCapabilityInstanceOnGraphByVertex(TitanVertex riVertex, String resourceInstanceId, String capabilityId, Wrapper<TitanOperationStatus> errorWrapper, Wrapper<TitanVertex> overrideCapabilityDataWrapper, Wrapper<CapabilityDefinition> overrideCapabilityDefinitionWrapper, Either<CapabilityDefinition, TitanOperationStatus> getCapabilityDefinitionRes) { Either<TitanVertex, TitanOperationStatus> createCapabilityRes; - log.trace("Before creating capability instance of capability {} {}", capabilityId, onGraph); + log.trace("Before creating capability instance of capability {} on graph", capabilityId); overrideCapabilityDefinitionWrapper.setInnerElement(getCapabilityDefinitionRes.left().value()); CapabilityInstData capabilityInstance = buildCapabilityInstanceData(resourceInstanceId, overrideCapabilityDefinitionWrapper.getInnerElement()); createCapabilityRes = createCapabilityInstanceOnGraph(riVertex, resourceInstanceId, overrideCapabilityDataWrapper.getInnerElement(), capabilityInstance); if (createCapabilityRes.isRight()) { errorWrapper.setInnerElement(createCapabilityRes.right().value()); - log.debug("Failed to create capability instance of capability {} {} {} {} {} ", capabilityId, ofRI, resourceInstanceId, statusIs, errorWrapper.getInnerElement()); + log.debug("Failed to create capability instance of capability {} of resource instance {}, status is {} ", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); } - log.debug("After creating capability instance of capability {} {} {} {} {}", capabilityId, onGraph, statusIs, errorWrapper.getInnerElement()); + log.debug("After creating capability instance of capability {} on graph, status is {}", capabilityId, errorWrapper.getInnerElement()); return createCapabilityRes; } private Either<CapabilityDefinition, TitanOperationStatus> getCapabiityDefinition(String resourceInstanceId, String capabilityId, Wrapper<TitanOperationStatus> errorWrapper, Wrapper<CapabilityData> overrideCapabilityDataWrapper, Either<ImmutablePair<CapabilityData, GraphEdge>, TitanOperationStatus> getCapabilityRes) { Either<CapabilityDefinition, TitanOperationStatus> getCapabilityDefinitionRes; - log.debug("Before getting capability definition {} forRI {}.", capabilityId, resourceInstanceId); + log.debug("Before getting capability definition {} for resource instance {}", capabilityId, resourceInstanceId); CapabilityData overrideCapabilityData = getCapabilityRes.left().value().getLeft(); overrideCapabilityDataWrapper.setInnerElement(overrideCapabilityData); getCapabilityDefinitionRes = capabilityOperation.getCapabilityByCapabilityData(overrideCapabilityData); if (getCapabilityDefinitionRes.isRight()) { errorWrapper.setInnerElement(getCapabilityDefinitionRes.right().value()); - log.debug("Failed to retrieve capability {} ofRI {} statusIs {}.", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); + log.debug("Failed to retrieve capability {} of resource instance {}, status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); } - log.debug("After getting capability definition for {} forRI {} statusIs {}.", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); + log.debug("After getting capability definition for {} for resource instance {}, status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); return getCapabilityDefinitionRes; } private Either<CapabilityDefinition, TitanOperationStatus> getCapabiityDefinitionByVertex(String resourceInstanceId, String capabilityId, Wrapper<TitanOperationStatus> errorWrapper, Wrapper<TitanVertex> overrideCapabilityDataWrapper, Either<ImmutablePair<TitanVertex, Edge>, TitanOperationStatus> getCapabilityRes) { Either<CapabilityDefinition, TitanOperationStatus> getCapabilityDefinitionRes; - log.trace("Before getting capability definition {} {} {}", capabilityId, forRI, resourceInstanceId); + log.trace("Before getting capability definition {} for resource instance {}", capabilityId, resourceInstanceId); TitanVertex overrideCapabilityData = getCapabilityRes.left().value().getLeft(); @@ -296,90 +279,90 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC getCapabilityDefinitionRes = capabilityOperation.getCapabilityByCapabilityData(overrideCapabilityData); if (getCapabilityDefinitionRes.isRight()) { errorWrapper.setInnerElement(getCapabilityDefinitionRes.right().value()); - log.debug("Failed to retrieve capability {} ofRI {} statusIs {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); + log.debug("Failed to retrieve capability {} of resource instance {}, status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); } - log.debug("After getting capability definition for {} forRI {} statusIs {}.", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); + log.debug("After getting capability definition for {} for resource instance {} status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); return getCapabilityDefinitionRes; } private Either<ImmutablePair<CapabilityData, GraphEdge>, TitanOperationStatus> getCapabilitiesOfResourceInstance(String resourceInstanceId, String capabilityId, String capabilityName, Wrapper<TitanOperationStatus> errorWrapper) { Either<ImmutablePair<CapabilityData, GraphEdge>, TitanOperationStatus> getCapabilityRes; - log.debug("Before getting capability {} forRI {}.", capabilityId, resourceInstanceId); + log.debug("Before getting capability {} for resource instance {}", capabilityId, resourceInstanceId); Map<String, Object> props = new HashMap<>(); props.put(GraphPropertiesDictionary.NAME.getProperty(), capabilityName); getCapabilityRes = titanGenericDao.getChildByEdgeCriteria(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId, GraphEdgeLabels.CALCULATED_CAPABILITY, NodeTypeEnum.Capability, CapabilityData.class, props); if (getCapabilityRes.isRight()) { errorWrapper.setInnerElement(getCapabilityRes.right().value()); - log.debug("Failed to get capability {} ofRI {} statusIs {}.", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); + log.debug("Failed to get capability {} of resource instance {}, status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); } - log.debug("After getting capability for {} forRI {} statusIs {}.", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); + log.debug("After getting capability for {} for resource instance {}. status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); return getCapabilityRes; } private Either<ImmutablePair<TitanVertex, Edge>, TitanOperationStatus> getCapabilitiesOfResourceInstance(TitanVertex instanceVertex, String resourceInstanceId, String capabilityId, String capabilityName, Wrapper<TitanOperationStatus> errorWrapper) { Either<ImmutablePair<TitanVertex, Edge>, TitanOperationStatus> getCapabilityRes; - log.trace("Before getting capability {} {} {}", capabilityId, forRI, resourceInstanceId); + log.trace("Before getting capability {} {} {}", capabilityId, " for resource instance ", resourceInstanceId); Map<String, Object> props = new HashMap<>(); props.put(GraphPropertiesDictionary.NAME.getProperty(), capabilityName); getCapabilityRes = titanGenericDao.getChildByEdgeCriteria(instanceVertex, GraphEdgeLabels.CALCULATED_CAPABILITY, props); if (getCapabilityRes.isRight()) { errorWrapper.setInnerElement(getCapabilityRes.right().value()); - log.debug("Failed to get capability {} {} {} {} {}", capabilityId, ofRI, resourceInstanceId, statusIs, errorWrapper.getInnerElement()); + log.debug("Failed to get capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); } - log.trace("After getting capability for {} {} {} {} {}", capabilityId, forRI, resourceInstanceId, statusIs, errorWrapper.getInnerElement()); + log.trace("After getting capability for {} for resource instance {}. status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); return getCapabilityRes; } private void validateCapabilityInstanceExistence(String resourceInstanceId, String capabilityId, Wrapper<TitanOperationStatus> errorWrapper) { - log.debug("Before validation of existence of capability instance of capability {} forRI {}.", capabilityId, resourceInstanceId); + log.debug("Before validation of existence of capability instance of capability {} for resource instance {}", capabilityId, resourceInstanceId); boolean capabilityInstOfCapabilityAlreadyExists; Either<Boolean, TitanOperationStatus> validateCapabilityInstExistenceRes = validateCapabilityInstExistence(resourceInstanceId, capabilityId); if (validateCapabilityInstExistenceRes.isRight()) { errorWrapper.setInnerElement(validateCapabilityInstExistenceRes.right().value()); - log.debug("Failed to validate uniqueness of capability instance of capability {} ofRI {} statusIs {}.", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); + log.debug("Failed to validate uniqueness of capability instance of capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); } else { capabilityInstOfCapabilityAlreadyExists = validateCapabilityInstExistenceRes.left().value(); if (capabilityInstOfCapabilityAlreadyExists) { errorWrapper.setInnerElement(TitanOperationStatus.ALREADY_EXIST); - log.debug("failedCreateCI {} ofRI {} statusIs {}.", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); + log.debug("Failed to create capability instance of capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); } } - log.debug("After validation of existence of capability instance of capability {} forRI {} statusIs {}.", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); + log.debug("After validation of existence of capability instance of capability {} for resource instance {}. status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); } private void validateCapabilityInstanceExistence(TitanVertex resourceInstanceVertex, String resourceInstanceId, String capabilityId, Wrapper<TitanOperationStatus> errorWrapper) { - log.trace("Before validation of existence of capability instance of capability {} {} {}", capabilityId, forRI, resourceInstanceId); + log.trace("Before validation of existence of capability instance of capability {} for resource instance {}", capabilityId, resourceInstanceId); boolean capabilityInstOfCapabilityAlreadyExists; Either<Boolean, TitanOperationStatus> validateCapabilityInstExistenceRes = validateCapabilityInstExistence(resourceInstanceId, capabilityId); if (validateCapabilityInstExistenceRes.isRight()) { errorWrapper.setInnerElement(validateCapabilityInstExistenceRes.right().value()); - log.debug("Failed to validate uniqueness of capability instance of capability {} ofRI {} statusIs {}.", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); + log.debug("Failed to validate uniqueness of capability instance of capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); } else { capabilityInstOfCapabilityAlreadyExists = validateCapabilityInstExistenceRes.left().value(); if (capabilityInstOfCapabilityAlreadyExists) { errorWrapper.setInnerElement(TitanOperationStatus.ALREADY_EXIST); - log.debug("failedCreateCI {} ofRI {} statusIs {}.", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); + log.debug("Failed to create capability instance of capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); } } - log.debug("After validation of existence of capability instance of capability {} forRI {} statusIs {}.", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); + log.debug("After validation of existence of capability instance of capability {} for resource instance {}. status is {}", capabilityId, resourceInstanceId, errorWrapper.getInnerElement()); } private Either<List<PropertyValueData>, TitanOperationStatus> addPropertyValuesToCapabilityInstance(CapabilityInstData createdCapabilityInstance, List<ComponentInstanceProperty> propertyValues, Map<String, PropertyDefinition> defaultProperties) { TitanOperationStatus error = null; List<PropertyValueData> createdPropertyValues = new ArrayList<>(); for (ComponentInstanceProperty property : propertyValues) { - log.debug("Before adding property value {} toCI {}.", property.getName(), createdCapabilityInstance.getUniqueId()); + log.debug("Before adding property value {} to capability instance {}", property.getName(), createdCapabilityInstance.getUniqueId()); PropertyValueData propertyData = buildPropertyValueData(property.getName(), property.getType(), property.getValue(), createdCapabilityInstance.getUniqueId()); Either<PropertyValueData, TitanOperationStatus> addPropertyValueRes = addPropertyValueToCapabilityInstance(createdCapabilityInstance, propertyData, defaultProperties.get(property.getName())); if (addPropertyValueRes.isRight()) { error = addPropertyValueRes.right().value(); - log.debug("Failed to add property to capability instance {} ofRI. StatusIs {}.", createdCapabilityInstance.getUniqueId(), error); + log.debug("Failed to add property to capability instance {} of resource instance, status is {}", createdCapabilityInstance.getUniqueId(), error); break; } else { createdPropertyValues.add(addPropertyValueRes.left().value()); } - log.debug("After adding property value {} toCI {} statusIs {}", property.getName(), createdCapabilityInstance.getUniqueId(), error); + log.debug("After adding property value {} to capability instance {}. status is {}", property.getName(), createdCapabilityInstance.getUniqueId(), error); } if (error == null) { return Either.left(createdPropertyValues); @@ -391,15 +374,15 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC TitanOperationStatus error = null; String id = (String) titanGenericDao.getProperty(createdCapabilityInstancevertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty()); for (ComponentInstanceProperty property : propertyValues) { - log.trace("Before adding property value {} {} {}", property.getName(), toCI, id); + log.trace("Before adding property value {} to capability instance {}", property.getName(), id); PropertyValueData propertyData = buildPropertyValueData(property.getName(), property.getType(), property.getValue(), id); TitanOperationStatus addPropertyValueRes = addPropertyValueToCapabilityInstance(createdCapabilityInstancevertex, propertyData, defaultProperties.get(property.getName()), id); if (!addPropertyValueRes.equals(TitanOperationStatus.OK)) { error = addPropertyValueRes; - log.debug("Failed to add property to capability instance {} {} {} {}", id, ofRI, statusIs, error); + log.debug("Failed to add property to capability instance {} of resource instance. status is {}", id, error); break; } - log.debug("After adding property value {} {} {} {} {}", property.getName(), toCI, id, statusIs, error); + log.debug("After adding property value {} to capability instance {}. status is {}", property.getName(), id, error); } if (error == null) { return TitanOperationStatus.OK; @@ -424,15 +407,15 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC Map<String, Object> props = null; Either<GraphRelation, TitanOperationStatus> createRelationRes; PropertyValueData createdValue = null; - log.debug("Before creating property value node {} onGraph.", propertyValue.getUniqueId()); + log.debug("Before creating property value node {} on graph", propertyValue.getUniqueId()); Either<PropertyValueData, TitanOperationStatus> createValueRes = titanGenericDao.createNode(propertyValue, PropertyValueData.class); if (createValueRes.isRight()) { error = createValueRes.right().value(); - log.debug("Failed to create property value for capability instance {} ofRI statusIs {}.", createdCapabilityInstance.getUniqueId(), error); + log.debug("Failed to create property value for capability instance {} of resource instance. status is {}", createdCapabilityInstance.getUniqueId(), error); } - log.debug("After creating property value node {} onGraph statusIs {}.", propertyValue.getUniqueId(), error); + log.debug("After creating property value node {} on graph. status is {}", propertyValue.getUniqueId(), error); if (error == null) { - log.debug("Before creating relation from property value node {} toCI {}.", propertyValue.getUniqueId(), createdCapabilityInstance.getUniqueId()); + log.debug("Before creating relation from property value node {} to capability instance {}", propertyValue.getUniqueId(), createdCapabilityInstance.getUniqueId()); createdValue = createValueRes.left().value(); props = new HashMap<>(); props.put(GraphPropertiesDictionary.PROPERTY_NAME.name(), propertyDefinition.getName()); @@ -440,18 +423,18 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC createRelationRes = titanGenericDao.createRelation(createdCapabilityInstance, createdValue, GraphEdgeLabels.PROPERTY_VALUE, props); if (createRelationRes.isRight()) { error = createRelationRes.right().value(); - log.debug("Failed to create relation from capability instance {} toValue {} statusIs {}.", createdCapabilityInstance.getUniqueId(), createdValue.getUniqueId(), error); + log.debug("Failed to create relation from capability instance {} to property value {}. status is {}", createdCapabilityInstance.getUniqueId(), createdValue.getUniqueId(), error); } - log.debug("After creating relation from property value node {} toCI {} statusIs {}.", propertyValue.getUniqueId(), createdCapabilityInstance.getUniqueId(), error); + log.debug("After creating relation from property value node {} to capability instance {}. status is {}", propertyValue.getUniqueId(), createdCapabilityInstance.getUniqueId(), error); } if (error == null) { - log.debug("Before creating relation from property value node {} toProperty {}.", propertyValue.getUniqueId(), propertyDefinition.getUniqueId()); + log.debug("Before creating relation from property value node {} to property {}", propertyValue.getUniqueId(), propertyDefinition.getUniqueId()); createRelationRes = titanGenericDao.createRelation(propertyValue, new PropertyData(propertyDefinition, null), GraphEdgeLabels.PROPERTY_IMPL, props); if (createRelationRes.isRight()) { error = createRelationRes.right().value(); - log.debug("Failed to create relation from property value {} toProperty {} statusIs {}.", createdValue.getUniqueId(), propertyDefinition.getUniqueId(), error); + log.debug("Failed to create relation from property value {} to property {}. status is {}", createdValue.getUniqueId(), propertyDefinition.getUniqueId(), error); } - log.debug("After creating relation from property value node {} toProperty statusIs {}.", propertyValue.getUniqueId(), propertyDefinition.getUniqueId(), error); + log.debug("After creating relation from property value node {} to property {}. status is {}", propertyValue.getUniqueId(), propertyDefinition.getUniqueId(), error); } if (error == null) { return Either.left(createdValue); @@ -467,15 +450,13 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC Either<TitanVertex, TitanOperationStatus> createValueRes = titanGenericDao.createNode(propertyValue); if (createValueRes.isRight()) { error = createValueRes.right().value(); - if (log.isDebugEnabled()){ - log.debug("Failed to create property value for capability instance {} {} {} {}", id, ofRI, statusIs, error); - } + log.debug("Failed to create property value for capability instance {} of resource instance. status is {}", id, error); } log.trace("After creating property value node {} on graph status is {}", propertyValue.getUniqueId(), error); TitanVertex createdPropVertex = null; String createdId = null; if (error == null) { - log.trace("Before creating relation from property value node {} {} {} ", propertyValue.getUniqueId(), toCI, id); + log.trace("Before creating relation from property value node {} to capability instance {} ", propertyValue.getUniqueId() , id); props = new HashMap<>(); props.put(GraphPropertiesDictionary.PROPERTY_NAME.name(), propertyDefinition.getName()); props.put(GraphPropertiesDictionary.PROPERTY_ID.name(), propertyDefinition.getUniqueId()); @@ -484,22 +465,18 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC if (!createRelationRes.equals(TitanOperationStatus.OK)) { error = createRelationRes; createdId = (String) titanGenericDao.getProperty(createdPropVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty()); - if (log.isDebugEnabled()) { - log.debug("Failed to create relation from capability instance {} {} {} {} {}", id, toValue, createdId, statusIs, error); - } - } - if (log.isTraceEnabled()){ - log.trace("After creating relation from property value node {} {} {} {} {}", propertyValue.getUniqueId(), toCI, id, statusIs, error); + log.debug("Failed to create relation from capability instance {} to property value {}. status is {}", id, createdId, error); } + log.trace("After creating relation from property value node {} to capability instance {}. status is {}", propertyValue.getUniqueId(), id, error); } if (error == null) { - log.trace("Before creating relation from property value node {} {} {}", propertyValue.getUniqueId(), toProperty, propertyDefinition.getUniqueId()); + log.trace("Before creating relation from property value node {} to property {}", propertyValue.getUniqueId(), propertyDefinition.getUniqueId()); createRelationRes = titanGenericDao.createEdge(createdPropVertex, new PropertyData(propertyDefinition, null), GraphEdgeLabels.PROPERTY_IMPL, props); if (!createRelationRes.equals(TitanOperationStatus.OK)) { error = createRelationRes; - log.debug("Failed to create relation from property value {} {} {} {} {}", createdId, toProperty, propertyDefinition.getUniqueId(), statusIs, error); + log.debug("Failed to create relation from property value {} to property {}. status is {}", createdId, propertyDefinition.getUniqueId(), error); } - log.debug("After creating relation from property value node {} {} {} {} {}", propertyValue.getUniqueId(), toProperty, propertyDefinition.getUniqueId(), statusIs, error); + log.debug("After creating relation from property value node {} to property {}. status is {}", propertyValue.getUniqueId(), propertyDefinition.getUniqueId(), error); } if (error == null) { return TitanOperationStatus.OK; @@ -537,7 +514,7 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = applicationDataTypeCache.getAll(); if (allDataTypes.isRight()) { TitanOperationStatus status = allDataTypes.right().value(); - log.debug("Failed to update property value statusIs {}.", status); + log.debug("Failed to update property value. status is {}", status); result = Either.right(status); } if (result == null) { @@ -582,7 +559,7 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC if (error.equals(TitanOperationStatus.NOT_FOUND)) { result = Either.left(false); } else { - log.debug("Failed to get outgoing edge for resource instance {} statusIs {}.", resourceInstanceId, error); + log.debug("Failed to get outgoing edge for resource instance {}. status is {}.", resourceInstanceId, error); result = Either.right(error); } } @@ -604,7 +581,7 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC if (error.equals(TitanOperationStatus.NOT_FOUND)) { result = Either.left(false); } else { - log.debug("Failed to get outgoing edge for resource instance {} {} {}", resourceInstanceId, statusIs, error); + log.debug("Failed to get outgoing edge for resource instance {} status is {}", resourceInstanceId, error); result = Either.right(error); } } @@ -615,7 +592,7 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC } private Either<CapabilityInstData, TitanOperationStatus> createCapabilityInstanceOnGraph(String resourceInstanceId, CapabilityData overrideCapabilityData, CapabilityInstData capabilityInstance) { - log.debug("Before creation of capability instance of capability {} forRI {}.", overrideCapabilityData.getUniqueId(), resourceInstanceId); + log.debug("Before creation of capability instance of capability {} for resource instance {}", overrideCapabilityData.getUniqueId(), resourceInstanceId); Either<GraphRelation, TitanOperationStatus> createRelationRes; CapabilityInstData createdCapabilityInstance = null; @@ -624,9 +601,9 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC Either<CapabilityInstData, TitanOperationStatus> createCapabilityInstanceRes = titanGenericDao.createNode(capabilityInstance, CapabilityInstData.class); if (createCapabilityInstanceRes.isRight()) { error = createCapabilityInstanceRes.right().value(); - log.debug("failedCreateCI {} forRI {} statusIs {}.", overrideCapabilityData.getUniqueId(), resourceInstanceId, error); + log.debug("Failed to create capability instance of capability {} for resource instance {}. status is {}.", overrideCapabilityData.getUniqueId(), resourceInstanceId, error); } - log.debug("After creation of capability instance of capability {} forRI {} statusIs {}.", overrideCapabilityData.getUniqueId(), resourceInstanceId, error); + log.debug("After creation of capability instance of capability {} for resource instance {}. status is {}.", overrideCapabilityData.getUniqueId(), resourceInstanceId, error); if (error == null) { createdCapabilityInstance = createCapabilityInstanceRes.left().value(); capabilityInstanceId = createdCapabilityInstance.getUniqueId(); @@ -637,20 +614,20 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC createRelationRes = titanGenericDao.createRelation(resourceInstanceIdData, capabilityInstance, GraphEdgeLabels.CAPABILITY_INST, props); if (createRelationRes.isRight()) { error = createRelationRes.right().value(); - log.debug("Failed to assotiate resource instance {} toCI {} statusIs {}.", resourceInstanceId, capabilityInstanceId, error); + log.debug("Failed to assotiate resource instance {} to capability instance {}. status is {}", resourceInstanceId, capabilityInstanceId, error); } - log.debug("After associating resource instance {} to CI {} statusIs {}.", resourceInstanceId, capabilityInstanceId, error); + log.debug("After associating resource instance {} to capability instance {}. status is {}", resourceInstanceId, capabilityInstanceId, error); } if (error == null) { - log.debug("Before associating capability instance {} toCapability {}.", capabilityInstanceId, overrideCapabilityData.getUniqueId()); + log.debug("Before associating capability instance {} to capability {}.", capabilityInstanceId, overrideCapabilityData.getUniqueId()); Map<String, Object> props = new HashMap<>(); props.put(GraphPropertiesDictionary.CAPABILITY_ID.getProperty(), overrideCapabilityData.getUniqueId()); createRelationRes = titanGenericDao.createRelation(createdCapabilityInstance, overrideCapabilityData, GraphEdgeLabels.INSTANCE_OF, props); if (createRelationRes.isRight()) { error = createRelationRes.right().value(); - log.debug("Failed to associate capability instance {} toCapability statusIs {}.", capabilityInstanceId, overrideCapabilityData.getUniqueId(), error); + log.debug("Failed to associate capability instance {} to capability {}. status is {}", capabilityInstanceId, overrideCapabilityData.getUniqueId(), error); } - log.debug("After associating capability instance {} toCapability statusIs {}.", capabilityInstanceId, overrideCapabilityData.getUniqueId(), error); + log.debug("After associating capability instance {} to capability {}. status is {}.", capabilityInstanceId, overrideCapabilityData.getUniqueId(), error); } if (error == null) { return createCapabilityInstanceRes; @@ -660,7 +637,7 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC private Either<TitanVertex, TitanOperationStatus> createCapabilityInstanceOnGraph(TitanVertex riVertex, String resourceInstanceId, TitanVertex overrideCapabilityDataVertex, CapabilityInstData capabilityInstance) { String overrideCapabilityDataId = (String) titanGenericDao.getProperty(overrideCapabilityDataVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty()); - log.trace("Before creation of capability instance of capability {} {} {}", overrideCapabilityDataVertex, forRI, resourceInstanceId); + log.trace("Before creation of capability instance of capability {} for resource instance {}", overrideCapabilityDataVertex, resourceInstanceId); TitanOperationStatus createRelationRes; TitanVertex createdCapabilityInstance = null; @@ -669,9 +646,9 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC Either<TitanVertex, TitanOperationStatus> createCapabilityInstanceRes = titanGenericDao.createNode(capabilityInstance); if (createCapabilityInstanceRes.isRight()) { error = createCapabilityInstanceRes.right().value(); - log.debug("Failed to create capability instance of capability {} {} {} {} {}", overrideCapabilityDataId, forRI, resourceInstanceId, statusIs, error); + log.debug("Failed to create capability instance of capability {} for resource instance {} status is {}", overrideCapabilityDataId, resourceInstanceId, error); } - log.trace("After creation of capability instance of capability {} {} {} {} {}", overrideCapabilityDataId, forRI, resourceInstanceId, statusIs, error); + log.trace("After creation of capability instance of capability {} for resource instance {} status is {}", overrideCapabilityDataId, resourceInstanceId, error); if (error == null) { createdCapabilityInstance = createCapabilityInstanceRes.left().value(); capabilityInstanceId = (String) titanGenericDao.getProperty(createdCapabilityInstance, GraphPropertiesDictionary.UNIQUE_ID.getProperty()); @@ -682,22 +659,22 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC createRelationRes = titanGenericDao.createEdge(riVertex, capabilityInstance, GraphEdgeLabels.CAPABILITY_INST, props); if (!createRelationRes.equals(TitanOperationStatus.OK)) { error = createRelationRes; - log.debug("Failed to assotiate resource instance {} {} {} {} {}", resourceInstanceId, toCI, capabilityInstanceId, statusIs, error); + log.debug("Failed to assotiate resource instance {} to capability instance {} status is {}", resourceInstanceId, capabilityInstanceId, error); } if (log.isTraceEnabled()) { - log.trace("After associating resource instance {} {} {} {} {}", resourceInstanceId, toCI, capabilityInstanceId, statusIs, error); + log.trace("After associating resource instance {} to capability instance {}. status is {}", resourceInstanceId, capabilityInstanceId, error); } } if (error == null) { - log.trace("Before associating capability instance {} {} {}", capabilityInstanceId, toCapability, overrideCapabilityDataId); + log.trace("Before associating capability instance {} to capability {}", capabilityInstanceId, overrideCapabilityDataId); Map<String, Object> props = new HashMap<>(); props.put(GraphPropertiesDictionary.CAPABILITY_ID.getProperty(), overrideCapabilityDataId); createRelationRes = titanGenericDao.createEdge(createdCapabilityInstance, overrideCapabilityDataVertex, GraphEdgeLabels.INSTANCE_OF, props); if (!createRelationRes.equals(TitanOperationStatus.OK)) { error = createRelationRes; - log.debug("Failed to associate capability instance {} {} {} {} {}", capabilityInstanceId, toCapability, overrideCapabilityDataId, statusIs, error); + log.debug("Failed to associate capability instance {} to capability {} status is {}", capabilityInstanceId, overrideCapabilityDataId, error); } - log.debug("After associating capability instance {} {} {} {} {}", capabilityInstanceId, toCapability, overrideCapabilityDataId, statusIs, error); + log.debug("After associating capability instance {} to capability {}. status is {}", capabilityInstanceId, overrideCapabilityDataId, error); } if (error == null) { return createCapabilityInstanceRes; @@ -726,23 +703,23 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC */ @Override public Either<CapabilityInstData, TitanOperationStatus> deleteCapabilityInstanceFromResourceInstance(String resourceInstanceId, String capabilityInstanceId) { - log.debug("Before deleting of capability instance {} fromRI {}.", capabilityInstanceId, resourceInstanceId); + log.debug("Before deleting of capability instance {} from resource instance {}.", capabilityInstanceId, resourceInstanceId); Either<CapabilityInstData, TitanOperationStatus> deleteCapabilityInstRes = null; TitanOperationStatus error = null; Either<Boolean, TitanOperationStatus> deleteProperyValuesRes = deleteAllPropertyValuesOfCapabilityInstance(resourceInstanceId, capabilityInstanceId); if (deleteProperyValuesRes.isRight()) { error = deleteProperyValuesRes.right().value(); - log.debug("failedDeletePropertyValues {} for RI {} statusIs {}.", capabilityInstanceId, resourceInstanceId, error); + log.debug("Failed to delete property values of capability instance {} for resource instance {}. status is {}", capabilityInstanceId, resourceInstanceId, error); } if (error == null) { deleteCapabilityInstRes = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityInst), capabilityInstanceId, CapabilityInstData.class); if (deleteCapabilityInstRes.isRight()) { error = deleteCapabilityInstRes.right().value(); - log.debug("Failed to delete capability instance {} forRI {} statusIs {}", capabilityInstanceId, resourceInstanceId, error); + log.debug("Failed to delete capability instance {} for resource instance {}. status is {}", capabilityInstanceId, resourceInstanceId, error); } } - log.debug("After deleting of capability instance {} fromRI {} statusIs {}.", capabilityInstanceId, resourceInstanceId, error); + log.debug("After deleting of capability instance {} from resource instance {}. status is {}", capabilityInstanceId, resourceInstanceId, error); if (error == null) { return Either.left(deleteCapabilityInstRes.left().value()); } @@ -750,14 +727,14 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC } private Either<Boolean, TitanOperationStatus> deleteAllPropertyValuesOfCapabilityInstance(String resourceInstanceId, String capabilityInstanceId) { - log.debug("Before deleting all property values of capability instance {} fromRI {}.", capabilityInstanceId, resourceInstanceId); + log.debug("Before deleting all property values of capability instance {} from resource instance {}", capabilityInstanceId, resourceInstanceId); TitanOperationStatus error = null; List<ImmutablePair<PropertyValueData, GraphEdge>> deletePropertiesPairs; Either<List<ImmutablePair<PropertyValueData, GraphEdge>>, TitanOperationStatus> getPropertyValuesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityInst), capabilityInstanceId, GraphEdgeLabels.PROPERTY_VALUE, NodeTypeEnum.PropertyValue, PropertyValueData.class); if (getPropertyValuesRes.isRight()) { error = getPropertyValuesRes.right().value(); - log.debug("Failed to retrieve property values of capability instance {} forRI {} status {}.", capabilityInstanceId, resourceInstanceId, error); + log.debug("Failed to retrieve property values of capability instance {} for resource instance {}. status is {}", capabilityInstanceId, resourceInstanceId, error); } if (error == null) { deletePropertiesPairs = getPropertyValuesRes.left().value(); @@ -765,12 +742,12 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC Either<PropertyValueData, TitanOperationStatus> deletePropertyRes = titanGenericDao.deleteNode(propertyPair.getLeft(), PropertyValueData.class); if (deletePropertyRes.isRight()) { error = deletePropertyRes.right().value(); - log.debug("failedDeletePropertyValues {} forRI {} statusIs {}.", capabilityInstanceId, resourceInstanceId, error); + log.debug("Failed to delete property values of capability instance {} for resource instance {}. status is {}", capabilityInstanceId, resourceInstanceId, error); break; } } } - log.debug("After deleting all property values of capability instance {} fromRI {} statusIs {}.", capabilityInstanceId, resourceInstanceId, error); + log.debug("After deleting all property values of capability instance from resource instance {}. status is {}", capabilityInstanceId, resourceInstanceId, error); if (error == null) { return Either.left(true); } @@ -786,15 +763,15 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC */ @Override public Either<List<ImmutablePair<CapabilityInstData, GraphEdge>>, TitanOperationStatus> getAllCapabilityInstancesOfResourceInstance(String resourceInstanceId) { - log.debug("Before deleting all capability instances of resource instance {}.", resourceInstanceId); + log.debug("Before deleting all capability instances of resource instance {}", resourceInstanceId); TitanOperationStatus error = null; Either<List<ImmutablePair<CapabilityInstData, GraphEdge>>, TitanOperationStatus> getCapabilityInstancesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId, GraphEdgeLabels.CAPABILITY_INST, NodeTypeEnum.CapabilityInst, CapabilityInstData.class); if (getCapabilityInstancesRes.isRight()) { error = getCapabilityInstancesRes.right().value(); - log.debug("Failed to retrieve capability Instances of resource instance {} statusIs {}.", resourceInstanceId, error); + log.debug("Failed to retrieve capability Instances of resource instance {}. status is {}", resourceInstanceId, error); } - log.debug("After deleting all capability instances of resource instance {} statusIs {}", resourceInstanceId, error); + log.debug("After deleting all capability instances of resource instance {}. status is {}", resourceInstanceId, error); if (error == null) { return getCapabilityInstancesRes; } @@ -817,7 +794,7 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC GraphEdgeLabels.CAPABILITY_INST, NodeTypeEnum.CapabilityInst, CapabilityInstData.class, props); if (getCapabilityInstanceRes.isRight()) { error = getCapabilityInstanceRes.right().value(); - log.debug("Failed to retrieve capability Instance of capability {} ofRI {} statusIs {}.", capabilityId, resourceInstanceId, error); + log.debug("Failed to retrieve capability Instance of capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, error); } if (error == null) { return Either.left(getCapabilityInstanceRes.left().value().getLeft()); @@ -835,7 +812,7 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC */ @Override public Either<List<PropertyValueData>, TitanOperationStatus> updateCapabilityPropertyValues(String resourceInstanceId, String capabilityId, List<ComponentInstanceProperty> propertyValues) { - log.debug("Before updating property values of capability {} ofRI {}.", capabilityId, resourceInstanceId); + log.debug("Before updating property values of capability {} of resource instance {}.", capabilityId, resourceInstanceId); TitanOperationStatus error = null; Map<String, Object> props = new HashMap<>(); CapabilityInstData capabilityInstance = null; @@ -849,47 +826,47 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC Either<List<PropertyValueData>, TitanOperationStatus> addPropertyValuesRes = null; Either<CapabilityDefinition, TitanOperationStatus> getCapabilityDefinitionRes = null; - log.debug("Before getting all capability instances of RI {}.", resourceInstanceId); + log.debug("Before getting all capability instances of resource instance {}.", resourceInstanceId); props.put(GraphPropertiesDictionary.CAPABILITY_ID.getProperty(), capabilityId); Either<ImmutablePair<CapabilityInstData, GraphEdge>, TitanOperationStatus> getCapabilityInstancesRes = titanGenericDao.getChildByEdgeCriteria(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId, GraphEdgeLabels.CAPABILITY_INST, NodeTypeEnum.CapabilityInst, CapabilityInstData.class, props); if (getCapabilityInstancesRes.isRight()) { error = getCapabilityInstancesRes.right().value(); - log.debug("Failed to retrieve capability Instances of capability {} ofRI {} statusIs {}.", capabilityId, resourceInstanceId, error); + log.debug("Failed to retrieve capability Instances of capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, error); } - log.debug("After getting all capability instances ofRI {} statusIs {}.", resourceInstanceId, error); + log.debug("After getting all capability instances of resource instance {}. status is {}.", resourceInstanceId, error); if (error == null) { - log.debug("Before deleting all capability instances ofRI {}.", resourceInstanceId); + log.debug("Before deleting all capability instances of resource instance {}.", resourceInstanceId); capabilityInstance = getCapabilityInstancesRes.left().value().getLeft(); capabilityInstanceId = capabilityInstance.getUniqueId(); deleteProperyValuesRes = deleteAllPropertyValuesOfCapabilityInstance(resourceInstanceId, capabilityInstanceId); if (deleteProperyValuesRes.isRight()) { error = deleteProperyValuesRes.right().value(); - log.debug("failedDeletePropertyValues {} forRI {} statusIs {}", capabilityInstanceId, resourceInstanceId, statusIs, error); + log.debug("Failed to delete property values of capability instance {} for resource instance {}. status is {}", capabilityInstanceId, resourceInstanceId, error); } - log.debug("After deleting all capability instances ofRI {} statusIs {}.", resourceInstanceId, error); + log.debug("After deleting all capability instances of resource instance {}. status is {}", resourceInstanceId, error); } if (error == null) { - log.debug("Before getting capability {} ofRI {}.", capabilityId, resourceInstanceId); + log.debug("Before getting capability {} of resource instance {}", capabilityId, resourceInstanceId); getCapabilityDataRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId, GraphEdgeLabels.CALCULATED_CAPABILITY, NodeTypeEnum.Capability, CapabilityData.class); if (getCapabilityDataRes.isRight()) { error = getCapabilityDataRes.right().value(); - log.debug("Failed to get capability {} ofRI {} statusIs {}.", capabilityId, resourceInstanceId, error); + log.debug("Failed to get capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, error); } - log.debug("After getting capability {} ofRI {} statusIs {}.", capabilityId, resourceInstanceId, error); + log.debug("After getting capability {} of resource instance {}. status is {}.", capabilityId, resourceInstanceId, error); } if (error == null) { - log.debug("Before getting capability definition for capability {} ofRI {}.", capabilityId, resourceInstanceId); + log.debug("Before getting capability definition for capability {} of resource instance {}.", capabilityId, resourceInstanceId); overrideCapabilityData = getCapabilityDataRes.left().value().getLeft(); getCapabilityDefinitionRes = capabilityOperation.getCapabilityByCapabilityData(overrideCapabilityData); if (getCapabilityDefinitionRes.isRight()) { error = getCapabilityDefinitionRes.right().value(); - log.debug("Failed to retrieve capability {} ofRI {} statusIs {}", capabilityId, resourceInstanceId, error); + log.debug("Failed to retrieve capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, error); } - log.debug("After getting capability definition for capability {} ofRI {} statusIs {}.", capabilityId, resourceInstanceId, error); + log.debug("After getting capability definition for capability {} of resource instance {}. status is {}.", capabilityId, resourceInstanceId, error); } if (error == null) { - log.debug("Before validating capability properties of capability instance {} ofRI {}.", capabilityInstanceId, resourceInstanceId); + log.debug("Before validating capability properties of capability instance {} of resource instance {}.", capabilityInstanceId, resourceInstanceId); overrideCapabilityDefinition = getCapabilityDefinitionRes.left().value(); if (overrideCapabilityDefinition.getProperties() != null) { defaultProperties = overrideCapabilityDefinition.getProperties().stream().collect(Collectors.toMap(PropertyDefinition::getName, Function.identity())); @@ -897,20 +874,20 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC Either<Boolean, TitanOperationStatus> result = validateCapabilityInstanceProperties(defaultProperties, propertyValues); if (result.isRight()) { error = result.right().value(); - log.debug("failedAddProperties {} ofRI {} statusIs {}.", capabilityInstance.getUniqueId(), resourceInstanceId, error); + log.debug("Failed to add properties to capability instance {} of resource instance {}. status is {}", capabilityInstance.getUniqueId(), resourceInstanceId, error); } - log.debug("After validating capability properties of capability instance {} of RI {} statusIs {}.", capabilityInstanceId, resourceInstanceId, error); + log.debug("After validating capability properties of capability instance {} of resource instance {}. status is {}.", capabilityInstanceId, resourceInstanceId, error); } if (error == null) { - log.debug("Before adding property values toCI {} ofRI {}.", capabilityInstanceId, resourceInstanceId); + log.debug("Before adding property values to capability instance {} of resource instance {}.", capabilityInstanceId, resourceInstanceId); addPropertyValuesRes = addPropertyValuesToCapabilityInstance(capabilityInstance, propertyValues, defaultProperties); if (addPropertyValuesRes.isRight()) { error = addPropertyValuesRes.right().value(); - log.debug("failedAddProperties {} ofRI {} statusIs {}.", capabilityInstance.getUniqueId(), resourceInstanceId, error); + log.debug("Failed to add properties to capability instance {} of resource instance {}. status is {}", capabilityInstance.getUniqueId(), resourceInstanceId, error); } - log.debug("Before adding property values toCI {} ofRI {}.", capabilityInstanceId, resourceInstanceId); + log.debug("Before adding property values to capability instance {} of resource instance {}.", capabilityInstanceId, resourceInstanceId); } - log.debug("After updating property values of capability {} ofRI {} statusIs {}.", capabilityId, resourceInstanceId, error); + log.debug("After updating property values of capability {} of resource instance {}. status is {}.", capabilityId, resourceInstanceId, error); if (error == null) { return addPropertyValuesRes; } @@ -933,33 +910,33 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC String componentInstanceId = createdComponentInstance.getUniqueId(); String capabilityInstanceId = capabilityInstPair.getLeft().getUniqueId(); - log.debug("Before cloning capability instance with property values of capability instance {} ofRI {}.", capabilityInstanceId, componentInstanceId); + log.debug("Before cloning capability instance with property values of capability instance {} of resource instance {}.", capabilityInstanceId, componentInstanceId); List<ImmutablePair<PropertyValueData, GraphEdge>> propertyValuePairs; List<PropertyValueData> newPropertyValues = new ArrayList<>(); CapabilityInstData cloneCapabilityInstance = null; Either<CapabilityInstData, TitanOperationStatus> cloneCapabilityInstanceNodeRes = null; - log.debug("Before getting all property values ofCI {} ofRI {}.", capabilityInstanceId, componentInstanceId); + log.debug("Before getting all property values of component instance {} of resource instance {}.", capabilityInstanceId, componentInstanceId); Either<List<ImmutablePair<PropertyValueData, GraphEdge>>, TitanOperationStatus> getPropertyValuesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityInst), capabilityInstPair.getLeft().getUniqueId(), GraphEdgeLabels.PROPERTY_VALUE, NodeTypeEnum.PropertyValue, PropertyValueData.class); if (getPropertyValuesRes.isRight()) { error = getPropertyValuesRes.right().value(); - log.debug("Failed to retrieve property values of capability instance {} ofCI {} statusIs {}.", capabilityInstPair.getLeft().getUniqueId(), componentInstanceId ,error); + log.debug("Failed to retrieve property values of capability instance {} of component instance {}. status is {}", capabilityInstPair.getLeft().getUniqueId(), componentInstanceId, error); } - log.debug("After getting all property values ofCI {} ofRI {} statusIs {}.", capabilityInstanceId, componentInstanceId, error); + log.debug("After getting all property values of component instance {} of resource instance {}. status is {}.", capabilityInstanceId, componentInstanceId, error); if (error == null) { CapabilityInstData cloneCapabilityInst = buildCapabilityInstanceData(componentInstanceId, capability); - log.debug("Before creating capability instance node {} onGraph.", cloneCapabilityInst.getUniqueId()); + log.debug("Before creating capability instance node {} on graph.", cloneCapabilityInst.getUniqueId()); cloneCapabilityInstanceNodeRes = titanGenericDao.createNode(cloneCapabilityInst, CapabilityInstData.class); if (cloneCapabilityInstanceNodeRes.isRight()) { error = cloneCapabilityInstanceNodeRes.right().value(); - log.debug("Failed to create capability instance of capability {} ofCI {} statusIs {}.", capability.getUniqueId(), componentInstanceId, error); + log.debug("Failed to create capability instance of capability {} of component instance {}. status is {}", capability.getUniqueId(), componentInstanceId, error); } - log.debug("After creating capability instance node {} onGraph. statusIs {}", cloneCapabilityInst.getUniqueId(), error); + log.debug("After creating capability instance node {} on graph. status is {}.", cloneCapabilityInst.getUniqueId(), error); } if (error == null) { - log.debug("Before creating relation from capability instance {} toCapability {} onGraph.", cloneCapabilityInstanceNodeRes.left().value().getUniqueId(), capability.getUniqueId()); + log.debug("Before creating relation from capability instance {} to capability {} on graph.", cloneCapabilityInstanceNodeRes.left().value().getUniqueId(), capability.getUniqueId()); cloneCapabilityInstance = cloneCapabilityInstanceNodeRes.left().value(); CapabilityData capabilityData = buildCapabilityData(capability); Map<String, Object> props = new HashMap<>(); @@ -967,29 +944,27 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC Either<GraphRelation, TitanOperationStatus> createRelationRes = titanGenericDao.createRelation(cloneCapabilityInstance, capabilityData, GraphEdgeLabels.INSTANCE_OF, props); if (createRelationRes.isRight()) { error = createRelationRes.right().value(); - log.debug("Failed to associate capability instance {} toCapability {} statusIs {}.", cloneCapabilityInstance.getUniqueId(), capability.getUniqueId(), error); + log.debug("Failed to associate capability instance {} to capability {}. status is {}", cloneCapabilityInstance.getUniqueId(), capability.getUniqueId(), error); } - log.debug("After creating relation from capability instance {} toCapability {} onGraph. statusIs {}.", cloneCapabilityInstanceNodeRes.left().value().getUniqueId(), capability.getUniqueId(), error); + log.debug("After creating relation from capability instance {} to capability {} on graph. status is.", cloneCapabilityInstanceNodeRes.left().value().getUniqueId(), capability.getUniqueId(), error); } if (error == null) { - log.debug("Before cloning property values ofCI {}.", capabilityInstanceId); + log.debug("Before cloning property values of component instance {}.", capabilityInstanceId); propertyValuePairs = getPropertyValuesRes.left().value(); for (ImmutablePair<PropertyValueData, GraphEdge> propertyValuePair : propertyValuePairs) { Either<PropertyValueData, TitanOperationStatus> clonePropertyValueRes = cloneAssociatePropertyValue(cloneCapabilityInstance, propertyValuePair); if (clonePropertyValueRes.isRight()) { error = clonePropertyValueRes.right().value(); - if (log.isDebugEnabled()) { - log.debug("Failed to clone property value {} ofCapability {} ofCI {}. statusIs {}.", propertyValuePair.getLeft().getUniqueId(), capability.getUniqueId(), componentInstanceId, error); - } + log.debug("Failed to clone property value {} of capability {} of component instance {}. status is {}", propertyValuePair.getLeft().getUniqueId(), capability.getUniqueId(), componentInstanceId, error); break; } else { newPropertyValues.add(clonePropertyValueRes.left().value()); } } - log.debug("After cloning property values of CI {} statusIs {}.", capabilityInstanceId, error); + log.debug("After cloning property values of component instance {}. status is {}.", capabilityInstanceId, error); } - log.debug("After cloning capability instance with property values of capability instance {} ofRI {} statusIs {}.", capabilityInstanceId, componentInstanceId, error); + log.debug("After cloning capability instance with property values of capability instance {} of resource instance {}. status is {}.", capabilityInstanceId, componentInstanceId, error); if (error == null) { return Either.left(new ImmutablePair<CapabilityInstData, List<PropertyValueData>>(cloneCapabilityInstance, newPropertyValues)); } @@ -1003,44 +978,40 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC String capabilityInstanceId = capabilityInstPair.getLeft().getUniqueId(); if (log.isTraceEnabled()) { - log.trace("Before cloning capability instance with property values of capability instance {} {} {}", capabilityInstanceId, ofRI, componentInstanceId); + log.trace("Before cloning capability instance with property values of capability instance {} of resource instance {}", capabilityInstanceId, componentInstanceId); } List<ImmutablePair<TitanVertex, Edge>> propertyValuePairs; Either<TitanVertex, TitanOperationStatus> cloneCapabilityInstanceNodeRes = null; if (log.isTraceEnabled()) { - log.trace("Before getting all property values {} {} {} {}", ofCI, capabilityInstanceId, ofRI, componentInstanceId); + log.trace("Before getting all property values of component instance {} of resource instance {}", capabilityInstanceId, componentInstanceId); } Either<List<ImmutablePair<TitanVertex, Edge>>, TitanOperationStatus> getPropertyValuesRes = titanGenericDao.getChildrenVertecies(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityInst), capabilityInstPair.getLeft().getUniqueId(), GraphEdgeLabels.PROPERTY_VALUE); if (getPropertyValuesRes.isRight()) { error = getPropertyValuesRes.right().value(); - if (log.isDebugEnabled()) { - log.debug("Failed to retrieve property values of capability instance {} {} {} {} {}", capabilityInstPair.getLeft().getUniqueId(), ofCI, componentInstanceId, statusIs, error); - } + log.debug("Failed to retrieve property values of capability instance {} of component instance {}. status is {}", capabilityInstPair.getLeft().getUniqueId(), componentInstanceId, error); } if (log.isTraceEnabled()) { - log.trace("After getting all property values {} {} {} {} {} {}", ofCI, capabilityInstanceId, ofRI, componentInstanceId, statusIs, error); + log.trace("After getting all property values of component instance {} of resource instance {}. status is {}", capabilityInstanceId, componentInstanceId, error); } if (error == null) { CapabilityInstData cloneCapabilityInst = buildCapabilityInstanceData(componentInstanceId, capability); - log.trace("Before creating capability instance node {} {} ", cloneCapabilityInst.getUniqueId(), onGraph); + log.trace("Before creating capability instance node {} on graph", cloneCapabilityInst.getUniqueId()); cloneCapabilityInstanceNodeRes = titanGenericDao.createNode(cloneCapabilityInst); if (cloneCapabilityInstanceNodeRes.isRight()) { error = cloneCapabilityInstanceNodeRes.right().value(); - if (log.isDebugEnabled()) { - log.debug("Failed to create capability instance of capability {} {} {} {} {}", capability.getUniqueId(), ofCI, componentInstanceId, statusIs, error); - } + log.debug("Failed to create capability instance of capability {} of component instance {}. status is {}", capability.getUniqueId(), componentInstanceId, error); } if (log.isTraceEnabled()) { - log.trace("After creating capability instance node {} {} {} {}", cloneCapabilityInst.getUniqueId(), onGraph, statusIs, error); + log.trace("After creating capability instance node {} on graph. status is {}", cloneCapabilityInst.getUniqueId(), error); } } CapabilityData capabilityData; TitanVertex cloneCapabilityInstance = null; if (error == null) { if (log.isTraceEnabled()) { - log.trace("Before creating relation from capability instance {} {} {} {}", capability.getUniqueId(), toCapability, capability.getUniqueId(), onGraph); + log.trace("Before creating relation from capability instance {} to capability {} on graph", capability.getUniqueId(), capability.getUniqueId()); } capabilityData = buildCapabilityData(capability); Map<String, Object> props = new HashMap<>(); @@ -1049,33 +1020,25 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC TitanOperationStatus createRelationRes = titanGenericDao.createEdge(cloneCapabilityInstance, capabilityData, GraphEdgeLabels.INSTANCE_OF, props); if (!createRelationRes.equals(TitanOperationStatus.OK)) { error = createRelationRes; - if (log.isDebugEnabled()) { - log.debug("Failed to associate capability instance {} {} {} {} {}", capabilityData.getUniqueId(), toCapability, capability.getUniqueId(), statusIs, createRelationRes); - } - } - if (log.isTraceEnabled()) { - log.trace("After creating relation from capability instance {} {} {} {} {} {}", capabilityData.getUniqueId(), toCapability, capability.getUniqueId(), onGraph, statusIs, error); + log.debug("Failed to associate capability instance {} to capability {}. status is {}", capabilityData.getUniqueId(), capability.getUniqueId(), createRelationRes); } + log.trace("After creating relation from capability instance {} to capability {} on graph. status is {}", capabilityData.getUniqueId(), capability.getUniqueId(), error); } if (error == null) { - log.trace("Before cloning property values {} {} ", ofCI, capabilityInstanceId); + log.trace("Before cloning property values of component instance {} ", capabilityInstanceId); propertyValuePairs = getPropertyValuesRes.left().value(); for (ImmutablePair<TitanVertex, Edge> propertyValuePair : propertyValuePairs) { TitanOperationStatus clonePropertyValueRes = cloneAssociatePropertyValue(cloneCapabilityInstance, propertyValuePair); if (!clonePropertyValueRes.equals(TitanOperationStatus.OK)) { error = clonePropertyValueRes; - if (log.isDebugEnabled()) { - log.debug("Failed to clone property value of capability {} {} {} {} {}", capability.getUniqueId(), ofCI, componentInstanceId, statusIs, error); - } + log.debug("Failed to clone property value of capability {} of component instance {}. status is {}", capability.getUniqueId(), componentInstanceId, error); break; } } - if (log.isDebugEnabled()) { - log.debug("After cloning property values {} {} {} {}", ofCI, capabilityInstanceId, statusIs, error); - } + log.debug("After cloning property values of component instance {}. status is {}", capabilityInstanceId, error); } - log.debug("After cloning capability instance with property values of capability instance {} ofRI {} statusIs {}.", capabilityInstanceId, componentInstanceId, error); + log.debug("After cloning capability instance with property values of capability instance {} of resource instance {}. status is {}.", capabilityInstanceId, componentInstanceId, error); if (error == null) { return Either.left(cloneCapabilityInstance); } @@ -1100,7 +1063,7 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC TitanOperationStatus error = null; String propertyValueID = propertyValuePair.getLeft().getUniqueId(); String capabilityInstanceId = cloneCapabilityInstance.getUniqueId(); - log.debug("Before cloning property values {} ofCI {}.", propertyValueID, capabilityInstanceId); + log.debug("Before cloning property values {} of component instance {}.", propertyValueID, capabilityInstanceId); Map<String, Object> props = propertyValuePair.getRight().getProperties(); PropertyData propertyData = new PropertyData(); @@ -1111,33 +1074,33 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC PropertyValueData createdValue = null; Either<GraphRelation, TitanOperationStatus> createRelationRes; - log.debug("Before creating property values node {} onGraph.", propertyValue.getUniqueId()); + log.debug("Before creating property values node {} on graph.", propertyValue.getUniqueId()); Either<PropertyValueData, TitanOperationStatus> createValueRes = titanGenericDao.createNode(propertyValue, PropertyValueData.class); if (createValueRes.isRight()) { error = createValueRes.right().value(); - log.debug("Failed to create property value for capability instance {} ofRI. statusIs {}.", cloneCapabilityInstance.getUniqueId(), error); + log.debug("Failed to create property value for capability instance {} of resource instance. status is {}.", cloneCapabilityInstance.getUniqueId(), error); } - log.debug("After creating property values node {} onGraph. statusIs {}.", propertyValue.getUniqueId(), error); + log.debug("After creating property values node {} on graph. status is {}.", propertyValue.getUniqueId(), error); if (error == null) { createdValue = createValueRes.left().value(); - log.debug("Before creating relation from capability instance {} toValue {}.", capabilityInstanceId, createdValue.getUniqueId()); + log.debug("Before creating relation from capability instance {} to property value {}.", capabilityInstanceId, createdValue.getUniqueId()); createRelationRes = titanGenericDao.createRelation(cloneCapabilityInstance, createdValue, GraphEdgeLabels.PROPERTY_VALUE, props); if (createRelationRes.isRight()) { error = createRelationRes.right().value(); - log.debug("Failed to create relation from capability instance {} toValue {} statusIs {}.", cloneCapabilityInstance.getUniqueId(), createdValue.getUniqueId(), error); + log.debug("Failed to create relation from capability instance {} to property value {}. status is {}.", cloneCapabilityInstance.getUniqueId(), createdValue.getUniqueId(), error); } - log.debug("After creating relation from capability instance {} toValue {} statusIs {}", capabilityInstanceId, createdValue.getUniqueId(), error); + log.debug("After creating relation from capability instance {} to property value {}. status is {}.", capabilityInstanceId, createdValue.getUniqueId(), error); } if (error == null) { - log.debug("Before creating relation from property value {} toProperty {}.", createdValue, propertyData.getUniqueId()); + log.debug("Before creating relation from property value {} to property {}.", createdValue, propertyData.getUniqueId()); createRelationRes = titanGenericDao.createRelation(createdValue, propertyData, GraphEdgeLabels.PROPERTY_IMPL, props); if (createRelationRes.isRight()) { error = createRelationRes.right().value(); - log.debug("Failed to create relation from property value {} toProperty {} statusIs {}.", createdValue.getUniqueId(), propertyId, error); + log.debug("Failed to create relation from property value {} to property {}. status is {}.", createdValue.getUniqueId(), propertyId, error); } - log.debug("Before creating relation from property value {} toProperty {} statusIs {}.", createdValue, propertyData.getUniqueId(), error); + log.debug("Before creating relation from property value {} to property {}. status is {}.", createdValue, propertyData.getUniqueId(), error); } - log.debug("After cloning property values {} ofCI {} statusIs {}.", propertyValueID, capabilityInstanceId, error); + log.debug("After cloning property values {} of component instance {}. status is {}.", propertyValueID, capabilityInstanceId, error); if (error == null) { return Either.left(createdValue); } @@ -1150,7 +1113,7 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC String propertyValueID = (String) titanGenericDao.getProperty(propertyVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty()); String capabilityInstanceId = (String) titanGenericDao.getProperty(capabilityInstanceVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty()); if (log.isTraceEnabled()) { - log.trace("Before cloning property values {} {} {}", propertyValueID, ofCI, capabilityInstanceId); + log.trace("Before cloning property values {} of component instance {}", propertyValueID, capabilityInstanceId); } Map<String, Object> props = titanGenericDao.getProperties(propertyValuePair.getRight()); @@ -1165,48 +1128,40 @@ public class CapabilityInstanceOperation extends AbstractOperation implements IC TitanVertex createdValue = null; TitanOperationStatus createRelationRes; - log.trace("Before creating property values node {} {} ", propertyValue.getUniqueId(), onGraph); + log.trace("Before creating property values node {} on graph.", propertyValue.getUniqueId()); Either<TitanVertex, TitanOperationStatus> createValueRes = titanGenericDao.createNode(propertyValue); String capabiltyInstId = (String) titanGenericDao.getProperty(capabilityInstanceVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty()); if (createValueRes.isRight()) { error = createValueRes.right().value(); - if (log.isDebugEnabled()) { - log.debug("Failed to create property value for capability instance {} {} {} {}", capabiltyInstId, ofRI, statusIs, error); - } + log.debug("Failed to create property value for capability instance {} of resource instance. status is {}", capabiltyInstId, error); } if (log.isTraceEnabled()) { - log.trace("After creating property values node {} {} {} {} ", propertyValue.getUniqueId(), onGraph, statusIs, error); + log.trace("After creating property values node {} on graph. status is {} ", propertyValue.getUniqueId(), error); } if (error == null) { createdValue = createValueRes.left().value(); - log.trace("Before creating relation from capability instance {} {} {}", capabilityInstanceId, toValue, propertyValue.getUniqueId()); + log.trace("Before creating relation from capability instance {} to property value {}", capabilityInstanceId, propertyValue.getUniqueId()); createRelationRes = titanGenericDao.createEdge(capabilityInstanceVertex, createdValue, GraphEdgeLabels.PROPERTY_VALUE, props); if (!createRelationRes.equals(TitanOperationStatus.OK)) { error = createRelationRes; - if (log.isDebugEnabled()) { - log.debug("Failed to create relation from capability instance {} {} {} {} {}", capabiltyInstId, toValue, propertyValue.getUniqueId(), statusIs, error); - } + log.debug("Failed to create relation from capability instance {} to property value {}. status is {}", capabiltyInstId, propertyValue.getUniqueId(), error); } if (log.isTraceEnabled()) { - log.trace("After creating relation from capability instance {} {} {} {} {} ", capabilityInstanceId, toValue, propertyValue.getUniqueId(), statusIs, error); + log.trace("After creating relation from capability instance {} to property value {}. status is {} ", capabilityInstanceId, propertyValue.getUniqueId(), error); } } if (error == null) { - log.trace("Before creating relation from property value {} {} {} ", createdValue, toProperty, propertyData.getUniqueId()); + log.trace("Before creating relation from property value {} to property {} ", createdValue, propertyData.getUniqueId()); createRelationRes = titanGenericDao.createEdge(createdValue, propertyData, GraphEdgeLabels.PROPERTY_IMPL, props); if (!createRelationRes.equals(TitanOperationStatus.OK)) { error = createRelationRes; - if (log.isDebugEnabled()) { - log.debug("Failed to create relation from property value {} {} {} {} {}", propertyValue.getUniqueId(), toProperty, propertyId, statusIs, error); - } + log.debug("Failed to create relation from property value {} to property {}. status is {}", propertyValue.getUniqueId(), propertyId, error); } if (log.isTraceEnabled()) { - log.trace("Before creating relation from property value c", createdValue, toProperty, propertyData.getUniqueId(), statusIs, error); + log.trace("Before creating relation from property value {} to property {}. status is {}", createdValue, propertyData.getUniqueId(), error); } } - if (log.isTraceEnabled()) { - log.trace("After cloning property values {} {} {} {} {}", propertyValueID, ofCI, capabilityInstanceId, statusIs, error); - } + log.trace("After cloning property values {} of component instance {}. status is {}", propertyValueID, capabilityInstanceId, error); if (error == null) { return TitanOperationStatus.OK; } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityOperation.java index 9f00674780..ad43c60b0f 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityOperation.java @@ -99,7 +99,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit Either<CapabilityData, TitanOperationStatus> addCapStatus = addCapabilityToResource(resourceId, capabilityName, capabilityDefinition); if (addCapStatus.isRight()) { - log.debug("Failed to add capability {} [ {} ] to graph", capabilityName, capabilityDefinition); + log.debug("Failed to add capability {} [{}] to Graph", capabilityName, capabilityDefinition); BeEcompErrorManager.getInstance().logBeFailedCreateNodeError("Add Capability", capabilityName, String.valueOf(addCapStatus.right().value())); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(addCapStatus.right().value())); return result; @@ -108,11 +108,11 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit String capabilityUid = capabilityData.getUniqueId(); Either<CapabilityDefinition, StorageOperationStatus> capabilityRes = getCapability(capabilityUid, true); - log.debug("After fetching capability {} with uid {}. Status is {}", capabilityName, capabilityUid, capabilityRes); + log.debug("After fetching capability {} with uid {}. status is {}" ,capabilityName, capabilityUid,capabilityRes); if (capabilityRes.isRight()) { StorageOperationStatus status = capabilityRes.right().value(); - log.debug("Failed to fetch capability {] with uid {}. Status is {}", capabilityName, capabilityUid, status); + log.debug("Failed to fetch capability {} with uid {}. status is {}", capabilityName, capabilityUid, status); result = Either.right(status); return result; } @@ -147,7 +147,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit TitanOperationStatus addCapStatus = addCapabilityToResource(metadataVertex, resourceId, capabilityName, capabilityDefinition); if (!addCapStatus.equals(TitanOperationStatus.OK)) { - log.debug("Failed to add capability {} [ {} ]", capabilityName, capabilityDefinition); + log.debug("Failed to add capability {} [{}] to Graph", capabilityName, capabilityDefinition); BeEcompErrorManager.getInstance().logBeFailedCreateNodeError("Add Capability", capabilityName, String.valueOf(addCapStatus)); result = DaoStatusConverter.convertTitanStatusToStorageStatus(addCapStatus); } @@ -171,8 +171,6 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit CapabilityDefinition capabilityDefinition = new CapabilityDefinition(); capabilityDefinition.setType(capabilityData.getType()); - // TODO esofer do something - return capabilityDefinition; } @@ -326,7 +324,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit Either<CapabilityData, TitanOperationStatus> capabiltyRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability), uniqueId, CapabilityData.class); if (capabiltyRes.isRight()) { TitanOperationStatus status = capabiltyRes.right().value(); - log.debug("Failed to retrieve capability {} from graph. Status is {}", uniqueId, status); + log.debug("Failed to retrieve capability {} from graph. status is {}", uniqueId, status); BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("Fetch Capability", uniqueId, String.valueOf(status)); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); @@ -343,7 +341,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit Either<CapabilityTypeData, TitanOperationStatus> capabilityTypeRes = getCapabilityTypeOfCapability(uniqueId); if (capabilityTypeRes.isRight()) { TitanOperationStatus status = capabilityTypeRes.right().value(); - log.debug("Failed to retrieve capability type of capability {}. Status is {}", uniqueId, status); + log.debug("Failed to retrieve capability type of capability {}. status is {}", uniqueId, status); BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("Fetch Capability", uniqueId, String.valueOf(status)); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); @@ -361,7 +359,6 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit ImmutablePair<ResourceMetadataData, GraphEdge> pair = parentNode.left().value(); capabilityDefinition.setOwnerId(pair.left.getMetadataDataDefinition().getUniqueId()); List<String> derivedFromList = new ArrayList<>(); - // derivedFromList.add(pair.left.getMetadataDataDefinition().getName()); TitanOperationStatus fillResourceDerivedListFromGraph = fillResourceDerivedListFromGraph(pair.left.getMetadataDataDefinition().getUniqueId(), derivedFromList); if (fillResourceDerivedListFromGraph.equals(TitanOperationStatus.OK)) { capabilityDefinition.setCapabilitySources(derivedFromList); @@ -371,7 +368,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit Either<List<PropertyDefinition>, TitanOperationStatus> getPropertiesRes = getPropertiesOfCapability(uniqueId, capabilityTypeData.getCapabilityTypeDataDefinition().getType()); if (getPropertiesRes.isRight() && !getPropertiesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { TitanOperationStatus status = getPropertiesRes.right().value(); - log.debug("Failed to retrieve properties of capability {}. Status is {}", uniqueId, status); + log.debug("Failed to retrieve properties of capability {}. status is {}", uniqueId, status); BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("Fetch Properties of Capability", uniqueId, String.valueOf(status)); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); @@ -522,7 +519,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit } public Either<List<PropertyDefinition>, TitanOperationStatus> getPropertiesOfCapability(String capabilityUid, String capabilityType) { - log.debug("Before getting properties of capability {} from graph ", capabilityUid); + log.debug("Before getting properties of capability {} from graph " , capabilityUid); List<PropertyDefinition> properties; Either<List<PropertyDefinition>, TitanOperationStatus> result = null; @@ -539,7 +536,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit getPropertiesOfCapabilityTypeRes = getAllCapabilityTypePropertiesFromAllDerivedFrom(capabilityTypeUid); if (getPropertiesOfCapabilityTypeRes.isRight() && !getPropertiesOfCapabilityTypeRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { TitanOperationStatus status = getPropertiesOfCapabilityTypeRes.right().value(); - log.error("Failed to retrieve properties for capability type {} from graph. Status is {}", capabilityType, status); + log.error("Failed to retrieve properties for capability type {} from graph. status is {}", capabilityType, status); result = Either.right(status); } } @@ -560,14 +557,15 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit return result; } - protected Either<CapabilityTypeData, TitanOperationStatus> getCapabilityTypeOfCapability(String uniqueId) { + @Override + public Either<CapabilityTypeData, TitanOperationStatus> getCapabilityTypeOfCapability(String uniqueId) { Either<ImmutablePair<CapabilityTypeData, GraphEdge>, TitanOperationStatus> capabilityTypeRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability), uniqueId, GraphEdgeLabels.TYPE_OF, NodeTypeEnum.CapabilityType, CapabilityTypeData.class); if (capabilityTypeRes.isRight()) { TitanOperationStatus status = capabilityTypeRes.right().value();// - log.debug("Cannot find capability type associated with capability {}. Status is {}", uniqueId, status); + log.debug("Cannot find capability type associated with capability {}. status is {}", uniqueId, status); BeEcompErrorManager.getInstance().logBeFailedFindAssociationError("Fetch Capability type", NodeTypeEnum.CapabilityType.getName(), uniqueId, String.valueOf(status)); return Either.right(capabilityTypeRes.right().value()); } @@ -594,7 +592,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> capabilitiesNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.CAPABILITY, NodeTypeEnum.Capability, CapabilityData.class); - log.debug("After looking for all capabilities under resource {}. Status is {}", resourceId, capabilitiesNodes); + log.debug("After looking for all capabilities under resource {}. status is {}" , resourceId , capabilitiesNodes); if (capabilitiesNodes.isRight()) { TitanOperationStatus status = capabilitiesNodes.right().value(); return Either.right(status); @@ -610,7 +608,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit private Either<CapabilityData, TitanOperationStatus> addCapabilityToResource(String resourceId, String capabilityName, CapabilityDefinition capabilityDefinition) { - log.debug("Going to add capability {} [ {} ] to resource uid {}", capabilityName, capabilityDefinition, resourceId); + log.debug("Going to add capability {} [ {} ] to resource uid {}" , capabilityName, capabilityDefinition, resourceId); Either<CapabilityData, TitanOperationStatus> createCapRes = createCapability(resourceId, capabilityName, capabilityDefinition); @@ -647,7 +645,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit Either<GraphRelation, TitanOperationStatus> associateResourceRes = associateResourceToCapability(resourceId, capabilityName, capabilityData); if (associateResourceRes.isRight()) { TitanOperationStatus status = associateResourceRes.right().value(); - log.error("Failed to associate resource " + resourceId + " to capability " + capabilityData + ". status is " + status); + log.error("Failed to associate resource {} to capability {}. status is {}", resourceId, capabilityData, status); return Either.right(status); } @@ -702,10 +700,10 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit UniqueIdData capabilityTypeIdData = new UniqueIdData(NodeTypeEnum.CapabilityType, UniqueIdBuilder.buildCapabilityTypeUid(capabilityType)); log.debug("Before associating {} to capability type {}.", capabilityData, capabilityType); Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(capabilityData, capabilityTypeIdData, GraphEdgeLabels.TYPE_OF, null); - log.debug("After associating {} to capability type {}. status is {}", capabilityData, capabilityType, createRelResult); + log.debug("After associating {} to capability type {}. status is {}" , capabilityData, capabilityType, createRelResult); if (createRelResult.isRight()) { TitanOperationStatus operationStatus = createRelResult.right().value(); - log.error("Failed to associate capability {} to capability type {} in graph. Status is {}",capabilityData, capabilityTypeIdData, operationStatus); + log.error("Failed to associate capability {} to capability type {} in graph. status is {}", capabilityData, capabilityTypeIdData, operationStatus); return Either.right(operationStatus); } return Either.left(createRelResult.left().value()); @@ -733,10 +731,10 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit Map<String, Object> props = new HashMap<>(); props.put(GraphPropertiesDictionary.NAME.getProperty(), capabilityName); Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(resourceIdData, capabilityData, GraphEdgeLabels.CAPABILITY, props); - log.debug("After associating resource {} to capability {}. Status is {}", resourceId, capabilityData, createRelResult); + log.debug("After associating resource {} to capability {}. status is {}" , resourceId, capabilityData, createRelResult); if (createRelResult.isRight()) { TitanOperationStatus operationStatus = createRelResult.right().value(); - log.error("Failed to associate resource {} to capability {} in graph. Status is {}", resourceId, capabilityData, operationStatus); + log.error("Failed to associate resource {} to capability {} in graph. status is {}", resourceId, capabilityData, operationStatus); return Either.right(operationStatus); } @@ -825,7 +823,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit resultStatus = deletePropertiesStatus.right().value(); } if (resultStatus == null) { - log.debug("Before deleting capability from graph {}", capabilityUid); + log.debug("Before deleting capability from graph {}" , capabilityUid); Either<CapabilityData, TitanOperationStatus> deleteNodeStatus = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability), capabilityUid, CapabilityData.class); if (deleteNodeStatus.isRight()) { resultStatus = deleteNodeStatus.right().value(); @@ -848,7 +846,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit if (deleteAllRes.isRight()) { TitanOperationStatus status = deleteAllRes.right().value(); if (status != TitanOperationStatus.NOT_FOUND) { - log.debug("Failed to delete capabilities of resource {}. Status is {}", resourceId, status); + log.debug("Failed to delete capabilities of resource {}. status is {}", resourceId, status); } result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); return result; @@ -895,7 +893,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit CapabilityDefinition capabilityDefinition = entry.getValue(); String capabilityUid = capabilityDefinition.getUniqueId(); - log.debug("Before deleting properties of capability {} from graph", capabilityUid); + log.debug("Before deleting properties of capability {} from graph " , capabilityUid); Either<List<ImmutablePair<PropertyData, GraphEdge>>, TitanOperationStatus> deletePropertiesStatus = deletePropertiesOfCapability(capabilityUid); if (deletePropertiesStatus.isRight() && !deletePropertiesStatus.right().value().equals(TitanOperationStatus.NOT_FOUND)) { @@ -964,7 +962,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit Either<Map<String, PropertyDefinition>, TitanOperationStatus> allPropertiesOfCapabilityTypeRes = getAllCapabilityTypePropertiesFromAllDerivedFrom(capabilityTypeUid); if (allPropertiesOfCapabilityTypeRes.isRight() && !allPropertiesOfCapabilityTypeRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { TitanOperationStatus operationStatus = allPropertiesOfCapabilityTypeRes.right().value(); - log.error("Failed to retrieve properties for capability type " + capabilityType + " from graph. status is " + operationStatus); + log.error("Failed to retrieve properties for capability type {} from graph. status is {}", capabilityType, operationStatus); return Either.right(operationStatus); } @@ -976,7 +974,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit Either<List<PropertyDefinition>, TitanOperationStatus> validateAndReducePropertiesRes = validatePropertyUniqueness(propertiesOfCapabilityType, properties); if (validateAndReducePropertiesRes.isRight()) { TitanOperationStatus operationStatus = validateAndReducePropertiesRes.right().value(); - log.error("Failed to add properties to capability {} in graph. Status is {}", capabilityData.getUniqueId(), operationStatus); + log.error("Failed to add properties to capability {} in graph. status is {}", capabilityData.getUniqueId(), operationStatus); return Either.right(operationStatus); } } @@ -984,7 +982,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit Either<Map<String, PropertyData>, TitanOperationStatus> addPropertiesToCapabilityRes = propertyOperation.addPropertiesToElementType(capabilityData.getUniqueId(), NodeTypeEnum.Capability, properties); if (addPropertiesToCapabilityRes.isRight()) { TitanOperationStatus operationStatus = addPropertiesToCapabilityRes.right().value(); - log.error("Failed to add properties to capability {} in graph. Status is {}", capabilityData.getUniqueId(), operationStatus); + log.error("Failed to add properties to capability {} in graph. status is {}", capabilityData.getUniqueId(), operationStatus); return Either.right(operationStatus); } return Either.left(addPropertiesToCapabilityRes.left().value()); @@ -1066,7 +1064,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit } public Either<List<ImmutablePair<PropertyData, GraphEdge>>, TitanOperationStatus> deletePropertiesOfCapability(String capabilityUid) { - log.debug("Before deleting properties of capability {} from graph ", capabilityUid); + log.debug("Before deleting properties of capability {} from graph " , capabilityUid); Either<List<ImmutablePair<PropertyData, GraphEdge>>, TitanOperationStatus> deletePropertiesStatus = titanGenericDao.deleteChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability), capabilityUid, GraphEdgeLabels.PROPERTY, NodeTypeEnum.Property, PropertyData.class); @@ -1118,7 +1116,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit } } if (result.isRight()) { - log.debug("Failed to update properties of capability {}. Status is {}", uniqueId, result); + log.debug("Failed to update properties of capability {}. status is {}", uniqueId, result); } return result; } finally { @@ -1141,13 +1139,13 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit GraphEdgeLabels.CALCULATED_CAPABILITY, NodeTypeEnum.Capability, CapabilityData.class); if (getCapabilitiesRes.isRight()) { error = getCapabilitiesRes.right().value(); - log.debug("Failed to retrieve capabilities for resource instance {}. Status is {}", resourceInstanceId, error); + log.debug("Failed to retrieve capabilities for resource instance {}. status is {}", resourceInstanceId, error); } else { List<ImmutablePair<CapabilityData, GraphEdge>> capabilityPairsList = getCapabilitiesRes.left().value(); List<CapabilityData> capabilityPair = capabilityPairsList.stream().filter(pair -> pair.getLeft().getUniqueId().equals(capabilityUid)).map(pair -> pair.getLeft()).collect(Collectors.toList()); if (capabilityPair.isEmpty()) { error = TitanOperationStatus.NOT_FOUND; - log.debug("Failed to retrieve capability {} for resource instance {}. Status is {}", capabilityUid, resourceInstanceId, error); + log.debug("Failed to retrieve capability {} for resource instance {}. status is {}", capabilityUid, resourceInstanceId, error); } else { capability = capabilityPair.get(0); } @@ -1181,7 +1179,7 @@ public class CapabilityOperation extends AbstractOperation implements ICapabilit Either<Map<String, PropertyDefinition>, TitanOperationStatus> allPropertiesOfCapabilityTypeRes = propertyOperation.findPropertiesOfNode(NodeTypeEnum.CapabilityType, nextParentType); if (allPropertiesOfCapabilityTypeRes.isRight() && !allPropertiesOfCapabilityTypeRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { error = allPropertiesOfCapabilityTypeRes.right().value(); - log.error("Failed to retrieve properties for capability type {} from graph. Status is {}", nextParentType, error); + log.error("Failed to retrieve properties for capability type {} from graph. status is {}", nextParentType, error); return Either.right(error); } else if (allPropertiesOfCapabilityTypeRes.isLeft()) { if (allProperies.isEmpty()) { diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperation.java index 985399cb65..ddd6017620 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperation.java @@ -72,29 +72,22 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab } @Override - public Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType( - CapabilityTypeDefinition capabilityTypeDefinition, boolean inTransaction) { + public Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType(CapabilityTypeDefinition capabilityTypeDefinition, boolean inTransaction) { Either<CapabilityTypeDefinition, StorageOperationStatus> result = null; try { - Either<CapabilityTypeDefinition, TitanOperationStatus> validationRes = validateUpdateProperties( - capabilityTypeDefinition); + Either<CapabilityTypeDefinition, TitanOperationStatus> validationRes = validateUpdateProperties(capabilityTypeDefinition); if (validationRes.isRight()) { - log.error("One or all properties of capability type {} not valid. status is {}", - capabilityTypeDefinition, validationRes.right().value().name()); - result = Either - .right(DaoStatusConverter.convertTitanStatusToStorageStatus(validationRes.right().value())); + log.error("One or all properties of capability type {} not valid. status is {}", capabilityTypeDefinition, validationRes.right().value().name()); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(validationRes.right().value())); return result; } - Either<CapabilityTypeData, TitanOperationStatus> eitherStatus = addCapabilityTypeToGraph( - capabilityTypeDefinition); + Either<CapabilityTypeData, TitanOperationStatus> eitherStatus = addCapabilityTypeToGraph(capabilityTypeDefinition); if (eitherStatus.isRight()) { - log.error("Failed to add capability {} to Graph. status is {}", capabilityTypeDefinition, - eitherStatus.right().value().name()); - result = Either - .right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherStatus.right().value())); + log.error("Failed to add capability {} to Graph. status is {}", capabilityTypeDefinition, eitherStatus.right().value().name()); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherStatus.right().value())); return result; } else { CapabilityTypeData capabilityTypeData = eitherStatus.left().value(); @@ -120,28 +113,21 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab } - private Either<CapabilityTypeDefinition, TitanOperationStatus> validateUpdateProperties( - CapabilityTypeDefinition capabilityTypeDefinition) { + private Either<CapabilityTypeDefinition, TitanOperationStatus> validateUpdateProperties(CapabilityTypeDefinition capabilityTypeDefinition) { TitanOperationStatus error = null; - if (capabilityTypeDefinition.getProperties() != null && !capabilityTypeDefinition.getProperties().isEmpty() - && capabilityTypeDefinition.getDerivedFrom() != null) { - Either<Map<String, PropertyDefinition>, TitanOperationStatus> allPropertiesRes = capabilityOperation - .getAllCapabilityTypePropertiesFromAllDerivedFrom(capabilityTypeDefinition.getDerivedFrom()); - if (allPropertiesRes.isRight() - && !allPropertiesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { + if (capabilityTypeDefinition.getProperties() != null && !capabilityTypeDefinition.getProperties().isEmpty() && capabilityTypeDefinition.getDerivedFrom() != null) { + Either<Map<String, PropertyDefinition>, TitanOperationStatus> allPropertiesRes = capabilityOperation.getAllCapabilityTypePropertiesFromAllDerivedFrom(capabilityTypeDefinition.getDerivedFrom()); + if (allPropertiesRes.isRight() && !allPropertiesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { error = allPropertiesRes.right().value(); - log.debug("Couldn't fetch derived from property nodes for capability type {}, error: {}", - capabilityTypeDefinition.getType(), error); + log.debug("Couldn't fetch derived from property nodes for capability type {}, error: {}", capabilityTypeDefinition.getType(), error); } if (error == null && !allPropertiesRes.left().value().isEmpty()) { Map<String, PropertyDefinition> derivedFromProperties = allPropertiesRes.left().value(); - capabilityTypeDefinition.getProperties().entrySet().stream() - .filter(e -> derivedFromProperties.containsKey(e.getKey()) && e.getValue().getType() == null) + capabilityTypeDefinition.getProperties().entrySet().stream().filter(e -> derivedFromProperties.containsKey(e.getKey()) && e.getValue().getType() == null) .forEach(e -> e.getValue().setType(derivedFromProperties.get(e.getKey()).getType())); - Either<List<PropertyDefinition>, TitanOperationStatus> validatePropertiesRes = capabilityOperation - .validatePropertyUniqueness(allPropertiesRes.left().value(), capabilityTypeDefinition - .getProperties().values().stream().collect(Collectors.toList())); + Either<List<PropertyDefinition>, TitanOperationStatus> validatePropertiesRes = capabilityOperation.validatePropertyUniqueness(allPropertiesRes.left().value(), + capabilityTypeDefinition.getProperties().values().stream().collect(Collectors.toList())); if (validatePropertiesRes.isRight()) { error = validatePropertiesRes.right().value(); } @@ -163,8 +149,7 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab protected CapabilityTypeDefinition convertCTDataToCTDefinition(CapabilityTypeData capabilityTypeData) { log.debug("The object returned after create capability is {}", capabilityTypeData); - CapabilityTypeDefinition capabilityTypeDefResult = new CapabilityTypeDefinition( - capabilityTypeData.getCapabilityTypeDataDefinition()); + CapabilityTypeDefinition capabilityTypeDefResult = new CapabilityTypeDefinition(capabilityTypeData.getCapabilityTypeDataDefinition()); return capabilityTypeDefResult; } @@ -177,14 +162,12 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab * * 2. Add edge between the former node to its parent(if exists) * - * 3. Add property node and associate it to the node created at #1. (per - * property & if exists) + * 3. Add property node and associate it to the node created at #1. (per property & if exists) * * @param capabilityTypeDefinition * @return */ - private Either<CapabilityTypeData, TitanOperationStatus> addCapabilityTypeToGraph( - CapabilityTypeDefinition capabilityTypeDefinition) { + private Either<CapabilityTypeData, TitanOperationStatus> addCapabilityTypeToGraph(CapabilityTypeDefinition capabilityTypeDefinition) { log.debug("Got capability type {}", capabilityTypeDefinition); @@ -194,37 +177,31 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab CapabilityTypeData capabilityTypeData = buildCapabilityTypeData(capabilityTypeDefinition, ctUniqueId); log.debug("Before adding capability type to graph. capabilityTypeData = {}", capabilityTypeData); - Either<CapabilityTypeData, TitanOperationStatus> createCTResult = titanGenericDao.createNode(capabilityTypeData, - CapabilityTypeData.class); + Either<CapabilityTypeData, TitanOperationStatus> createCTResult = titanGenericDao.createNode(capabilityTypeData, CapabilityTypeData.class); log.debug("After adding capability type to graph. status is = {}", createCTResult); if (createCTResult.isRight()) { TitanOperationStatus operationStatus = createCTResult.right().value(); - log.error("Failed to capability type " + capabilityTypeDefinition.getType() + " to graph. status is " - + operationStatus); + log.error("Failed to capability type {} to graph. status is {}", capabilityTypeDefinition.getType(), operationStatus); return Either.right(operationStatus); } CapabilityTypeData resultCTD = createCTResult.left().value(); Map<String, PropertyDefinition> propertiesMap = capabilityTypeDefinition.getProperties(); Collection<PropertyDefinition> properties = propertiesMap != null ? propertiesMap.values() : null; - Either<Map<String, PropertyData>, TitanOperationStatus> addPropertiesToCapablityType = propertyOperation - .addPropertiesToElementType(resultCTD.getUniqueId(), NodeTypeEnum.CapabilityType, propertiesMap); + Either<Map<String, PropertyData>, TitanOperationStatus> addPropertiesToCapablityType = propertyOperation.addPropertiesToElementType(resultCTD.getUniqueId(), NodeTypeEnum.CapabilityType, propertiesMap); if (addPropertiesToCapablityType.isRight()) { - log.error( - "Failed add properties " + propertiesMap + " to capability " + capabilityTypeDefinition.getType()); + log.error("Failed add properties {} to capability {}", propertiesMap, capabilityTypeDefinition.getType()); return Either.right(addPropertiesToCapablityType.right().value()); } String derivedFrom = capabilityTypeDefinition.getDerivedFrom(); if (derivedFrom != null) { - log.debug( - "Before creating relation between capability type " + ctUniqueId + " to its parent " + derivedFrom); + log.debug("Before creating relation between capability type {} to its parent {}", ctUniqueId, derivedFrom); UniqueIdData from = new UniqueIdData(NodeTypeEnum.CapabilityType, ctUniqueId); UniqueIdData to = new UniqueIdData(NodeTypeEnum.CapabilityType, derivedFrom); - Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(from, to, - GraphEdgeLabels.DERIVED_FROM, null); - log.debug("After create relation between capability type {} to its parent {}. Status is {}", ctUniqueId, derivedFrom, createRelation); + Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(from, to, GraphEdgeLabels.DERIVED_FROM, null); + log.debug("After create relation between capability type {} to its parent {}. status is {}", ctUniqueId, derivedFrom, createRelation); if (createRelation.isRight()) { return Either.right(createRelation.right().value()); } @@ -234,8 +211,7 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab } - private CapabilityTypeData buildCapabilityTypeData(CapabilityTypeDefinition capabilityTypeDefinition, - String ctUniqueId) { + private CapabilityTypeData buildCapabilityTypeData(CapabilityTypeDefinition capabilityTypeDefinition, String ctUniqueId) { CapabilityTypeData capabilityTypeData = new CapabilityTypeData(capabilityTypeDefinition); @@ -250,8 +226,7 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab } @Override - public Either<CapabilityTypeDefinition, StorageOperationStatus> getCapabilityType(String uniqueId, - boolean inTransaction) { + public Either<CapabilityTypeDefinition, StorageOperationStatus> getCapabilityType(String uniqueId, boolean inTransaction) { Either<CapabilityTypeDefinition, StorageOperationStatus> result = null; try { @@ -261,7 +236,7 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab if (ctResult.isRight()) { TitanOperationStatus status = ctResult.right().value(); if (status != TitanOperationStatus.NOT_FOUND) { - log.error("Failed to retrieve information on capability type {}. Status is {}", uniqueId, status); + log.error("Failed to retrieve information on capability type {}. status is {}", uniqueId, status); } result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(ctResult.right().value())); return result; @@ -288,33 +263,30 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab Either<CapabilityTypeDefinition, TitanOperationStatus> result = null; - Either<CapabilityTypeData, TitanOperationStatus> capabilityTypesRes = titanGenericDao.getNode( - UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), uniqueId, CapabilityTypeData.class); + Either<CapabilityTypeData, TitanOperationStatus> capabilityTypesRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), uniqueId, CapabilityTypeData.class); if (capabilityTypesRes.isRight()) { TitanOperationStatus status = capabilityTypesRes.right().value(); - log.debug("Capability type {} cannot be found in graph. Status is {}", uniqueId, status); + log.debug("Capability type {} cannot be found in graph. status is {}", uniqueId, status); return Either.right(status); } CapabilityTypeData ctData = capabilityTypesRes.left().value(); - CapabilityTypeDefinition capabilityTypeDefinition = new CapabilityTypeDefinition( - ctData.getCapabilityTypeDataDefinition()); + CapabilityTypeDefinition capabilityTypeDefinition = new CapabilityTypeDefinition(ctData.getCapabilityTypeDataDefinition()); TitanOperationStatus propertiesStatus = fillProperties(uniqueId, capabilityTypeDefinition); if (propertiesStatus != TitanOperationStatus.OK) { - log.error("Failed to fetch properties of capability type " + uniqueId); + log.error("Failed to fetch properties of capability type {}", uniqueId); return Either.right(propertiesStatus); } - Either<ImmutablePair<CapabilityTypeData, GraphEdge>, TitanOperationStatus> parentNode = titanGenericDao - .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), uniqueId, - GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.CapabilityType, CapabilityTypeData.class); - log.debug("After retrieving DERIVED_FROM node of {}. Status is {}", uniqueId, parentNode); + Either<ImmutablePair<CapabilityTypeData, GraphEdge>, TitanOperationStatus> parentNode = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), uniqueId, GraphEdgeLabels.DERIVED_FROM, + NodeTypeEnum.CapabilityType, CapabilityTypeData.class); + log.debug("After retrieving DERIVED_FROM node of {}. status is {}", uniqueId, parentNode); if (parentNode.isRight()) { TitanOperationStatus titanOperationStatus = parentNode.right().value(); if (titanOperationStatus != TitanOperationStatus.NOT_FOUND) { - log.error("Failed to find the parent capability of capability type {}. Status is {}", uniqueId, titanOperationStatus); + log.error("Failed to find the parent capability of capability type {}. status is {}", uniqueId, titanOperationStatus); result = Either.right(titanOperationStatus); return result; } @@ -331,11 +303,10 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab private TitanOperationStatus fillProperties(String uniqueId, CapabilityTypeDefinition capabilityTypeDefinition) { - Either<Map<String, PropertyDefinition>, TitanOperationStatus> findPropertiesOfNode = propertyOperation - .findPropertiesOfNode(NodeTypeEnum.CapabilityType, uniqueId); + Either<Map<String, PropertyDefinition>, TitanOperationStatus> findPropertiesOfNode = propertyOperation.findPropertiesOfNode(NodeTypeEnum.CapabilityType, uniqueId); if (findPropertiesOfNode.isRight()) { TitanOperationStatus titanOperationStatus = findPropertiesOfNode.right().value(); - log.debug("After looking for properties of vertex {}. Status is {}", uniqueId, titanOperationStatus); + log.debug("After looking for properties of vertex {}. status is {}", uniqueId, titanOperationStatus); if (TitanOperationStatus.NOT_FOUND.equals(titanOperationStatus)) { return TitanOperationStatus.OK; } else { @@ -348,12 +319,10 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab } } - public Either<Boolean, StorageOperationStatus> isCapabilityTypeDerivedFrom(String childCandidateType, - String parentCandidateType) { + public Either<Boolean, StorageOperationStatus> isCapabilityTypeDerivedFrom(String childCandidateType, String parentCandidateType) { Map<String, Object> propertiesToMatch = new HashMap<String, Object>(); propertiesToMatch.put(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), childCandidateType); - Either<List<CapabilityTypeData>, TitanOperationStatus> getResponse = titanGenericDao - .getByCriteria(NodeTypeEnum.CapabilityType, propertiesToMatch, CapabilityTypeData.class); + Either<List<CapabilityTypeData>, TitanOperationStatus> getResponse = titanGenericDao.getByCriteria(NodeTypeEnum.CapabilityType, propertiesToMatch, CapabilityTypeData.class); if (getResponse.isRight()) { TitanOperationStatus titanOperationStatus = getResponse.right().value(); log.debug("Couldn't fetch capability type {}, error: {}", childCandidateType, titanOperationStatus); @@ -363,14 +332,12 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab Set<String> travelledTypes = new HashSet<>(); do { travelledTypes.add(childUniqueId); - Either<List<ImmutablePair<CapabilityTypeData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao - .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), childUniqueId, - GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.CapabilityType, CapabilityTypeData.class); + Either<List<ImmutablePair<CapabilityTypeData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), childUniqueId, GraphEdgeLabels.DERIVED_FROM, + NodeTypeEnum.CapabilityType, CapabilityTypeData.class); if (childrenNodes.isRight()) { if (childrenNodes.right().value() != TitanOperationStatus.NOT_FOUND) { TitanOperationStatus titanOperationStatus = getResponse.right().value(); - log.debug("Couldn't fetch derived from node for capability type {}, error: {}", childCandidateType, - titanOperationStatus); + log.debug("Couldn't fetch derived from node for capability type {}, error: {}", childCandidateType, titanOperationStatus); return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(titanOperationStatus)); } else { log.debug("Derived from node is not found for type {} - this is OK for root capability."); @@ -379,8 +346,7 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab } String derivedFromUniqueId = childrenNodes.left().value().get(0).getLeft().getUniqueId(); if (derivedFromUniqueId.equals(parentCandidateType)) { - log.debug("Verified that capability type {} derives from capability type {}", childCandidateType, - parentCandidateType); + log.debug("Verified that capability type {} derives from capability type {}", childCandidateType, parentCandidateType); return Either.left(true); } childUniqueId = derivedFromUniqueId; @@ -402,8 +368,7 @@ public class CapabilityTypeOperation extends AbstractOperation implements ICapab } @Override - public Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType( - CapabilityTypeDefinition capabilityTypeDefinition) { + public Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType(CapabilityTypeDefinition capabilityTypeDefinition) { return addCapabilityType(capabilityTypeDefinition, false); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperation.java index cb85888780..c487b0ce71 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentInstanceOperation.java @@ -29,6 +29,7 @@ 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.Function; import java.util.function.Supplier; import java.util.stream.Collectors; @@ -50,10 +51,12 @@ import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.dao.titan.TitanGenericDao; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; -import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyRule; +import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; @@ -67,7 +70,8 @@ import org.openecomp.sdc.be.model.ComponentInstanceAttribute; import org.openecomp.sdc.be.model.ComponentInstanceInput; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.GetInputValueInfo; +import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.GroupInstance; import org.openecomp.sdc.be.model.HeatParameterDefinition; import org.openecomp.sdc.be.model.IComponentInstanceConnectedElement; import org.openecomp.sdc.be.model.InputDefinition; @@ -78,6 +82,7 @@ import org.openecomp.sdc.be.model.RequirementAndRelationshipPair; 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.cache.ApplicationDataTypeCache; import org.openecomp.sdc.be.model.operations.api.IAttributeOperation; import org.openecomp.sdc.be.model.operations.api.IComponentInstanceOperation; @@ -99,6 +104,7 @@ import org.openecomp.sdc.be.resources.data.RelationshipTypeData; import org.openecomp.sdc.be.resources.data.RequirementData; import org.openecomp.sdc.be.resources.data.ResourceMetadataData; import org.openecomp.sdc.be.resources.data.UniqueIdData; +import org.openecomp.sdc.be.resources.data.UserData; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.openecomp.sdc.common.config.EcompErrorName; @@ -137,9 +143,6 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo private CapabilityInstanceOperation capabilityInstanceOperation; @Autowired - private CapabilityTypeOperation capabilityTypeOperation; - - @Autowired private RequirementOperation requirementOperation; @Autowired @@ -160,6 +163,12 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo @Autowired private ApplicationDataTypeCache dataTypeCache; + @Autowired + protected GroupOperation groupOperation; + + @Autowired + protected GroupInstanceOperation groupInstanceOperation; + /** * FOR TEST ONLY * @@ -180,12 +189,15 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo NodeTypeEnum compInstNodeType, boolean allowDeleted, boolean inTransaction) { Either<ComponentInstance, StorageOperationStatus> result = null; + if (!ValidationUtils.validateStringNotEmpty(componentInstance.getCustomizationUUID())) { + generateCustomizationUUID(componentInstance); + } try { Either<ComponentInstance, TitanOperationStatus> addRes = addComponentInstanceToContainerComponent(containerComponentId, containerNodeType, instanceNumber, isCreateLocgicalName, componentInstance, compInstNodeType, allowDeleted); if (addRes.isRight()) { TitanOperationStatus status = addRes.right().value(); - log.error("Failed to add resource instance {} to service {}. Status is {}", componentInstance, containerComponentId, status); + log.error("Failed to add resource instance {} to service {}. status is {}", componentInstance, containerComponentId, status); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); return result; } @@ -246,7 +258,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo if (deleteRes.isRight()) { TitanOperationStatus status = deleteRes.right().value(); - log.error("Failed to remove resource instance {} from component {}. Status is {}", resourceInstUid, containerComponentId, status); + log.error("Failed to remove resource instance {} from component {}. status is {}", resourceInstUid, containerComponentId, status); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); return result; } @@ -288,7 +300,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo if (updateRes.isRight()) { TitanOperationStatus status = updateRes.right().value(); - log.error("Failed to find resource instance name {}. Status is {}", uniqId, status); + log.error("Failed to find resource instance name {}. status is {}", uniqId, status); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); return result; } @@ -366,10 +378,48 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo Map<String, Object> properties = titanGenericDao.getProperties(ciVertex); ComponentInstanceData createdComponentInstance = GraphElementFactory.createElement(NodeTypeEnum.ResourceInstance.getName(), GraphElementTypeEnum.Node, properties, ComponentInstanceData.class); + Either<ComponentInstance, TitanOperationStatus> createdResourceInstanceRes = createGroupInstancesOnComponentInstance(componentInstance, ciVertex, createdComponentInstance); + return createdResourceInstanceRes; + } + + + public Either<ComponentInstance, TitanOperationStatus> createGroupInstancesOnComponentInstance(ComponentInstance componentInstance, TitanVertex ciVertex, ComponentInstanceData createdComponentInstance) { ComponentInstance createdResourceInstance = new ComponentInstance(createdComponentInstance.getComponentInstDataDefinition()); + createdResourceInstance.setGroupInstances(componentInstance.getGroupInstances()); + List<GroupInstance> groupInstancesList = new ArrayList<GroupInstance>(); + List<GroupDefinition> group = null; + Either<List<GroupDefinition>, TitanOperationStatus> groupEither = groupOperation.getAllGroupsFromGraph(createdResourceInstance.getComponentUid(), NodeTypeEnum.Resource); + if (groupEither.isRight() && groupEither.right().value() != TitanOperationStatus.OK && groupEither.right().value() != TitanOperationStatus.NOT_FOUND) { + TitanOperationStatus status = groupEither.right().value(); + log.debug("Failed to associate group instances to component instance {}. Status is {}", componentInstance.getUniqueId(), status); + return Either.right(status); + } else { + if (groupEither.isLeft()) { + group = groupEither.left().value(); + if (group != null && !group.isEmpty()) { + List<GroupDefinition> vfGroupsList = group.stream().filter(p -> p.getType().equals("org.openecomp.groups.VfModule")).collect(Collectors.toList()); + for (GroupDefinition groupDefinition : vfGroupsList) { + Either<GroupInstance, StorageOperationStatus> status = createGroupInstance(ciVertex, groupDefinition, createdResourceInstance); + if (status.isRight()) { + log.debug("Failed to associate group instances to component instance {}. Status is {}", componentInstance.getUniqueId(), status); + + } else { + GroupInstance groupInstance = status.left().value(); + groupInstancesList.add(groupInstance); + } + + } + createdResourceInstance.setGroupInstances(groupInstancesList); + } + } + } return Either.left(createdResourceInstance); + } + public void generateCustomizationUUID(ComponentInstance componentInstance) { + UUID uuid = UUID.randomUUID(); + componentInstance.setCustomizationUUID(uuid.toString()); } /** @@ -409,7 +459,6 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } String originType = (String) titanGenericDao.getProperty(originVertex, GraphPropertiesDictionary.LABEL.getProperty()); String resourceType = (String) titanGenericDao.getProperty(originVertex, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty()); - detectOriginType(originType, componentInstanceData, resourceType); log.trace("Before adding component instance to graph. componentInstanceData = {}", componentInstanceData); @@ -427,7 +476,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo TitanOperationStatus associateContainerRes = associateContainerCompToComponentInstance(metadataVertex, createdComponentInstanceVertex, logicalName); String componentInstanceUniqueId = componentInstanceData.getUniqueId(); - if (!associateContainerRes.equals(TitanOperationStatus.OK)) { + if (associateContainerRes != TitanOperationStatus.OK) { BeEcompErrorManager.getInstance().logBeDaoSystemError("Add Component Instance"); log.debug("Failed to associate container component {} to component instance {}. Status is {}", containerComponentId, componentInstanceUniqueId, associateContainerRes); return Either.right(associateContainerRes); @@ -435,20 +484,20 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo String originId = (String) titanGenericDao.getProperty(createdComponentInstanceVertex, GraphPropertiesDictionary.TYPE.getProperty()); TitanOperationStatus associateToInstOriginComponent = associateToInstOriginComponent(createdComponentInstanceVertex, originVertex, originId); - if (!associateToInstOriginComponent.equals(TitanOperationStatus.OK)) { + if (associateToInstOriginComponent != TitanOperationStatus.OK) { BeEcompErrorManager.getInstance().logBeDaoSystemError("Add Component Instance"); log.debug("Failed to associate component instance {} to its origin component {}. Status is {}", componentInstanceUniqueId, componentInstanceData.getComponentInstDataDefinition().getComponentUid(), associateToInstOriginComponent); return Either.right(associateToInstOriginComponent); } TitanOperationStatus associateCompInstToRequirements = associateCompInstToRequirements(createdComponentInstanceVertex, containerNodeType, compInstNodeType, originId); - if (!associateCompInstToRequirements.equals(TitanOperationStatus.OK)) { + if (associateCompInstToRequirements != TitanOperationStatus.OK) { BeEcompErrorManager.getInstance().logBeDaoSystemError("Add Component Instance"); log.debug("Failed to associate component instance {} to its origin requirements. Status is {}", componentInstanceUniqueId, associateCompInstToRequirements); return Either.right(associateCompInstToRequirements); } TitanOperationStatus associateCompInstToCapabilities = associateCompInstToCapabilities(createdComponentInstanceVertex, containerNodeType, compInstNodeType, originId); - if (!associateCompInstToCapabilities.equals(TitanOperationStatus.OK)) { + if (associateCompInstToCapabilities != TitanOperationStatus.OK) { BeEcompErrorManager.getInstance().logBeDaoSystemError("Add Component Instance"); log.debug("Failed to associate component instance {} to its origin capabilities. Status is {}", componentInstanceUniqueId, associateCompInstToCapabilities); return Either.right(associateCompInstToCapabilities); @@ -469,7 +518,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } else if (containerNodeType.equals(NodeTypeEnum.Resource) && componentInstance.getCapabilities() != null && !componentInstance.getCapabilities().isEmpty()) { // in case of creation from scar TitanOperationStatus addPropertiesRes = createCapabilityInstancesWithPropertyValues(createdComponentInstanceVertex, componentInstanceUniqueId, componentInstance.getCapabilities(), true); - if (!addPropertiesRes.equals(TitanOperationStatus.OK)) { + if (addPropertiesRes != TitanOperationStatus.OK) { status = addPropertiesRes; log.debug("Failed to create capability instances with property values for component instance {}. Status is {}", componentInstance.getUniqueId(), status); } @@ -490,13 +539,14 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo // in case of cloning of service log.trace("Before associating created component instance {} to cloned capability instances.", componentInstanceUniqueId); TitanOperationStatus associationStatus = associateCreatedComponentInstanceToClonedCapabilityInstances(createdComponentInstanceVertex, componentInstanceUniqueId, cloneCapabilityInstancesRes.left().value()); - if (!associationStatus.equals(TitanOperationStatus.OK) && !associationStatus.equals(TitanOperationStatus.NOT_FOUND)) { + if (associationStatus != TitanOperationStatus.OK && associationStatus != TitanOperationStatus.NOT_FOUND) { status = associationStatus; log.debug("Failed to associate capability instances to component instance {}. Status is {}", componentInstance.getUniqueId(), status); } log.trace("After associating created component instance {} to cloned capability instances. Status is {}", componentInstanceUniqueId, status); } } + if (status == null) { // ComponentInstance createdResourceInstance = new // ComponentInstance(createdComponentInstance.getComponentInstDataDefinition()); @@ -536,7 +586,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo CapabilityDefinition capability = capailityEntry.getValue().get(0); if (capability.getProperties() != null && !capability.getProperties().isEmpty()) { TitanOperationStatus addPropertiesRes = addCapabilityPropertyValuesToResourceInstance(resourceInstanceVertex, resourceInstanceId, capability, isNewlyCreatedResourceInstance); - if (!addPropertiesRes.equals(TitanOperationStatus.OK)) { + if (addPropertiesRes != TitanOperationStatus.OK) { result = addPropertiesRes; log.debug("Failed to add property values to capabilities of component instance {}. Status is {}", resourceInstanceId, result); return result; @@ -555,7 +605,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo capInstPair.getRight().getProperties()); if (associateComponentInstanceToCapabilityinstanceRes.isRight()) { error = associateComponentInstanceToCapabilityinstanceRes.right().value(); - log.debug("Failed to associate capability instance {} to resource instance {}. Status is {}.", capInstPair.getLeft().getUniqueId(), newComponentResourceId, error); + log.debug("Failed to associate capability instance {} to resource instance {} status is {}.", capInstPair.getLeft().getUniqueId(), newComponentResourceId, error); break; } else { relationsToCapabilityInstances.add(associateComponentInstanceToCapabilityinstanceRes.left().value()); @@ -571,7 +621,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo TitanOperationStatus error = null; for (ImmutablePair<TitanVertex, GraphEdge> capInstPair : capabilityInstances) { TitanOperationStatus associateComponentInstanceToCapabilityinstanceRes = titanGenericDao.createEdge(riVertex, capInstPair.getLeft(), GraphEdgeLabels.CAPABILITY_INST, capInstPair.getRight().getProperties()); - if (!associateComponentInstanceToCapabilityinstanceRes.equals(TitanOperationStatus.OK)) { + if (associateComponentInstanceToCapabilityinstanceRes != TitanOperationStatus.OK) { error = associateComponentInstanceToCapabilityinstanceRes; log.debug("Failed to associate capability instance {} to resource instance {} status is {} .", capInstPair.getLeft(), newComponentResourceId, error); break; @@ -595,7 +645,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo GraphEdgeLabels.RESOURCE_INST, NodeTypeEnum.ResourceInstance, ComponentInstanceData.class); if (getAllResourceInstanceRes.isRight() && !getAllResourceInstanceRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { error = getAllResourceInstanceRes.right().value(); - log.debug("Failed to retrieve resource instances from resource {}. Status is {}.", resourceId, error); + log.debug("Failed to retrieve resource instances from resource {} status is {}.", resourceId, error); } if (getAllResourceInstanceRes.isLeft()) { resourceInstancesPair = getAllResourceInstanceRes.left().value(); @@ -606,7 +656,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo GraphEdgeLabels.CAPABILITY_INST, NodeTypeEnum.CapabilityInst, CapabilityInstData.class); if (getCapabilityInstancesRes.isRight() && !getCapabilityInstancesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { error = getCapabilityInstancesRes.right().value(); - log.debug("Failed to retrieve capability instances of resource instance {}. Status is {}", ri.getUniqueId(), error); + log.debug("Failed to retrieve capability instances of resource instance {} status is {}.", ri.getUniqueId(), error); break; } if (getCapabilityInstancesRes.isLeft()) { @@ -620,7 +670,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo capInstPair.getRight().getProperties()); if (associateComponentInstanceToCapabilityinstanceRes.isRight()) { error = associateComponentInstanceToCapabilityinstanceRes.right().value(); - log.debug("Failed to associate capability instance {} to resource instance {}. Status is {}", capInstPair.getLeft().getUniqueId(), componentResourceId, error); + log.debug("Failed to associate capability instance {} to resource instance {} status is {}.", capInstPair.getLeft().getUniqueId(), componentResourceId, error); break; } else { relationsToCapabilityInstances.add(associateComponentInstanceToCapabilityinstanceRes.left().value()); @@ -633,8 +683,10 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo return Either.right(error); } - private void detectOriginType(String label, ComponentInstanceData componentInstanceData, String resourceTypeStr) { - switch (NodeTypeEnum.getByName(label)) { + private NodeTypeEnum detectOriginType(String label, ComponentInstanceData componentInstanceData, String resourceTypeStr) { + NodeTypeEnum res = null; + res = NodeTypeEnum.getByName(label); + switch (res) { case Service: componentInstanceData.getComponentInstDataDefinition().setOriginType(OriginTypeEnum.SERVICE); break; @@ -650,6 +702,9 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo case VFC: componentInstanceData.getComponentInstDataDefinition().setOriginType(OriginTypeEnum.VFC); break; + case VFCMT: + componentInstanceData.getComponentInstDataDefinition().setOriginType(OriginTypeEnum.VFCMT); + break; case CP: componentInstanceData.getComponentInstDataDefinition().setOriginType(OriginTypeEnum.CP); break; @@ -661,6 +716,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo default: break; } + return res; } private Either<GraphRelation, TitanOperationStatus> associateToInstOriginComponent(ComponentInstanceData componentInstanceData, NodeTypeEnum compInstNodeType) { @@ -669,10 +725,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(componentInstanceData, resourceIdData, GraphEdgeLabels.INSTANCE_OF, null); - log.debug("After associating resource instance {} to resource {}. Status is {}", - componentInstanceData.getUniqueId(), - componentInstanceData.getComponentInstDataDefinition().getUniqueId(), - createRelation); + log.debug("After associating resource instance {} to resource {}. status is {}", componentInstanceData.getUniqueId(), componentInstanceData.getComponentInstDataDefinition().getUniqueId(), createRelation); return createRelation; } @@ -742,12 +795,12 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo props.put(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), componentInstanceData.getUniqueId()); if (requirementDef.getMinOccurrences() == null) { - props.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), RequirementData.MIN_OCCURRENCES); + props.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), RequirementDataDefinition.MIN_OCCURRENCES); } else { props.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), requirementDef.getMinOccurrences()); } if (requirementDef.getMaxOccurrences() == null) { - props.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), RequirementData.MAX_DEFAULT_OCCURRENCES); + props.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), RequirementDataDefinition.MAX_DEFAULT_OCCURRENCES); } else { props.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), requirementDef.getMaxOccurrences()); } @@ -784,12 +837,12 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo props.put(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), compoInstId); if (requirementDef.getMinOccurrences() == null) { - props.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), RequirementData.MIN_OCCURRENCES); + props.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), RequirementDataDefinition.MIN_OCCURRENCES); } else { props.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), requirementDef.getMinOccurrences()); } if (requirementDef.getMaxOccurrences() == null) { - props.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), RequirementData.MAX_DEFAULT_OCCURRENCES); + props.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), RequirementDataDefinition.MAX_DEFAULT_OCCURRENCES); } else { props.put(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty(), requirementDef.getMaxOccurrences()); } @@ -857,8 +910,8 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo GraphEdge edge = calculatedReq.right; Map<String, Object> properties = edge.getProperties(); String source = null; - String occurrences = RequirementData.MAX_DEFAULT_OCCURRENCES; - String minOccurrences = RequirementData.MIN_OCCURRENCES; + String occurrences = RequirementDataDefinition.MAX_DEFAULT_OCCURRENCES; + String minOccurrences = RequirementDataDefinition.MIN_OCCURRENCES; if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.SOURCE.getProperty())) { source = (String) properties.get(GraphEdgePropertiesDictionary.SOURCE.getProperty()); @@ -898,8 +951,8 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo Edge edge = calculatedReq.right; Map<String, Object> properties = titanGenericDao.getProperties(edge); String source = null; - String occurrences = RequirementData.MAX_DEFAULT_OCCURRENCES; - String minOccurrences = RequirementData.MIN_OCCURRENCES; + String occurrences = RequirementDataDefinition.MAX_DEFAULT_OCCURRENCES; + String minOccurrences = RequirementDataDefinition.MIN_OCCURRENCES; if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.SOURCE.getProperty())) { source = (String) properties.get(GraphEdgePropertiesDictionary.SOURCE.getProperty()); @@ -943,8 +996,8 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.SOURCE.getProperty())) { source = (String) properties.get(GraphEdgePropertiesDictionary.SOURCE.getProperty()); } - String minOccurrences = CapabilityData.MIN_OCCURRENCES; - String occurrences = CapabilityData.MAX_OCCURRENCES; + String minOccurrences = CapabilityDataDefinition.MIN_OCCURRENCES; + String occurrences = CapabilityDataDefinition.MAX_OCCURRENCES; if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty())) { minOccurrences = (String) properties.get(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty()); } @@ -982,8 +1035,8 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.SOURCE.getProperty())) { source = (String) properties.get(GraphEdgePropertiesDictionary.SOURCE.getProperty()); } - String minOccurrences = CapabilityData.MIN_OCCURRENCES; - String occurrences = CapabilityData.MAX_OCCURRENCES; + String minOccurrences = CapabilityDataDefinition.MIN_OCCURRENCES; + String occurrences = CapabilityDataDefinition.MAX_OCCURRENCES; if (properties != null && properties.containsKey(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty())) { minOccurrences = (String) properties.get(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty()); } @@ -1021,8 +1074,8 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo log.trace("Creating calculated capability relation from component instance {} to capability {}", componentInstanceData.getUniqueId(), capabilityData.getUniqueId()); CapabilityData capabilityDataNode = new CapabilityData(); capabilityDataNode.setUniqueId(capabilityData.getUniqueId()); - String minOccurrences = CapabilityData.MIN_OCCURRENCES; - String occurrences = CapabilityData.MAX_OCCURRENCES; + String minOccurrences = CapabilityDataDefinition.MIN_OCCURRENCES; + String occurrences = CapabilityDataDefinition.MAX_OCCURRENCES; if (capabilityData.getMinOccurrences() != null) { minOccurrences = capabilityData.getMinOccurrences(); } @@ -1054,8 +1107,8 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo log.trace("Creating calculated capability relation from component instance {} to capability {}", compoInstId, capabilityData.getUniqueId()); CapabilityData capabilityDataNode = new CapabilityData(); capabilityDataNode.setUniqueId(capabilityData.getUniqueId()); - String minOccurrences = CapabilityData.MIN_OCCURRENCES; - String occurrences = CapabilityData.MAX_OCCURRENCES; + String minOccurrences = CapabilityDataDefinition.MIN_OCCURRENCES; + String occurrences = CapabilityDataDefinition.MAX_OCCURRENCES; if (capabilityData.getMinOccurrences() != null) { minOccurrences = capabilityData.getMinOccurrences(); } @@ -1220,7 +1273,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo // "_").toLowerCase(); dataDefinition.setName(logicalName); if (dataDefinition.getNormalizedName() == null) - dataDefinition.setNormalizedName(ValidationUtils.normaliseComponentInstanceName(logicalName)); + dataDefinition.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(logicalName)); dataDefinition.setUniqueId(UniqueIdBuilder.buildResourceInstanceUniuqeId(componentId, ciOriginComponentUid, dataDefinition.getNormalizedName())); ComponentInstanceData resourceInstanceData = new ComponentInstanceData(dataDefinition); @@ -1238,7 +1291,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo TitanOperationStatus status = node.right().value(); BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Remove Component Instance"); BeEcompErrorManager.getInstance().logBeDaoSystemError("Remove Component Instance"); - log.debug("Failed to delete component instance {}. Status is {}", componentInstanceUid, status); + log.debug("Failed to delete component instance {}. status is {}", componentInstanceUid, status); return Either.right(status); } @@ -1280,11 +1333,18 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo return Either.right(status); } } + + // delete associated properties + status = deleteAssociatedGroupInstances(componentInstanceUid); + if (status != TitanOperationStatus.OK) { + return Either.right(status); + } + Either<ComponentInstanceData, TitanOperationStatus> deleteRI = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), componentInstanceUid, ComponentInstanceData.class); if (deleteRI.isRight()) { TitanOperationStatus deleteRiStatus = deleteRI.right().value(); - log.error("Failed to delete resource instance {}. Status is {}", componentInstanceUid, deleteRiStatus); + log.error("Failed to delete resource instance {}. status is {}", componentInstanceUid, deleteRiStatus); return Either.right(deleteRiStatus); } @@ -1295,6 +1355,11 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo return Either.left(resourceInstance); } + private TitanOperationStatus deleteAssociatedGroupInstances(String componentInstanceUid) { + + return this.groupInstanceOperation.deleteAllGroupInstances(componentInstanceUid); + } + private TitanOperationStatus deleteAssociatedCapabilityInstances(String resourceInstanceId) { TitanOperationStatus status = TitanOperationStatus.OK; @@ -1326,7 +1391,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo if (artifactRes.isRight()) { TitanOperationStatus status = artifactRes.right().value(); if (status != TitanOperationStatus.NOT_FOUND) { - log.error("Failed to find artifacts of resource instance {}. Status is {}", resourceInstanceUid, status); + log.error("Failed to find artifacts of resource instance {}. status is {}", resourceInstanceUid, status); return status; } } else { @@ -1334,10 +1399,10 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo List<ImmutablePair<ArtifactData, GraphEdge>> artifactPairs = artifactRes.left().value(); for (ImmutablePair<ArtifactData, GraphEdge> pair : artifactPairs) { String uniqueId = (String) pair.left.getUniqueId(); - Either<ArtifactData, TitanOperationStatus> removeArifactFromGraph = artifactOperation.removeArtifactOnGraph(resourceInstanceUid, uniqueId, NodeTypeEnum.ResourceInstance, resourceInstanceUid, true); + Either<ArtifactData, TitanOperationStatus> removeArifactFromGraph = artifactOperation.removeArtifactOnGraph(resourceInstanceUid, uniqueId, NodeTypeEnum.ResourceInstance, true); if (removeArifactFromGraph.isRight()) { TitanOperationStatus status = removeArifactFromGraph.right().value(); - log.error("Failed to delete artifact of resource instance {}. Status is {}", resourceInstanceUid, status); + log.error("Failed to delete artifact of resource instance {}. status is {}", resourceInstanceUid, status); return status; } @@ -1404,7 +1469,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo if (relationsForTarget.isRight()) { TitanOperationStatus status = relationsForTarget.right().value(); if (status != TitanOperationStatus.NOT_FOUND) { - log.error("Failed to find the relationships of resource instance {}. Status is {}", resourceInstanceUid, status); + log.error("Failed to find the relationships of resource instance {}. status is {}", resourceInstanceUid, status); return status; } } else { @@ -1432,7 +1497,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo if (relationsForSource.isRight()) { TitanOperationStatus status = relationsForSource.right().value(); if (status != TitanOperationStatus.NOT_FOUND) { - log.error("Failed to find the relationships of resource instance " + resourceInstanceUid + ". status is " + status); + log.error("Failed to find the relationships of resource instance {}. status is {}", resourceInstanceUid, status); return status; } } else { @@ -1462,7 +1527,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo Either<RelationshipInstData, TitanOperationStatus> deleteNode = titanGenericDao.deleteNode(relationshipTypeImplData, RelationshipInstData.class); if (deleteNode.isRight()) { TitanOperationStatus status = deleteNode.right().value(); - log.error("Failed to delete relationship node {}. Status is {}", relationshipTypeImplData, status); + log.error("Failed to delete relationship node {}. status is {}", relationshipTypeImplData, status); return status; } } @@ -1495,7 +1560,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo Either<TitanVertex, TitanOperationStatus> riFrom = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), fromResInstanceUid); if (riFrom.isRight()) { - log.debug("Failed to fetch component instance {}. Error: {}", fromResInstanceUid, riFrom.right().value()); + log.debug("Failed to fetch component instance {}. error {}", fromResInstanceUid, riFrom.right().value()); return Either.right(riFrom.right().value()); } Iterator<Edge> edgeIter = riFrom.left().value().edges(Direction.OUT, GraphEdgeLabels.RELATIONSHIP_INST.getProperty()); @@ -1504,7 +1569,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo return Either.right(TitanOperationStatus.NOT_FOUND); } List<RelationshipInstData> deletedRelations = new ArrayList<>(); - List<String> vertexToDelete = new ArrayList<>(); + Set<String> vertexToDelete = new HashSet<String>(); while (edgeIter.hasNext()) { TitanEdge edge = (TitanEdge) edgeIter.next(); String name = (String) edge.property(GraphEdgePropertiesDictionary.NAME.getProperty()).value(); @@ -1531,7 +1596,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo // remove relation vertex Either<RelationshipInstData, TitanOperationStatus> relationNode = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.RelationshipInst), relationVertexId, RelationshipInstData.class); if (relationNode.isRight()) { - log.debug("Failed to delete relation node with id {}. Error: {}", relationVertexId, relationNode.right().value()); + log.debug("Failed to delete relation node with id {}. error {}", relationVertexId, relationNode.right().value()); return Either.right(relationNode.right().value()); } RelationshipInstData deletedRelation = relationNode.left().value(); @@ -1555,7 +1620,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo Either<List<RelationshipInstData>, TitanOperationStatus> dissociateRes = disconnectResourcesInService(componentId, nodeType, requirementDef); if (dissociateRes.isRight()) { TitanOperationStatus status = dissociateRes.right().value(); - log.error("Failed to dissociate resource instance " + fromResInstanceUid + " from resource instance " + toResInstanceUid + " in service " + componentId + ". status is " + status); + log.error("Failed to dissociate resource instance {} from resource instance {} in service {}. status is {}", fromResInstanceUid, toResInstanceUid, componentId, status); BeEcompErrorManager.getInstance().logBeDaoSystemError("dissociateComponentInstances"); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); return result; @@ -1564,13 +1629,23 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo if (!updateCalculatedCapReqResult.equals(StorageOperationStatus.OK)) { BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "dissociateComponentInstances"); BeEcompErrorManager.getInstance().logBeDaoSystemError("dissociateComponentInstances"); - log.debug("Failed to dissociate component instances {}. Status is {}", requirementDef, updateCalculatedCapReqResult); + log.debug("Failed to dissociate component instances. {}. status is {}", requirementDef, updateCalculatedCapReqResult); result = Either.right(updateCalculatedCapReqResult); return result; } - // RelationshipInstData relationshipInstData = - // dissociateRes.left().value(); + StorageOperationStatus status; + status = updateCustomizationUUID(requirementDef.getFromNode()); + if (status != StorageOperationStatus.OK) { + result = Either.right(status); + return result; + } + status = updateCustomizationUUID(requirementDef.getToNode()); + if (status != StorageOperationStatus.OK) { + result = Either.right(status); + return result; + } + List<RelationshipInstData> relationshipInstData = dissociateRes.left().value(); RequirementCapabilityRelDef capabilityRelDef = buildCapabilityResult(fromResInstanceUid, toResInstanceUid, requirement, relationshipInstData); @@ -1612,12 +1687,12 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo private StorageOperationStatus updateRequirementEdges(GraphEdgeLabels requirmentNewLabel, GraphEdgeLabels requirmentCurrentLabel, RequirementAndRelationshipPair pair, String requirementOwnerId) { Either<TitanVertex, TitanOperationStatus> reqOwnerRI = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), requirementOwnerId); if (reqOwnerRI.isRight()) { - log.debug("Failed to fetch requirment Owner by Id {}. Error: {}", requirementOwnerId, reqOwnerRI.right().value()); + log.debug("Failed to fetch requirment Owner by Id {} error {}", requirementOwnerId, reqOwnerRI.right().value()); return DaoStatusConverter.convertTitanStatusToStorageStatus(reqOwnerRI.right().value()); } Iterator<Edge> edgeIter = reqOwnerRI.left().value().edges(Direction.OUT, requirmentCurrentLabel.name(), requirmentNewLabel.name()); if (edgeIter == null) { - log.debug("No edges with label {} for woner RI {}", requirmentCurrentLabel, requirementOwnerId); + log.debug("No edges with label {} for owner RI {}", requirmentCurrentLabel, requirementOwnerId); return StorageOperationStatus.GENERAL_ERROR; } boolean associate = requirmentNewLabel.equals(GraphEdgeLabels.CALCULATED_REQUIREMENT_FULLFILLED) ? true : false; @@ -1635,7 +1710,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo String leftOccurrences = (String) titanGenericDao.getProperty(edge, GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty()); String requiredOccurrencesNew = "0"; - String leftOccurrencesNew = RequirementData.MAX_DEFAULT_OCCURRENCES; + String leftOccurrencesNew = RequirementDataDefinition.MAX_DEFAULT_OCCURRENCES; if (requiredOccurrences != null) { Integer iOccurrences = Integer.parseInt(requiredOccurrences); if (associate) { @@ -1646,7 +1721,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } else { String reqMinOccurrences = (String) titanGenericDao.getProperty(reqVertex, GraphPropertiesDictionary.MIN_OCCURRENCES.getProperty()); if (reqMinOccurrences == null) { - reqMinOccurrences = RequirementData.MIN_OCCURRENCES; + reqMinOccurrences = RequirementDataDefinition.MIN_OCCURRENCES; } if (Integer.parseInt(reqMinOccurrences) > iOccurrences) { iOccurrences++; @@ -1657,7 +1732,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo Map<String, Object> properties = titanGenericDao.getProperties(edge); properties.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), requiredOccurrencesNew); - if (leftOccurrences != null && !leftOccurrences.equals(RequirementData.MAX_OCCURRENCES)) { + if (leftOccurrences != null && !leftOccurrences.equals(RequirementDataDefinition.MAX_OCCURRENCES)) { Integer iOccurrences = Integer.parseInt(leftOccurrences); if (associate) { if (iOccurrences > 0) { @@ -1694,7 +1769,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo private StorageOperationStatus updateCapabiltyEdges(GraphEdgeLabels capabiltyNewLabel, GraphEdgeLabels capabiltyCurrentLabel, RequirementAndRelationshipPair pair, String capabiltyOwnerId) { Either<TitanVertex, TitanOperationStatus> capOwnerRI = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), capabiltyOwnerId); if (capOwnerRI.isRight()) { - log.debug("Failed to fetch requirment Owner by Id {}. Error: {}", capabiltyOwnerId, capOwnerRI.right().value()); + log.debug("Failed to fetch requirment Owner by Id {}. error {}", capabiltyOwnerId, capOwnerRI.right().value()); return DaoStatusConverter.convertTitanStatusToStorageStatus(capOwnerRI.right().value()); } Iterator<Edge> edgeIter = capOwnerRI.left().value().edges(Direction.OUT, capabiltyCurrentLabel.name(), capabiltyNewLabel.name()); @@ -1719,7 +1794,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo String leftOccurrences = (String) titanGenericDao.getProperty(edge, GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty()); String requiredOccurrencesNew = "0"; - String leftOccurrencesNew = CapabilityData.MAX_OCCURRENCES; + String leftOccurrencesNew = CapabilityDataDefinition.MAX_OCCURRENCES; if (requiredOccurrences != null) { Integer iOccurrences = Integer.parseInt(requiredOccurrences); if (associate) { @@ -1730,7 +1805,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } else { String reqMinOccurrences = (String) titanGenericDao.getProperty(capVertex, GraphPropertiesDictionary.MIN_OCCURRENCES.getProperty()); if (reqMinOccurrences == null) { - reqMinOccurrences = CapabilityData.MIN_OCCURRENCES; + reqMinOccurrences = CapabilityDataDefinition.MIN_OCCURRENCES; } if (Integer.parseInt(reqMinOccurrences) > iOccurrences) { iOccurrences++; @@ -1741,7 +1816,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo Map<String, Object> properties = titanGenericDao.getProperties(edge); properties.put(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty(), requiredOccurrencesNew); - if (leftOccurrences != null && !leftOccurrences.equals(CapabilityData.MAX_OCCURRENCES)) { + if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) { Integer iOccurrences = Integer.parseInt(leftOccurrences); if (associate) { if (iOccurrences > 0) { @@ -1806,24 +1881,24 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo relationship = relationPair.getRelationship().getType(); } - if (log.isDebugEnabled()) { - log.debug("Going to associate resource instance {} to resource instance {} under component {}. Requirement is {}.", fromResInstanceUid, toResInstanceUid, componentId, requirement); - } + log.debug("Going to associate resource instance {} to resource instance {} under component {}. Requirement is {}.", fromResInstanceUid, toResInstanceUid, componentId, requirement); Either<ComponentInstanceData, TitanOperationStatus> fromResourceInstDataRes = findMandatoryResourceInstData(fromResInstanceUid); if (fromResourceInstDataRes.isRight()) { TitanOperationStatus status = fromResourceInstDataRes.right().value(); - log.error("Failed to find resource instance {}. Status is {}", fromResInstanceUid, status); + log.error("Failed to find resource instance {}. status is {}", fromResInstanceUid, status); return Either.right(status); } - ComponentInstanceData fromResourceInstanceData = fromResourceInstDataRes.left().value(); + ComponentInstanceData fromCI = fromResourceInstDataRes.left().value(); + ComponentInstanceData fromResourceInstanceData = fromCI; Either<ComponentInstanceData, TitanOperationStatus> toResourceInstDataRes = findMandatoryResourceInstData(toResInstanceUid); if (toResourceInstDataRes.isRight()) { TitanOperationStatus status = toResourceInstDataRes.right().value(); - log.error("Failed to find resource instance " + toResInstanceUid + ". status is " + status); + log.error("Failed to find resource instance {}. status is {}", toResInstanceUid, status); return Either.right(status); } - ComponentInstanceData toResourceInstanceData = toResourceInstDataRes.left().value(); + ComponentInstanceData toCI = toResourceInstDataRes.left().value(); + ComponentInstanceData toResourceInstanceData = toCI; // THE component NodeTypeEnum should be sent TitanOperationStatus isResourceInstOfService = verifyResourceInstanceUnderComponent(nodeType, componentId, fromResInstanceUid); if (isResourceInstOfService != TitanOperationStatus.OK) { @@ -1837,24 +1912,24 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo Either<ImmutablePair<RelationshipTypeData, String>, TitanOperationStatus> isValidRes = validateRequirementVsCapability(fromResourceInstanceData, toResourceInstanceData, requirement, relationship, relationPair); if (isValidRes.isRight()) { TitanOperationStatus status = isValidRes.right().value(); - log.error("Failed to validate requirement {} between resource instance {} to resource instance {}. Status is {}", requirement, fromResInstanceUid, toResInstanceUid, status); + log.error("Failed to validate requirement {} between resource instance {} to resource instance {}. status is {}", requirement, fromResInstanceUid, toResInstanceUid, status); return Either.right(status); } RelationshipTypeData relationshipTypeData = isValidRes.left().value().getKey(); String capabilityName = isValidRes.left().value().getValue(); RelationshipInstData relationshipInstData = buildRelationshipInstData(fromResInstanceUid, requirement, relationshipTypeData, relationPair); - Either<RelationshipInstData, TitanOperationStatus> createNode = createRelationshipInstData(fromResourceInstDataRes.left().value(), relationshipInstData, relationshipTypeData, requirement); + Either<RelationshipInstData, TitanOperationStatus> createNode = createRelationshipInstData(fromCI, relationshipInstData, relationshipTypeData, requirement); if (createNode.isRight()) { return Either.right(createNode.right().value()); } RelationshipInstData createdRelInstData = createNode.left().value(); - Either<GraphRelation, TitanOperationStatus> associateResInst = associateRelationshipInstToTarget(toResourceInstDataRes.left().value(), requirement, capabilityName, createdRelInstData); + Either<GraphRelation, TitanOperationStatus> associateResInst = associateRelationshipInstToTarget(toCI, requirement, capabilityName, createdRelInstData); if (associateResInst.isRight()) { TitanOperationStatus status = associateResInst.right().value(); - log.error("Failed to associate relationship instance {} to target node {}. Status is {}", createdRelInstData.getUniqueId(), toResInstanceUid, status); + log.error("Failed to associate relationship instance {} to target node {}. status is {}", createdRelInstData.getUniqueId(), toResInstanceUid, status); return Either.right(status); } @@ -1868,7 +1943,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo if (parentNode.isRight()) { TitanOperationStatus status = parentNode.right().value(); - log.error("Failed to find the service associated to the resource instance {}. Status is {}", resInstanceUid, status); + log.error("Failed to find the service associated to the resource instance {}. status is {}", resInstanceUid, status); return status; } @@ -1881,7 +1956,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } else { BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeIncorrectServiceError, "Resource Instance - verifyResourceInstanceUnderComponent", containerComponentId); BeEcompErrorManager.getInstance().logBeIncorrectComponentError("Resource Instance - verifyResourceInstanceUnderComponent", containerNodeType.getName(), containerComponentId); - log.debug("The provided component id {} is not equal to the component ({}) which associated to resource instance {}.", containerComponentId, uniqueId, resInstanceUid); + log.debug("The provided component id {} is not equal to the component ({}) which associated to resource instance {}", containerComponentId, uniqueId, resInstanceUid); return TitanOperationStatus.INVALID_ID; } @@ -1919,7 +1994,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo Map<String, Object> props = new HashMap<String, Object>(); props.put(GraphPropertiesDictionary.NAME.getProperty(), capabilityName); Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(relInstData, toResInstance, GraphEdgeLabels.CAPABILITY_NODE, props); - log.debug("After creating relation between relationship instance {} to target node {}", relInstData.getUniqueId(), toResInstance.getUniqueId()); + log.debug("After creatingrelation between relationship instance {} to target node {}", relInstData.getUniqueId(), toResInstance.getUniqueId()); return createRelation; @@ -1950,7 +2025,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(resInstance, createdRelationshipInst, GraphEdgeLabels.RELATIONSHIP_INST, properties); if (createRelation.isRight()) { TitanOperationStatus status = createRelation.right().value(); - log.error("Failed to associate resource instance " + resInstance.getUniqueIdKey() + " to relationship instance " + createdRelationshipInst.getUniqueId() + ". status is " + status); + log.error("Failed to associate resource instance {} to relationship instance {}. status is {}", resInstance.getUniqueIdKey(), createdRelationshipInst.getUniqueId(), status); return Either.right(status); } @@ -1984,15 +2059,13 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } Either<RequirementDefinition, TitanOperationStatus> requirementDefinitionE = requirementOperation.getRequirement(relationPair.getRequirementUid()); if (requirementDefinitionE.isRight()) { - log.error("The requirement cannot be found {}" , relationPair.getRequirementUid()); + log.error("The requirement cannot be found {}", relationPair.getRequirementUid()); return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); } RequirementDefinition requirementDefinition = requirementDefinitionE.left().value(); String fetchedRequirementRelationship = requirementDefinition.getRelationship(); String fetchedRequirementCapability = requirementDefinition.getCapability(); - // TODO temporary remove of capability sources validation - uncomment - // after alignment // String fetchedRequirementNodeName = requirementDefinition.getNode(); TitanOperationStatus status = validateAvailableRequirement(fromResInstance, relationPair); @@ -2010,8 +2083,6 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo log.error("Failed to fetch the origin resource for capabilty resource instance with id {}, error {}", relationPair.getCapabilityOwnerId(), originCapabilty.right().value()); return Either.right(originCapabilty.right().value()); } - // TODO temporary remove of capability sources validation - uncomment - // after alignment // String originCapabId = // originCapabilty.left().value().getComponentInstDataDefinition().getComponentUid(); @@ -2027,13 +2098,11 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo CapabilityDefinition capabilityDefinition = capabilityDefinitionE.left().value(); String capabilityName = requirement; - if (log.isDebugEnabled()) { - log.debug("The capability {} of resource {} appropriates to requiremt {} on resource {}", capabilityDefinition, toResourceUid, requirement, fromResourceUid); - } + log.debug("The capability {} of resource {} appropriates to requirement {} on resource {}", capabilityDefinition, toResourceUid, requirement, fromResourceUid); String capabilityType = capabilityDefinition.getType(); if (false == fetchedRequirementCapability.equals(capabilityType)) { - log.error("The capability type in the requirement ({}) does not equal to the capability on the resource {}({})", fetchedRequirementCapability, toResourceUid, capabilityType); + log.error("The capability type in the requirement ({}) does not equal to the capability on the resource {} ({})", fetchedRequirementCapability, toResourceUid, capabilityType); return Either.right(TitanOperationStatus.MATCH_NOT_FOUND); } @@ -2054,7 +2123,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo private TitanOperationStatus validateAvailableRequirement(ComponentInstanceData fromResInstance, RequirementAndRelationshipPair relationPair) { Either<TitanVertex, TitanOperationStatus> fromRi = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), fromResInstance.getUniqueId()); if (fromRi.isRight()) { - log.debug("Failed to fetch component instance {}. Error: {}", fromResInstance.getUniqueId(), fromRi.right().value()); + log.debug("Failed to fetch component instance {} error {}", fromResInstance.getUniqueId(), fromRi.right().value()); return fromRi.right().value(); } Iterator<Edge> edgeIter = fromRi.left().value().edges(Direction.OUT, GraphEdgeLabels.CALCULATED_REQUIREMENT.name()); @@ -2071,7 +2140,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo String ownerIdOnEdge = (String) edge.value(GraphEdgePropertiesDictionary.OWNER_ID.getProperty()); if (ownerIdOnEdge.equals(relationPair.getRequirementOwnerId())) { String leftOccurrences = (String) titanGenericDao.getProperty(edge, GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty()); - if (leftOccurrences != null && !leftOccurrences.equals(RequirementData.MAX_OCCURRENCES)) { + if (leftOccurrences != null && !leftOccurrences.equals(RequirementDataDefinition.MAX_OCCURRENCES)) { Integer leftIntValue = Integer.parseInt(leftOccurrences); if (leftIntValue > 0) { exist = true; @@ -2106,7 +2175,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo String ownerIdOnEdge = (String) edge.value(GraphEdgePropertiesDictionary.OWNER_ID.getProperty()); if (ownerIdOnEdge.equals(relationPair.getCapabilityOwnerId())) { String leftOccurrences = (String) titanGenericDao.getProperty(edge, GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty()); - if (leftOccurrences != null && !leftOccurrences.equals(CapabilityData.MAX_OCCURRENCES)) { + if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) { Integer leftIntValue = Integer.parseInt(leftOccurrences); if (leftIntValue > 0) { exist = true; @@ -2150,7 +2219,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo List<ResourceMetadataData> resourcesPathList = new ArrayList<ResourceMetadataData>(); TitanOperationStatus status = resourceOperation.findResourcesPathRecursively(resourceUid, resourcesPathList); if (status != TitanOperationStatus.OK) { - log.error("Failed to find the parent list of resource {}. Status is {}", resourceUid, status); + log.error("Failed to find the parent list of resource {}. status is {}", resourceUid, status); return status; } @@ -2213,7 +2282,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo if (updateRes.isRight()) { TitanOperationStatus status = updateRes.right().value(); - log.error("Failed to update resource instance {}. Status is {}", resourceInstanceUid, status); + log.error("Failed to update resource instance {}. status is {}", resourceInstanceUid, status); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); return result; } @@ -2256,13 +2325,24 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo instance.setPropertyValueCounter(resourceInstance.getPropertyValueCounter()); instance.setAttributeValueCounter(resourceInstance.getAttributeValueCounter()); instance.setInputValueCounter(resourceInstance.getInputValueCounter()); + + boolean isNeedGenerate = isNeedGenerateCustomizationUUID(resourceInstance, currentInst); + if (isNeedGenerate) { + generateCustomizationUUID(instance); + } else { + instance.setCustomizationUUID(resourceInstance.getCustomizationUUID()); + } return instance; } + private boolean isNeedGenerateCustomizationUUID(ComponentInstance resourceInstance, ComponentInstanceData currentInst) { + return !currentInst.getComponentInstDataDefinition().getName().equals(resourceInstance.getName()); + } + private void printDiff(ComponentInstanceData currentInst, ComponentInstance resourceInstance) { log.debug("The current Resource Instance details are : {}", currentInst); - log.debug("The received Resource Instance details for update are : {}", resourceInstance); + log.debug("The received Resource Instance details for update are :{}", resourceInstance); } @@ -2274,11 +2354,11 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo public Either<ComponentInstance, TitanOperationStatus> updateResourceInstanceInService(String serviceId, String resourceInstanceUid, ComponentInstance resourceInstance) { - log.debug("Going to update resource instance {}. Properties are {}", resourceInstanceUid, resourceInstance); + log.trace("Going to update resource instance {}. Properies are {}", resourceInstanceUid, resourceInstance); Either<ComponentInstanceData, TitanOperationStatus> findInstRes = findResourceInstance(resourceInstanceUid); if (findInstRes.isRight()) { TitanOperationStatus status = findInstRes.right().value(); - log.error("Failed to find resource instance {}. Status is {}", resourceInstanceUid, status); + log.error("Failed to find resource instance {}. status is {}", resourceInstanceUid, status); return Either.right(status); } @@ -2294,7 +2374,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo Either<ComponentInstanceData, TitanOperationStatus> updateNodeRes = titanGenericDao.updateNode(resourceInstanceData, ComponentInstanceData.class); if (updateNodeRes.isRight()) { TitanOperationStatus status = updateNodeRes.right().value(); - log.error("Failed to update resource instance {}. Status is {}", resourceInstanceUid, status); + log.error("Failed to update resource instance {}. status is {}", resourceInstanceUid, status); return Either.right(status); } @@ -2319,7 +2399,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo if (resInstancesOfService.isRight()) { TitanOperationStatus status = resInstancesOfService.right().value(); if (status != TitanOperationStatus.NOT_FOUND) { - log.error("Failed to find resource instances of service {}. Status is {}", componentId, status); + log.error("Failed to find resource instances of service {}. status is {}", componentId, status); } result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); return result; @@ -2348,7 +2428,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo if (updateRes.isRight()) { TitanOperationStatus status = updateRes.right().value(); - log.error("Failed to find component instance name {}. Status is {}", componentInstName, status); + log.error("Failed to find component instance name {}. status is {}", componentInstName, status); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); return result; } @@ -2422,7 +2502,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo Either<ComponentMetadataData, TitanOperationStatus> componentRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(containerNodeType), componentId, ComponentMetadataData.class); if (componentRes.isRight()) { TitanOperationStatus status = componentRes.right().value(); - log.error("Failed to find component {}. Status is {}", componentId, status); + log.error("Failed to find component {}. status is {}", componentId, status); return Either.right(status); } @@ -2440,7 +2520,8 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo if (resourceInstances != null && false == resourceInstances.isEmpty()) { Map<String, Map<String, CapabilityDefinition>> compInstCapabilities = new HashMap<String, Map<String, CapabilityDefinition>>(); Map<String, Map<String, RequirementDefinition>> compInstReq = new HashMap<String, Map<String, RequirementDefinition>>(); - Map<String, Map<String, ArtifactDefinition>> compInstArtifacts = new HashMap<String, Map<String, ArtifactDefinition>>(); + Map<String, Map<String, ArtifactDefinition>> compInstDeploymentArtifacts = new HashMap<String, Map<String, ArtifactDefinition>>(); + Map<String, Map<String, ArtifactDefinition>> compInstInformationalArtifacts = new HashMap<String, Map<String, ArtifactDefinition>>(); Map<String, Component> compInstOriginsMap = new HashMap<String, Component>(); for (ImmutablePair<ComponentInstanceData, GraphEdge> immutablePair : resourceInstances) { @@ -2451,7 +2532,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo ComponentInstance resourceInstance = new ComponentInstance(resourceInstanceData.getComponentInstDataDefinition()); - TitanOperationStatus status = getFullComponentInstance(compInstCapabilities, compInstReq, compInstArtifacts, compInstOriginsMap, resourceInstance, compInstNodeType); + TitanOperationStatus status = getFullComponentInstance(compInstCapabilities, compInstReq, compInstDeploymentArtifacts, compInstOriginsMap, resourceInstance, compInstNodeType, compInstInformationalArtifacts); if (status != TitanOperationStatus.OK) { return Either.right(status); } @@ -2507,11 +2588,11 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo if (relationshipsRes.isRight()) { status = relationshipsRes.right().value(); - log.debug("After fetching all reslationships of resource instance {}. Status is {}", resourceInstanceUid, status); + log.debug("After fetching all reslationships of resource instance {}. status is {}", resourceInstanceUid, status); if (status == TitanOperationStatus.NOT_FOUND) { return Either.left(requirementsResult); } else { - log.error("Failed to find relationhips of resource instance {}. Status is {}", resourceInstanceUid, status); + log.error("Failed to find relationhips of resource instance {}. status is {}", resourceInstanceUid, status); return Either.right(status); } } @@ -2545,11 +2626,11 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo if (relationshipsRes.isRight()) { status = relationshipsRes.right().value(); - log.debug("After fetching all reslationships of resource instance {}. Status is {}", resourceInstanceUid, status); + log.debug("After fetching all reslationships of resource instance {}. status is {}", resourceInstanceUid, status); if (status == TitanOperationStatus.NOT_FOUND) { return Either.left(requirementsResult); } else { - log.error("Failed to find relationhips of resource instance {}. Status is {}", resourceInstanceUid, status); + log.error("Failed to find relationhips of resource instance {}. status is {}", resourceInstanceUid, status); return Either.right(status); } } @@ -2576,10 +2657,11 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo public Either<ComponentInstance, StorageOperationStatus> getFullComponentInstance(ComponentInstance componentInstance, NodeTypeEnum compInstNodeType) { Map<String, Map<String, CapabilityDefinition>> compInstCapabilities = new HashMap<String, Map<String, CapabilityDefinition>>(); Map<String, Map<String, RequirementDefinition>> compInstReq = new HashMap<String, Map<String, RequirementDefinition>>(); - Map<String, Map<String, ArtifactDefinition>> compInstArtifacts = new HashMap<String, Map<String, ArtifactDefinition>>(); + Map<String, Map<String, ArtifactDefinition>> compInstDeploymentArtifacts = new HashMap<String, Map<String, ArtifactDefinition>>(); + Map<String, Map<String, ArtifactDefinition>> compInstInformationalArtifacts = new HashMap<String, Map<String, ArtifactDefinition>>(); Map<String, Component> compInstOrigins = new HashMap<String, Component>(); - TitanOperationStatus fullResourceInstance = getFullComponentInstance(compInstCapabilities, compInstReq, compInstArtifacts, compInstOrigins, componentInstance, compInstNodeType); + TitanOperationStatus fullResourceInstance = getFullComponentInstance(compInstCapabilities, compInstReq, compInstDeploymentArtifacts, compInstOrigins, componentInstance, compInstNodeType, compInstInformationalArtifacts); if (!fullResourceInstance.equals(TitanOperationStatus.OK)) { log.debug("failed to get full data of resource instance. error: {}", fullResourceInstance); return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(fullResourceInstance)); @@ -2588,7 +2670,8 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } private TitanOperationStatus getFullComponentInstance(Map<String, Map<String, CapabilityDefinition>> compInstCapabilities, Map<String, Map<String, RequirementDefinition>> compInstReq, - Map<String, Map<String, ArtifactDefinition>> compInstArtifacts, Map<String, Component> compInstOrigins, ComponentInstance compInst, NodeTypeEnum compInstNodeType) { + Map<String, Map<String, ArtifactDefinition>> compInstDeploymentArtifacts, Map<String, Component> compInstOrigins, ComponentInstance compInst, NodeTypeEnum compInstNodeType, + Map<String, Map<String, ArtifactDefinition>> compInstInformationalArtifacts) { Component component = null; ComponentOperation componentOperation = getComponentOperation(compInstNodeType); String componentUid = compInst.getComponentUid(); @@ -2649,20 +2732,110 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } - capStatus = setCompInstDeploymentArtifactsFromGraph(compInstArtifacts, componentUid, compInst); + capStatus = setCompInstDeploymentArtifactsFromGraph(compInstDeploymentArtifacts, componentUid, compInst); + if (capStatus != StorageOperationStatus.OK) { + log.debug("Failed to find resource deployment artifacts of resource {}. status is {}", componentName, capStatus); + + } + + capStatus = setCompInstInformationalArtifactsResourceFromGraph(compInstInformationalArtifacts, componentUid, compInst); if (capStatus != StorageOperationStatus.OK) { log.debug("Failed to find resource deployment artifacts of resource {}. status is {}", componentName, capStatus); } - capStatus = setCompInstArtifactsFromGraph(compInst); + capStatus = setCompInstDeploymentArtifactsFromGraph(compInst); if (capStatus != StorageOperationStatus.OK) { log.debug("Failed to find resource deployment artifacts of resource instance {} . status is {}", compInst.getName(), capStatus); } + + capStatus = setCompInstInformationaltArtifactsFromGraph(compInst); + if (capStatus != StorageOperationStatus.OK) { + log.debug("Failed to find resource informational artifacts of resource instance {} . status is {}", compInst.getName(), capStatus); + } + + capStatus = setGroupInstFromGraph(compInst); + if (capStatus != StorageOperationStatus.OK) { + log.debug("Failed to find resource groups of resource instance {} . status is {}", compInst.getName(), capStatus); + } return TitanOperationStatus.OK; } - protected StorageOperationStatus setCompInstArtifactsFromGraph(ComponentInstance resourceInstance) { + private StorageOperationStatus setCompInstInformationaltArtifactsFromGraph(ComponentInstance resourceInstance) { + Map<String, ArtifactDefinition> informationalArtifacts = null; + if (resourceInstance.getArtifacts() == null) { + informationalArtifacts = new HashMap<String, ArtifactDefinition>(); + } else { + informationalArtifacts = new HashMap<String, ArtifactDefinition>(resourceInstance.getArtifacts()); + } + + Either<Map<String, ArtifactDefinition>, StorageOperationStatus> result = artifactOperation.getArtifacts(resourceInstance.getUniqueId(), NodeTypeEnum.ResourceInstance, true, ArtifactGroupTypeEnum.INFORMATIONAL.getType()); + if (result.isRight()) { + StorageOperationStatus status = result.right().value(); + if (status != StorageOperationStatus.NOT_FOUND) { + return status; + } + } else { + informationalArtifacts.putAll(result.left().value()); + } + + resourceInstance.setArtifacts(informationalArtifacts); + return StorageOperationStatus.OK; + } + + private StorageOperationStatus setGroupInstFromGraph(ComponentInstance compInst) { + List<GroupInstance> groupInstances = null; + + Either<List<GroupInstance>, StorageOperationStatus> result = groupInstanceOperation.getAllGroupInstances(compInst.getUniqueId(), NodeTypeEnum.ResourceInstance); + if (result.isRight()) { + StorageOperationStatus status = result.right().value(); + if (status != StorageOperationStatus.NOT_FOUND) { + return status; + } else { + + return StorageOperationStatus.OK; + } + } + + groupInstances = result.left().value(); + compInst.setGroupInstances(groupInstances); + + return StorageOperationStatus.OK; + } + + private StorageOperationStatus setCompInstInformationalArtifactsResourceFromGraph(Map<String, Map<String, ArtifactDefinition>> resourcesInformationalArtifacts, String componentUid, ComponentInstance resourceInstance) { + + if (resourcesInformationalArtifacts.containsKey(componentUid)) { + resourceInstance.setArtifacts(resourcesInformationalArtifacts.get(componentUid)); + return StorageOperationStatus.OK; + } + + Either<Map<String, ArtifactDefinition>, StorageOperationStatus> result = artifactOperation.getArtifacts(componentUid, NodeTypeEnum.Resource, true, ArtifactGroupTypeEnum.INFORMATIONAL.getType()); + if (result.isRight()) { + StorageOperationStatus status = result.right().value(); + if (status != StorageOperationStatus.NOT_FOUND) { + return status; + } else { + return StorageOperationStatus.OK; + } + } + Map<String, ArtifactDefinition> artifacts = result.left().value(); + if (!artifacts.isEmpty()) { + Map<String, ArtifactDefinition> tempArtifacts = new HashMap<>(artifacts); + for (Entry<String, ArtifactDefinition> artifact : artifacts.entrySet()) { + if (!artifact.getValue().checkEsIdExist()) { + tempArtifacts.remove(artifact.getKey()); + } + } + resourceInstance.setArtifacts(tempArtifacts); + resourcesInformationalArtifacts.put(componentUid, tempArtifacts); + } + + return StorageOperationStatus.OK; + + } + + protected StorageOperationStatus setCompInstDeploymentArtifactsFromGraph(ComponentInstance resourceInstance) { Map<String, ArtifactDefinition> deploymentArtifacts = null; if (resourceInstance.getDeploymentArtifacts() == null) { @@ -2691,7 +2864,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo log.debug("failed to get heat parameters values for heat artifact {}", artifact.getUniqueId()); return heatParamsForEnv.right().value(); } else { - artifact.setHeatParameters(heatParamsForEnv.left().value()); + artifact.setListHeatParameters(heatParamsForEnv.left().value()); } } } @@ -2706,17 +2879,6 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } - // resourceInstance) { - // ArrayList<HeatParameterDefinition>(); - // heatEnvArtifact.getGeneratedFromId()); - // Either<List<ImmutablePair<HeatParameterValueData, GraphEdge>>, - // TitanOperationStatus> heatEnvValuesWithEdges = titanGenericDao - // !heatEnvValuesWithEdges.right().value().equals(TitanOperationStatus.NOT_FOUND)) - // { - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // heatEnvValuesWithEdges.left().value()){ - // pair.right.getProperties().get(GraphEdgePropertiesDictionary.NAME.getProperty()); - // heatValuesMap.get(parameter.getName()); private Either<List<ImmutablePair<ComponentInstanceData, GraphEdge>>, TitanOperationStatus> getAllComponentInstanceFromGraph(String componentId, NodeTypeEnum containerNodeType, boolean withEdges) { if (log.isDebugEnabled()) log.debug("Going to fetch all resource instances nodes in graph associate to component {}", componentId); @@ -2757,7 +2919,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo if (targetNodeRes.isRight()) { TitanOperationStatus status = targetNodeRes.right().value(); - log.error("Failed to find the target node of relationship inst {}. Status is {}", relationshipInstData, status); + log.error("Failed to find the target node of relationship inst {}. status is {}", relationshipInstData, status); return status; } @@ -2782,7 +2944,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo if (sourceNodeRes.isRight()) { TitanOperationStatus status = sourceNodeRes.right().value(); - log.error("Failed to find the source node of relationship inst {}. Status is {}", relationshipInstData, status); + log.error("Failed to find the source node of relationship inst {}. status is {}", relationshipInstData, status); return status; } @@ -2816,7 +2978,6 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo requirementCapabilityRelDef.setToNode(targetResourceUid); String sourceUid = sourceToRel.getKey(); requirementCapabilityRelDef.setFromNode(sourceUid); - List<RequirementAndRelationshipPair> relationships = new ArrayList<RequirementAndRelationshipPair>(); populateRelationships(sourceToRel, relationships); @@ -2860,6 +3021,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo pair.setCapabilityUid(relationshipInstData.getCapabiltyId()); pair.setRequirementOwnerId(relationshipInstData.getRequirementOwnerId()); pair.setRequirementUid(relationshipInstData.getRequirementId()); + pair.setId(relationshipInstData.getUniqueId()); relationships.add(pair); } } @@ -2874,16 +3036,16 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } @Override - public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String componentId, NodeTypeEnum nodeType, RequirementCapabilityRelDef relation, boolean inTransaction) { + public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String componentId, NodeTypeEnum nodeType, RequirementCapabilityRelDef relation, boolean inTransaction, boolean isClone) { Either<RequirementCapabilityRelDef, StorageOperationStatus> result = null; try { - Either<RequirementCapabilityRelDef, TitanOperationStatus> multiRequirements = associateResourceInstancesMultiRequirements(componentId, nodeType, relation); + Either<RequirementCapabilityRelDef, TitanOperationStatus> multiRequirements = associateResourceInstancesMultiRequirements(componentId, nodeType, relation, isClone); if (multiRequirements.isRight()) { TitanOperationStatus status = multiRequirements.right().value(); BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "associateComponentInstances"); BeEcompErrorManager.getInstance().logBeDaoSystemError("associateComponentInstances"); - log.debug("Failed to associate component instances. {}. Status is {}", relation, status); + log.debug("Failed to associate component instances {}. status is {}", relation, status); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); return result; } @@ -2891,7 +3053,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo if (!updateCalculatedCapReqResult.equals(StorageOperationStatus.OK)) { BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "associateComponentInstances"); BeEcompErrorManager.getInstance().logBeDaoSystemError("associateComponentInstances"); - log.debug("Failed to associate component instances. {}. Status is {}", relation, updateCalculatedCapReqResult); + log.debug("Failed to associate component instances. {}. status is {}", relation, updateCalculatedCapReqResult); result = Either.right(updateCalculatedCapReqResult); return result; } @@ -2906,7 +3068,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } } - private Either<RequirementCapabilityRelDef, TitanOperationStatus> associateResourceInstancesMultiRequirements(String componentId, NodeTypeEnum nodeType, RequirementCapabilityRelDef relation) { + private Either<RequirementCapabilityRelDef, TitanOperationStatus> associateResourceInstancesMultiRequirements(String componentId, NodeTypeEnum nodeType, RequirementCapabilityRelDef relation, boolean isClone) { String fromNode = relation.getFromNode(); String toNode = relation.getToNode(); @@ -2928,7 +3090,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo TitanOperationStatus status = associateRes.right().value(); BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeFailedAddingResourceInstanceError, "AssociateResourceInstances", fromNode, componentId); BeEcompErrorManager.getInstance().logBeFailedAddingResourceInstanceError("AssociateResourceInstances - missing relationship", fromNode, componentId); - log.debug("Failed to associate resource instance {} to resource instnace {}. Status is {}", fromNode, toNode, status); + log.debug("Failed to associate resource instance {} to resource instance {}. status is {}", fromNode, toNode, status); return Either.right(status); } @@ -2942,6 +3104,18 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo requirementAndRelationshipPair.setCapabilityUid(immutablePair.getCapabilityUid()); requirementAndRelationshipPair.setRequirementUid(immutablePair.getRequirementUid()); relationshipsResult.add(requirementAndRelationshipPair); + if (!isClone) { + log.trace("update customization UUID for from CI {} and to CI {}", relation.getFromNode(), relation.getToNode()); + StorageOperationStatus status; + status = updateCustomizationUUID(relation.getFromNode()); + if (status != StorageOperationStatus.OK) { + return Either.right(TitanOperationStatus.GENERAL_ERROR); + } + status = updateCustomizationUUID(relation.getToNode()); + if (status != StorageOperationStatus.OK) { + return Either.right(TitanOperationStatus.GENERAL_ERROR); + } + } } @@ -2955,7 +3129,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo @Override public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String componentId, NodeTypeEnum nodeType, RequirementCapabilityRelDef relation) { - return associateResourceInstances(componentId, nodeType, relation, false); + return associateResourceInstances(componentId, nodeType, relation, false, false); } @Override @@ -2970,7 +3144,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeSystemError, "deleteAllResourceInstances - missing relationship"); BeEcompErrorManager.getInstance().logBeSystemError("deleteAllResourceInstances - missing relationship"); } - log.debug("Failed to delete resource instances of service {}. Status is {}", containerComponentId, status); + log.debug("Failed to delete resource instances of service {}. status is {}", containerComponentId, status); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); return result; @@ -3002,7 +3176,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo if (resourceInstancesRes.isRight()) { TitanOperationStatus status = resourceInstancesRes.right().value(); - log.debug("After fetching all resource instances of service {}. Status is {}", componentId, status); + log.debug("After fetching all resource instances of service {}. status is {}", componentId, status); return Either.right(status); } @@ -3015,14 +3189,14 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo log.debug("After removing resource instance {}. Result is {}", resourceInstUid, removeResourceInstanceRes); if (removeResourceInstanceRes.isRight()) { TitanOperationStatus status = removeResourceInstanceRes.right().value(); - log.error("After removing resource instance {}. Status is {}", resourceInstUid, status); + log.error("After removing resource instance {}. status is {}", resourceInstUid, status); return Either.right(status); } ComponentInstance resourceInstance = removeResourceInstanceRes.left().value(); result.add(resourceInstance); } - log.debug("The following resource instances was deleted from service {}:{}", componentId, result); + log.debug("The following resource instances was deleted from service {} : {}", componentId, result); return Either.left(result); } @@ -3112,7 +3286,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo pair.setCapabilityOwnerId(capOwnerId); } - Either<RequirementCapabilityRelDef, StorageOperationStatus> associateInstances = associateResourceInstances(component.getUniqueId(), containerNodeType, relation, true); + Either<RequirementCapabilityRelDef, StorageOperationStatus> associateInstances = associateResourceInstances(component.getUniqueId(), containerNodeType, relation, true, true); if (associateInstances.isRight()) { StorageOperationStatus status = associateInstances.right().value(); log.error("failed to assosiate resource instance {} and resource instance {}. status ={}", relation.getFromNode(), relation.getToNode(), status); @@ -3131,33 +3305,6 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo ImmutablePair<List<ComponentInstance>, Map<String, String>> result = new ImmutablePair<List<ComponentInstance>, Map<String, String>>(list, oldCompInstToNew); - // Either<ImmutablePair<List<ComponentInstance>, - // List<RequirementCapabilityRelDef>>, StorageOperationStatus> - // allResourceInstances = getAllComponentInstances(componentIdFrom, - // containerNodeType, compInstNodeType, true); - // - // - // if (allResourceInstances.isRight()) { - // StorageOperationStatus status = allResourceInstances.right().value(); - // if (status.equals(StorageOperationStatus.NOT_FOUND)) { - // - // return Either.left(result); - // } else { - // log.error("failed to get all resource instances for service {}. - // status={}", componentIdFrom, status); - // return Either.right(status); - // } - // } - - // ImmutablePair<List<ComponentInstance>, - // List<RequirementCapabilityRelDef>> instanceRelationPair = - // allResourceInstances.left().value(); - - // ImmutablePair<List<ComponentInstance>, - // List<RequirementCapabilityRelDef>> instanceRelationPair = new - // ImmutablePair<List<ComponentInstance>, - // List<RequirementCapabilityRelDef>>(prevResource.getComponentInstances(), - // prevResource.getComponentInstancesRelations()); List<ComponentInstance> riList = prevResource.getComponentInstances(); Map<String, ComponentInstance> riMapper = new HashMap<>(); int instanceNumber = 0; @@ -3238,7 +3385,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo pair.setCapabilityOwnerId(capOwnerId); } - Either<RequirementCapabilityRelDef, StorageOperationStatus> associateInstances = associateResourceInstances(componentIdTo, containerNodeType, relation, true); + Either<RequirementCapabilityRelDef, StorageOperationStatus> associateInstances = associateResourceInstances(componentIdTo, containerNodeType, relation, true, true); if (associateInstances.isRight()) { StorageOperationStatus status = associateInstances.right().value(); log.error("failed to assosiate resource instance {} and resource instance {}. status ={}", relation.getFromNode(), relation.getToNode(), status); @@ -3251,7 +3398,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo private boolean isAtomicComponentInstance(ComponentInstance componentInstance) { OriginTypeEnum originType = componentInstance.getOriginType(); - if (originType.equals(OriginTypeEnum.VFC) || originType.equals(OriginTypeEnum.VL) || originType.equals(OriginTypeEnum.CP)) { + if (originType == OriginTypeEnum.VFC || originType == OriginTypeEnum.VFCMT || originType == OriginTypeEnum.VL || originType == OriginTypeEnum.CP) { return true; } return false; @@ -3269,9 +3416,14 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } Map<String, ArtifactDefinition> artifacts = getArtifactsOfRI.left().value(); + List<GroupInstance> groupInstancesFrom = fromResourceInstance.getGroupInstances(); + List<GroupInstance> groupInstancesTo = toResourceInstance.getGroupInstances(); + Map<String, List<String>> groupsInstanceArtifact = new HashMap<String, List<String>>(); for (Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) { ArtifactDefinition artifactDefinition = entry.getValue(); + String generatedFromIdArtifactUid = artifactDefinition.getGeneratedFromId(); + // US687135 Do not Add VF_MODULES_METADATA when checking out if (ArtifactTypeEnum.VF_MODULES_METADATA.getType().equals(artifactDefinition.getArtifactType())) { // The artifact of type VF_MODULES_METADATA should not be cloned @@ -3287,7 +3439,37 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo if (addArifactToResource.isRight()) { return addArifactToResource.right().value(); } + + if (groupInstancesTo != null) { + for (GroupInstance groupInstanceTo : groupInstancesTo) { + Optional<String> op = groupInstanceTo.getArtifacts().stream().filter(p -> p.equals(generatedFromIdArtifactUid)).findAny(); + if (op.isPresent()) { + + List<String> artifactsUid = null; + if (groupsInstanceArtifact.containsKey(groupInstanceTo.getUniqueId())) { + artifactsUid = groupsInstanceArtifact.get(groupInstanceTo.getUniqueId()); + } else { + artifactsUid = new ArrayList<String>(); + } + artifactsUid.add(addArifactToResource.left().value().getUniqueId()); + groupsInstanceArtifact.put(groupInstanceTo.getUniqueId(), artifactsUid); + break; + } + } + + } + } + if (groupsInstanceArtifact != null && !groupsInstanceArtifact.isEmpty()) { + for (Map.Entry<String, List<String>> groupArtifact : groupsInstanceArtifact.entrySet()) { + groupInstanceOperation.associateArtifactsToGroupInstance(groupArtifact.getKey(), groupArtifact.getValue()); + } } + Either<List<GroupInstance>, StorageOperationStatus> groupInstanceStatus = groupInstanceOperation.getAllGroupInstances(toResourceInstance.getUniqueId(), NodeTypeEnum.ResourceInstance); + if (groupInstanceStatus.isRight()) { + log.debug("failed to get groupinstance for component inatance {}", toResourceInstance.getUniqueId()); + return groupInstanceStatus.right().value(); + } + toResourceInstance.setGroupInstances(groupInstanceStatus.left().value()); toResourceInstance.setDeploymentArtifacts(artifacts); return StorageOperationStatus.OK; } @@ -3406,11 +3588,11 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo Either<List<String>, TitanOperationStatus> resInstancesOfService = getComponentInstancesNameOfService(serviceId, nodeType); - log.debug("After fetching resource instances of service {}. Result is {}", serviceId, resInstancesOfService); + log.debug("After fetching resource instances of service {}. result is {}", serviceId, resInstancesOfService); if (resInstancesOfService.isRight()) { TitanOperationStatus status = resInstancesOfService.right().value(); if (status != TitanOperationStatus.NOT_FOUND) { - log.error("Failed to find resource instances of service {}. Status is {}", serviceId, status); + log.error("Failed to find resource instances of service {}. status is {}", serviceId, status); } result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); return result; @@ -3438,7 +3620,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo Either<List<ImmutablePair<ComponentInstanceData, GraphEdge>>, TitanOperationStatus> resourceInstancesRes = getAllComponentInstanceFromGraph(serviceId, nodeType, false); if (resourceInstancesRes.isRight()) { TitanOperationStatus status = resourceInstancesRes.right().value(); - log.debug("Resource instance was found under service {}. Status is {}", serviceId, status); + log.debug("Resource instance was found under service {}. status is {}", serviceId, status); return Either.right(status); } @@ -3570,15 +3752,15 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo return status; } + @Override public Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> getCapabilities(ComponentInstance compInstance, NodeTypeEnum nodeTypeEnum) { - DataNodeCollector<CapabilityData> collector = () -> titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeTypeEnum), compInstance.getUniqueId(), GraphEdgeLabels.CALCULATED_CAPABILITY, NodeTypeEnum.Capability, CapabilityData.class); return getDataFromGraph(collector); - } + @Override public Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> getRequirements(ComponentInstance compInstance, NodeTypeEnum nodeTypeEnum) { DataNodeCollector<RequirementData> collector = () -> titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeTypeEnum), compInstance.getUniqueId(), GraphEdgeLabels.CALCULATED_REQUIREMENT, NodeTypeEnum.Requirement, @@ -3588,6 +3770,24 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } + @Override + public Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> getFulfilledCapabilities(ComponentInstance compInstance, NodeTypeEnum nodeTypeEnum) { + DataNodeCollector<CapabilityData> collector = () -> titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeTypeEnum), compInstance.getUniqueId(), GraphEdgeLabels.CALCULATED_CAPABILITY_FULLFILLED, NodeTypeEnum.Capability, + CapabilityData.class); + + return getDataFromGraph(collector); + } + + @Override + public Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> getFulfilledRequirements(ComponentInstance compInstance, NodeTypeEnum nodeTypeEnum) { + + DataNodeCollector<RequirementData> collector = () -> titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeTypeEnum), compInstance.getUniqueId(), GraphEdgeLabels.CALCULATED_REQUIREMENT_FULLFILLED, NodeTypeEnum.Requirement, + RequirementData.class); + + return getDataFromGraph(collector); + + } + public Either<Boolean, StorageOperationStatus> isAvailableRequirement(ComponentInstance fromResInstance, RequirementAndRelationshipPair relationPair) { Either<TitanVertex, TitanOperationStatus> fromRi = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), fromResInstance.getUniqueId()); if (fromRi.isRight()) { @@ -3608,7 +3808,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo String ownerIdOnEdge = (String) edge.value(GraphEdgePropertiesDictionary.OWNER_ID.getProperty()); if (ownerIdOnEdge.equals(relationPair.getRequirementOwnerId())) { String leftOccurrences = (String) edge.value(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty()); - if (leftOccurrences != null && !leftOccurrences.equals(RequirementData.MAX_OCCURRENCES)) { + if (leftOccurrences != null && !leftOccurrences.equals(RequirementDataDefinition.MAX_OCCURRENCES)) { Integer leftIntValue = Integer.parseInt(leftOccurrences); if (leftIntValue > 0) { exist = true; @@ -3626,7 +3826,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo public Either<Boolean, StorageOperationStatus> isAvailableCapabilty(ComponentInstance toResInstance, RequirementAndRelationshipPair relationPair) { Either<TitanVertex, TitanOperationStatus> fromRi = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), toResInstance.getUniqueId()); if (fromRi.isRight()) { - log.debug("Failed to fetch component instance {}. Error: {}", toResInstance.getUniqueId(), fromRi.right().value()); + log.debug("Failed to fetch component instance {} error {}", toResInstance.getUniqueId(), fromRi.right().value()); return Either.right(StorageOperationStatus.NOT_FOUND); } Iterator<Edge> edgeIter = fromRi.left().value().edges(Direction.OUT, GraphEdgeLabels.CALCULATED_CAPABILITY.name()); @@ -3643,7 +3843,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo String ownerIdOnEdge = (String) edge.value(GraphEdgePropertiesDictionary.OWNER_ID.getProperty()); if (ownerIdOnEdge.equals(relationPair.getCapabilityOwnerId())) { String leftOccurrences = (String) edge.value(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty()); - if (leftOccurrences != null && !leftOccurrences.equals(CapabilityData.MAX_OCCURRENCES)) { + if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) { Integer leftIntValue = Integer.parseInt(leftOccurrences); if (leftIntValue > 0) { exist = true; @@ -3727,7 +3927,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo List<ComponentInstanceAttribute> attributesOnInstance = compInstanceAttList.getInnerElement(); for (int i = 0; i < attributesOnInstance.size() && storageStatusWrapper.isEmpty(); i++) { StorageOperationStatus result = cloneSingleAttributeOnResourceInstance(createdInstanceVertex, attributesOnInstance.get(i), instanceId); - if (!result.equals(StorageOperationStatus.OK)) { + if (result != StorageOperationStatus.OK) { log.trace("Failed to clone attribute for instance {} error {}", instanceId, result); return result; } @@ -4024,7 +4224,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo Either<ComponentInstanceProperty, TitanOperationStatus> addPropertyToResourceInstance = this.addPropertyToResourceInstance(property, toResourceInstance, false, index, resourceInstanceId); - if (addPropertyToResourceInstance.isRight() && !addPropertyToResourceInstance.right().value().equals(TitanOperationStatus.OK)) { + if (addPropertyToResourceInstance.isRight() && addPropertyToResourceInstance.right().value() != TitanOperationStatus.OK) { StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(addPropertyToResourceInstance.right().value()); return storageStatus; } @@ -4032,13 +4232,13 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo ComponentInstanceProperty newProp = addPropertyToResourceInstance.left().value(); Set<String> inputsKey = inputsPropMap.keySet(); String inputToAssName = null; - GetInputValueInfo getInputInfo = null; + GetInputValueDataDefinition getInputInfo = null; for (String inputName : inputsKey) { List<ComponentInstanceProperty> propsList = inputsPropMap.get(inputName); Optional<ComponentInstanceProperty> op = propsList.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny(); if (op.isPresent()) { ComponentInstanceProperty inpProp = op.get(); - getInputInfo = new GetInputValueInfo(); + getInputInfo = new GetInputValueDataDefinition(); getInputInfo.setPropName(inpProp.getName()); getInputInfo.setInputName(inputName); inputToAssName = inputName; @@ -4536,7 +4736,8 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo * Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes.left().value()); * * String newValue = value; if (isValid.isRight()) { Boolean res = isValid.right().value(); if (res == false) { return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); } } else { Object object = isValid.left().value(); if (object != - * null) { newValue = object.toString(); } } InputValueData propertyValueData = updateDataContainer.getValueDataWrapper().getInnerElement(); log.debug("Going to update property value from {} to {}", propertyValueData.getValue(), newValue); propertyValueData.setValue(newValue); + * null) { newValue = object.toString(); } } InputValueData propertyValueData = updateDataContainer.getValueDataWrapper().getInnerElement(); log.debug("Going to update property value from " + propertyValueData.getValue() + " to " + + * newValue); propertyValueData.setValue(newValue); * * ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, resourceInstanceProerty.getRules(), innerType, allDataTypes.left().value()); if (pair.getRight() != null && pair.getRight() == false) { * BeEcompErrorManager.getInstance(). logBeInvalidValueError("Add property value", pair.getLeft(), resourceInstanceProerty.getName(), propertyType); return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); } @@ -4695,7 +4896,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } if (isPropertyValueExists.getLeft() != TitanOperationStatus.NOT_FOUND) { - log.debug("After finding property value of {} on component instance {}", propertyId, resourceInstanceId); + log.debug("After finding property value of {} on componenet instance {}", propertyId, resourceInstanceId); return Either.right(isPropertyValueExists.getLeft()); } @@ -4771,8 +4972,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo if (createRelResult.isRight()) { TitanOperationStatus operationStatus = createRelResult.right().value(); - // TODO: change logger - log.error("Failed to associate property value " + uniqueId + " to property " + propertyId + " in graph. status is " + operationStatus); + log.error("Failed to associate property value {} to property {} in graph. status is {}", uniqueId, propertyId, operationStatus); return Either.right(operationStatus); } @@ -4780,8 +4980,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo if (createRelResult.isRight()) { TitanOperationStatus operationStatus = createRelResult.right().value(); - // TODO: change logger - log.error("Failed to associate resource instance " + resourceInstanceId + " property value " + uniqueId + " in graph. status is " + operationStatus); + log.error("Failed to associate resource instance {} property value {} in graph. status is {}", resourceInstanceId, uniqueId, operationStatus); return Either.right(operationStatus); } @@ -4879,7 +5078,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo log.trace("Before validateAndUpdateRules"); ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, resourceInstanceProperty.getRules(), innerType, allDataTypes.left().value(), isValidate); - log.debug("After validateAndUpdateRules. pair = {}", pair); + log.debug("After validateAndUpdateRules. pair = {} ", pair); if (pair.getRight() != null && pair.getRight() == false) { BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), resourceInstanceProperty.getName(), propertyType); return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); @@ -4900,20 +5099,19 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo if (createRelResult.isRight()) { TitanOperationStatus operationStatus = createRelResult.right().value(); - // TODO: change logger - log.error("Failed to associate property value " + uniqueId + " to property " + propertyId + " in graph. status is " + operationStatus); + log.error("Failed to associate property value {} to property {} in graph. status is {}", uniqueId, propertyId, operationStatus); return Either.right(operationStatus); } TitanOperationStatus edgeResult = titanGenericDao.createEdge(resourceInstanceVertex, propertyValueData, GraphEdgeLabels.PROPERTY_VALUE, null); - if (!edgeResult.equals(TitanOperationStatus.OK)) { - log.error("Failed to associate resource instance " + resourceInstanceId + " property value " + uniqueId + " in graph. status is " + edgeResult); + if (edgeResult != TitanOperationStatus.OK) { + log.error("Failed to associate resource instance {} property value {} in graph. status is {}", resourceInstanceId, uniqueId, edgeResult); return Either.right(edgeResult); } ComponentInstanceProperty propertyValueResult = propertyOperation.buildResourceInstanceProperty(propertyValueData, resourceInstanceProperty); - log.debug("The returned ResourceInstanceProperty is {}", propertyValueResult); + log.debug("The returned ResourceInstanceProperty is {} ", propertyValueResult); return Either.left(propertyValueResult); } else { @@ -4963,7 +5161,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo ImmutablePair<TitanOperationStatus, String> isInputValueExists = inputOperation.findInputValue(resourceInstanceId, propertyId); if (isInputValueExists.getLeft() == TitanOperationStatus.ALREADY_EXIST) { - log.debug("The property {} already added to the resource insance {}", propertyId, resourceInstanceId); + log.debug("The property {} already added to the resource instance {}", propertyId, resourceInstanceId); resourceInstanceInput.setValueUniqueUid(isInputValueExists.getRight()); /* * Either<InputValueData, TitanOperationStatus> updatePropertyOfResourceInstance = updatePropertyOfResourceInstance(resourceInstanceInput, resourceInstanceId); if (updatePropertyOfResourceInstance.isRight()) { @@ -4973,7 +5171,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } if (isInputValueExists.getLeft() != TitanOperationStatus.NOT_FOUND) { - log.debug("After finding input value of {} on compnent instance {}", propertyId, resourceInstanceId); + log.debug("After finding input value of {} on componenet instance {}", propertyId, resourceInstanceId); return Either.right(isInputValueExists.getLeft()); } @@ -4992,7 +5190,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } PropertyDataDefinition propDef = def.getProperty(); if (propDef == null) { - log.debug("Property in Schema Definition inside property of type {} doesn't exists", type); + log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); } innerType = propDef.getType(); @@ -5005,21 +5203,6 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); return Either.right(status); } - // Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes.left().value()); - // log.debug("After validateAndUpdatePropertyValue. isValid = {}", isValid); - - /*String newValue = value; - if (isValid.isRight()) { - Boolean res = isValid.right().value(); - if (res == false) { - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); - } - } else { - Object object = isValid.left().value(); - if (object != null) { - newValue = object.toString(); - } - }*/ String uniqueId = UniqueIdBuilder.buildResourceInstanceInputValueUid(resourceInstanceData.getUniqueId(), index); InputValueData propertyValueData = new InputValueData(); @@ -5028,7 +5211,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo log.debug("Before validateAndUpdateRules"); ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, resourceInstanceInput.getRules(), innerType, allDataTypes.left().value(), true); - log.debug("After validateAndUpdateRules. pair = {}", pair); + log.debug("After validateAndUpdateRules. pair = {} ", pair); if (pair.getRight() != null && pair.getRight() == false) { BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), resourceInstanceInput.getName(), propertyType); return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); @@ -5049,8 +5232,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo if (createRelResult.isRight()) { TitanOperationStatus operationStatus = createRelResult.right().value(); - // TODO: change logger - log.error("Failed to associate property value {} to property {} in graph. Status is {}", uniqueId, propertyId, operationStatus); + log.error("Failed to associate property value {} to property {} in graph. status is {}", uniqueId, propertyId, operationStatus); return Either.right(operationStatus); } @@ -5063,8 +5245,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo if (createRelResult.isRight()) { TitanOperationStatus operationStatus = createNodeResult.right().value(); - // TODO: change logger - log.error("Failed to associate resource instance {} property value {} in graph. Status is {}", resourceInstanceId, uniqueId, operationStatus); + log.error("Failed to associate resource instance {} property value {} in graph. status is {}", resourceInstanceId, uniqueId, operationStatus); return Either.right(operationStatus); } @@ -5282,6 +5463,40 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo return Either.left(result); } + // TODO Tal G US831698 + public Either<List<ComponentInstanceProperty>, StorageOperationStatus> getComponentInstancesPropertiesAndValuesFromGraph(ComponentInstance resourceInstance) { + + Map<String, List<PropertyDefinition>> alreadyProcessedResources = new HashMap<>(); + Map<String, List<ComponentInstanceProperty>> alreadyProcessedInstances = new HashMap<>(); + Map<String, ImmutablePair<ComponentInstance, Integer>> processedInstances = new HashMap<>(); + Map<String, List<ComponentInstanceProperty>> resourceInstancesProperties = new HashMap<>(); + + List<String> path = new ArrayList<>(); + path.add(resourceInstance.getUniqueId()); + Either<List<ComponentInstanceProperty>, TitanOperationStatus> componentInstanceProperties = getComponentInstanceProperties(resourceInstance, alreadyProcessedResources, alreadyProcessedInstances, processedInstances, path); + + if (componentInstanceProperties.isRight()) { + StorageOperationStatus convertTitanStatusToStorageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(componentInstanceProperties.right().value()); + return Either.right(convertTitanStatusToStorageStatus); + } + + List<ComponentInstanceProperty> listOfProps = componentInstanceProperties.left().value(); + resourceInstancesProperties.put(resourceInstance.getUniqueId(), listOfProps); + + processedInstances.put(resourceInstance.getUniqueId(), new ImmutablePair<ComponentInstance, Integer>(resourceInstance, path.size())); + path.remove(path.size() - 1); + + Either<Map<String, Map<String, ComponentInstanceProperty>>, TitanOperationStatus> findAllPropertiesValuesOnInstances = findAllPropertyValueOnInstances(processedInstances); + // 1. check status + if (findAllPropertiesValuesOnInstances.isRight()) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(findAllPropertiesValuesOnInstances.right().value())); + } + + propertyOperation.updatePropertiesByPropertyValues(resourceInstancesProperties, findAllPropertiesValuesOnInstances.left().value()); + + return Either.left(resourceInstancesProperties.get(resourceInstance.getUniqueId())); + } + public Either<List<ComponentInstanceProperty>, TitanOperationStatus> getComponentInstanceProperties(ComponentInstance resourceInstance, Map<String, List<PropertyDefinition>> alreadyProcessedResources, Map<String, List<ComponentInstanceProperty>> alreadyProcessedInstances, Map<String, ImmutablePair<ComponentInstance, Integer>> processedInstances, List<String> path) { @@ -5333,7 +5548,6 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo resourceInstancePropertyList.add(resourceInstanceProperty); } - } OriginTypeEnum originType = resourceInstance.getOriginType(); @@ -5381,7 +5595,9 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo case PRODUCT: containerNodeType = NodeTypeEnum.Product; compInstNodeType = NodeTypeEnum.Service; + break; case VFC: + case VFCMT: case VL: case CP: break; @@ -5418,7 +5634,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo return null; } - List<String> clonedList = new ArrayList(); + List<String> clonedList = new ArrayList<String>(); clonedList.addAll(list); return clonedList; @@ -5441,7 +5657,6 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo ImmutablePair<ComponentInstance, Integer> pair = entry.getValue(); ComponentInstance componentInstance = pair.getLeft(); - Integer level = pair.getRight(); Either<List<ComponentInstanceProperty>, TitanOperationStatus> propeprtyValueOnCIResult = findPropertyValueOnComponentInstance(componentInstance); @@ -5454,10 +5669,10 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } List<ComponentInstanceProperty> propertyValuesOnCI = propeprtyValueOnCIResult.left().value(); - if (propeprtyValueOnCIResult != null) { + if (propertyValuesOnCI != null) { for (ComponentInstanceProperty instanceProperty : propertyValuesOnCI) { boolean result = addPropertyValue(compInstUniqueId, instanceProperty, propertyToInstanceValue); - if (result == false) { + if (!result) { return Either.right(TitanOperationStatus.ALREADY_EXIST); } } @@ -5558,7 +5773,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo capability.getUniqueId(), capability.getName(), capability.getProperties(), !isNewlyCreatedResourceInstance); if (addCapInstWithPropertiesRes.isRight()) { error = addCapInstWithPropertiesRes.right().value(); - log.debug("Failed to assotiate capability instance to resource instance {}. Status is {}", resourceInstanceId, error); + log.debug("Failed to assotiate capability instance to resource instance {}. status is {}", resourceInstanceId, error); } log.debug("After adding capability property values to resource instance {}. Status is {}", resourceInstanceId, error); if (error == null) { @@ -5573,7 +5788,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo TitanOperationStatus addCapInstWithPropertiesRes = capabilityInstanceOperation.createCapabilityInstanceOfCapabilityWithPropertyValuesForResourceInstance(resourceInstanceVertex, resourceInstanceId, capability.getUniqueId(), capability.getName(), capability.getProperties(), !isNewlyCreatedResourceInstance); - if (!addCapInstWithPropertiesRes.equals(TitanOperationStatus.OK)) { + if (addCapInstWithPropertiesRes != TitanOperationStatus.OK) { error = addCapInstWithPropertiesRes; log.debug("Failed to assotiate capability instance to resource instance {} . status is {}", resourceInstanceId, error); } @@ -5596,7 +5811,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo Either<List<PropertyValueData>, TitanOperationStatus> updateCapabilityPropertyValuesRes = capabilityInstanceOperation.updateCapabilityPropertyValues(resourceInstanceId, capabilityId, propertyValues); if (updateCapabilityPropertyValuesRes.isRight()) { error = updateCapabilityPropertyValuesRes.right().value(); - log.debug("Failed to update property values of capability {} of resource instance {}. Status is {}", capabilityId, resourceInstanceId, error); + log.debug("Failed to update property values of capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, error); } log.debug("After updating property values of capability {} of resource instance {}. Status is {}", capabilityId, resourceInstanceId, error); if (error == null) { @@ -5619,14 +5834,14 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo Either<CapabilityInstData, TitanOperationStatus> getCapInstByCapabilityRes = capabilityInstanceOperation.getCapabilityInstanceOfCapabilityOfResourceInstance(resourceInstanceId, capabilityId); if (getCapInstByCapabilityRes.isRight()) { error = getCapInstByCapabilityRes.right().value(); - log.debug("Failed to retrieve capability instance of capability {} of resource instance {}. Status is {}", capabilityId, resourceInstanceId, error); + log.debug("Failed to retrieve capability instance of capability {} of resource instance {}. status is {}", capabilityId, resourceInstanceId, error); } if (error == null) { String capabilityInstanceId = getCapInstByCapabilityRes.left().value().getUniqueId(); deleteCapInstWithPropertiesRes = capabilityInstanceOperation.deleteCapabilityInstanceFromResourceInstance(resourceInstanceId, capabilityInstanceId); if (deleteCapInstWithPropertiesRes.isRight()) { error = deleteCapInstWithPropertiesRes.right().value(); - log.debug("Failed to delete capability instance {} to resource instance {}. Status is {}", capabilityInstanceId, resourceInstanceId, error); + log.debug("Failed to delete capability instance {} to resource instance {}. status is {}", capabilityInstanceId, resourceInstanceId, error); } } log.debug("After deleting property values of capability {} from resource instance {}. Status is {}", capabilityId, resourceInstanceId, error); @@ -5653,7 +5868,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo Either<List<ImmutablePair<CapabilityInstData, GraphEdge>>, TitanOperationStatus> getAllCapabilityInstancesRes = capabilityInstanceOperation.getAllCapabilityInstancesOfResourceInstance(resourceInstanceId); if (getAllCapabilityInstancesRes.isRight() && !getAllCapabilityInstancesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { error = getAllCapabilityInstancesRes.right().value(); - log.debug("Failed to get capability instances of component instance {}. Status is {}", resourceInstanceId, error); + log.debug("Failed to get capability instances of component instance {}. status is {}", resourceInstanceId, error); } if (getAllCapabilityInstancesRes.isLeft()) { List<ImmutablePair<CapabilityInstData, GraphEdge>> capabilityInstances = getAllCapabilityInstancesRes.left().value(); @@ -5670,7 +5885,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo cloneAssociateCIWithPropertyValuesRes = capabilityInstanceOperation.cloneAssociateCapabilityInstanceWithPropertyValues(createdComponentInstance, relatedCapability, capabilityInstPair); if (cloneAssociateCIWithPropertyValuesRes.isRight()) { error = cloneAssociateCIWithPropertyValuesRes.right().value(); - log.debug("Failed to clone capability instances {} of component instance {}. Status is {}", capabilityInstPair.getLeft().getUniqueId(), resourceInstanceId, error); + log.debug("Failed to clone capability instances {} of component instance {}. status is {}", capabilityInstPair.getLeft().getUniqueId(), resourceInstanceId, error); break; } else { result.put(new ImmutablePair<CapabilityInstData, GraphEdge>(cloneAssociateCIWithPropertyValuesRes.left().value().getLeft(), capabilityInstPair.getRight()), cloneAssociateCIWithPropertyValuesRes.left().value().getRight()); @@ -5691,7 +5906,7 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo Either<TitanVertex, TitanOperationStatus> cloneAssociateCIWithPropertyValuesRes = null; Either<List<ImmutablePair<CapabilityInstData, GraphEdge>>, TitanOperationStatus> getAllCapabilityInstancesRes = capabilityInstanceOperation.getAllCapabilityInstancesOfResourceInstance(resourceInstanceId); - if (getAllCapabilityInstancesRes.isRight() && !getAllCapabilityInstancesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { + if (getAllCapabilityInstancesRes.isRight() && getAllCapabilityInstancesRes.right().value() != TitanOperationStatus.NOT_FOUND) { error = getAllCapabilityInstancesRes.right().value(); log.debug("Failed to get capability instances of component instance {}. status is {}", resourceInstanceId, error); } @@ -5784,29 +5999,26 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo if (getOverridedPropertyValuesRes.isRight()) { error = getOverridedPropertyValuesRes.right().value(); log.debug("Failed to retrieve property values of capability instance {}. Status is {}", curCapInstUid, error); - } - - log.debug("After getting all property values of capability instance {} of component istance {}. Status is {}", curCapInstUid, componentInstanceId, error); - Map<String, PropertyValueData> overridedPropertyValuesHM = new HashMap<>(); - List<ImmutablePair<PropertyValueData, GraphEdge>> overridedPropertyValues = getOverridedPropertyValuesRes.left().value(); - for (ImmutablePair<PropertyValueData, GraphEdge> curPropertyValuePair : overridedPropertyValues) { - PropertyValueData curPropertyValue = curPropertyValuePair.getLeft(); - String propertyValueUid = curPropertyValue.getUniqueId(); - log.debug("Before getting property related to property value {} of capability instance {} of component istance {}.", propertyValueUid, curCapInstUid, componentInstanceId); - Either<ImmutablePair<PropertyData, GraphEdge>, TitanOperationStatus> getPropertyDataRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.getByName(curPropertyValue.getLabel())), propertyValueUid, - GraphEdgeLabels.PROPERTY_IMPL, NodeTypeEnum.Property, PropertyData.class); - if (getPropertyDataRes.isRight()) { - error = getOverridedPropertyValuesRes.right().value(); - log.debug("Failed to retrieve property of property value {} Status is {}", propertyValueUid, error); - } - - if (log.isDebugEnabled()) { + } else { + log.debug("After getting all property values of capability instance {} of component istance {}. Status is {}", curCapInstUid, componentInstanceId, error); + Map<String, PropertyValueData> overridedPropertyValuesHM = new HashMap<>(); + List<ImmutablePair<PropertyValueData, GraphEdge>> overridedPropertyValues = getOverridedPropertyValuesRes.left().value(); + for (ImmutablePair<PropertyValueData, GraphEdge> curPropertyValuePair : overridedPropertyValues) { + PropertyValueData curPropertyValue = curPropertyValuePair.getLeft(); + String propertyValueUid = curPropertyValue.getUniqueId(); + log.debug("Before getting property related to property value {} of capability instance {} of component istance {}.", propertyValueUid, curCapInstUid, componentInstanceId); + Either<ImmutablePair<PropertyData, GraphEdge>, TitanOperationStatus> getPropertyDataRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.getByName(curPropertyValue.getLabel())), propertyValueUid, + GraphEdgeLabels.PROPERTY_IMPL, NodeTypeEnum.Property, PropertyData.class); + if (getPropertyDataRes.isRight()) { + error = getOverridedPropertyValuesRes.right().value(); + log.debug("Failed to retrieve property of property value {} Status is {}", propertyValueUid, error); + } log.debug("After getting property related to property value {} of capability instance {} of component istance {}. Status is {}", propertyValueUid, curCapInstUid, componentInstanceId, error); + PropertyData propertyData = getPropertyDataRes.left().value().getLeft(); + overridedPropertyValuesHM.put((String) propertyData.getUniqueId(), curPropertyValue); } - PropertyData propertyData = getPropertyDataRes.left().value().getLeft(); - overridedPropertyValuesHM.put((String) propertyData.getUniqueId(), curPropertyValue); + overridedCapabilitiesHM.put((String) curCapabilityPair.getRight().getProperties().get(GraphPropertiesDictionary.CAPABILITY_ID.getProperty()), overridedPropertyValuesHM); } - overridedCapabilitiesHM.put((String) curCapabilityPair.getRight().getProperties().get(GraphPropertiesDictionary.CAPABILITY_ID.getProperty()), overridedPropertyValuesHM); } } if (error == null && !overridedCapabilitiesHM.isEmpty()) { @@ -5838,7 +6050,6 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo @Override public Either<ComponentInstanceInput, StorageOperationStatus> updateInputValueInResourceInstance(ComponentInstanceInput input, String resourceInstanceId, boolean b) { - // TODO Auto-generated method stub return null; } @@ -5849,4 +6060,119 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo return result; } + @Override + public StorageOperationStatus updateCustomizationUUID(String componentInstanceId) { + Either<TitanVertex, TitanOperationStatus> vertexByProperty = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), componentInstanceId); + if (vertexByProperty.isRight()) { + log.debug("Failed to fetch component instance by id {} error {}", componentInstanceId, vertexByProperty.right().value()); + return DaoStatusConverter.convertTitanStatusToStorageStatus(vertexByProperty.right().value()); + } + UUID uuid = UUID.randomUUID(); + TitanVertex ciVertex = vertexByProperty.left().value(); + ciVertex.property(GraphPropertiesDictionary.CUSTOMIZATION_UUID.getProperty(), uuid.toString()); + + return StorageOperationStatus.OK; + } + + private Either<String, Boolean> handleGroupInstanceNameLogic(TitanVertex ciVertex, GroupInstance groupInstance, String componentInstanceId, String componentInstanceName, String groupName) { + + groupInstance.setGroupName(groupName); + + String logicalName = groupInstanceOperation.createGroupInstLogicalName(componentInstanceName, groupName); + + Boolean eitherValidation = validateGroupInstanceName(logicalName, groupInstance, true); + if (!eitherValidation) { + return Either.right(false); + } + // groupInstance.setName(logicalName); + return Either.left(logicalName); + } + + private Boolean validateGroupInstanceName(String groupInstanceName, GroupInstance groupInstance, boolean isCreate) { + + if (!ValidationUtils.validateStringNotEmpty(groupInstanceName)) { + return false; + } + groupInstance.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(groupInstanceName)); + if (!isCreate) { + if (!ValidationUtils.validateResourceInstanceNameLength(groupInstanceName)) { + return false; + } + if (!ValidationUtils.validateResourceInstanceName(groupInstanceName)) { + return false; + } + } + + return true; + + } + // Evg: need to be public for reuse code in migration + public Either<GroupInstance, StorageOperationStatus> createGroupInstance(TitanVertex ciVertex, GroupDefinition groupDefinition, ComponentInstance componentInstance) { + // create VFC instance on VF + GroupInstance groupInstance = null; + + boolean isCreateName = false; + List<GroupInstance> groupInstances = componentInstance.getGroupInstances(); + if (groupInstances != null && !groupInstances.isEmpty()) { + Optional<GroupInstance> op = groupInstances.stream().filter(p -> p.getGroupUid().equals(groupDefinition.getUniqueId())).findAny(); + if (op.isPresent()) { + groupInstance = op.get(); + + } + } + if (groupInstance == null) { + groupInstance = new GroupInstance(); + groupInstance.setGroupUid(groupDefinition.getUniqueId()); + + groupInstance.setArtifacts(groupDefinition.getArtifacts()); + Either<String, Boolean> handleNameLogic = handleGroupInstanceNameLogic(ciVertex, groupInstance, componentInstance.getUniqueId(), componentInstance.getNormalizedName(), groupDefinition.getName()); + if (handleNameLogic.isRight() && !handleNameLogic.right().value()) { + + if (handleNameLogic.isRight()) { + log.debug("failed to create logical name gor group instance {}", groupInstance.getName()); + return Either.right(StorageOperationStatus.INVALID_ID); + + } + } + isCreateName = true; + // groupInstance.setName(handleNameLogic.left().value()); + + } + + return groupInstanceOperation.createGroupInstance(ciVertex, componentInstance.getUniqueId(), groupInstance, isCreateName); + + } + + @Override + public Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) { + + log.debug("Going to update modification time of component instance {}. ", componentInstance.getName()); + Either<ComponentInstanceData, StorageOperationStatus> result = null; + try{ + ComponentInstanceData componentData = new ComponentInstanceData(componentInstance, componentInstance.getGroupInstances().size()); + componentData.getComponentInstDataDefinition().setModificationTime(modificationTime); + componentData.getComponentInstDataDefinition().setCustomizationUUID(UUID.randomUUID().toString()); + Either<ComponentInstanceData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(componentData, ComponentInstanceData.class); + if (updateNode.isRight()) { + log.error("Failed to update resource {}. status is {}", componentInstance.getUniqueId(), updateNode.right().value()); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value())); + }else{ + result = Either.left(updateNode.left().value()); + } + }catch(Exception e){ + log.error("Exception occured during update modification date of compomemt instance{}. The message is {}. ", componentInstance.getName(), e.getMessage(), e); + result = Either.right(StorageOperationStatus.GENERAL_ERROR); + }finally { + if(!inTransaction){ + if (result == null || result.isRight()) { + log.error("Going to execute rollback on graph."); + titanGenericDao.rollback(); + } else { + log.debug("Going to execute commit on graph."); + titanGenericDao.commit(); + } + } + } + return result; + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentOperation.java index b243c6ea4d..e06649bf77 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ComponentOperation.java @@ -22,23 +22,15 @@ package org.openecomp.sdc.be.model.operations.impl; import java.time.Duration; import java.time.Instant; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.Map.Entry; -import java.util.Optional; -import java.util.Set; -import java.util.UUID; import java.util.concurrent.LinkedBlockingQueue; import java.util.function.Function; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; +import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.ImmutableTriple; import org.apache.commons.lang3.tuple.Pair; @@ -66,6 +58,7 @@ import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.model.AdditionalInformationDefinition; import org.openecomp.sdc.be.model.ArtifactDefinition; @@ -80,8 +73,10 @@ import org.openecomp.sdc.be.model.GroupDefinition; import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition.PropertyNames; import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; import org.openecomp.sdc.be.model.RequirementDefinition; +import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; import org.openecomp.sdc.be.model.cache.ComponentCache; import org.openecomp.sdc.be.model.category.CategoryDefinition; @@ -93,6 +88,7 @@ import org.openecomp.sdc.be.model.operations.api.ICapabilityOperation; import org.openecomp.sdc.be.model.operations.api.IElementOperation; import org.openecomp.sdc.be.model.operations.api.IRequirementOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.api.ToscaDefinitionPathCalculator; import org.openecomp.sdc.be.resources.data.ArtifactData; import org.openecomp.sdc.be.resources.data.CapabilityData; import org.openecomp.sdc.be.resources.data.ComponentMetadataData; @@ -168,6 +164,9 @@ public abstract class ComponentOperation { @Autowired private ComponentCache componentCache; + @Autowired + private ToscaDefinitionPathCalculator toscaDefinitionPathCalculator; + private static Pattern uuidNewVersion = Pattern.compile("^\\d{1,}.1"); protected Gson prettyJson = new GsonBuilder().setPrettyPrinting().create(); @@ -193,18 +192,18 @@ public abstract class ComponentOperation { return Either.left(tagsToCreate); } - + protected StorageOperationStatus createTagNodesOnGraph(List<TagData> tagsToCreate) { StorageOperationStatus result = StorageOperationStatus.OK; // In order to avoid duplicate tags tagsToCreate = ImmutableSet.copyOf(tagsToCreate).asList(); if (tagsToCreate != null && false == tagsToCreate.isEmpty()) { for (TagData tagData : tagsToCreate) { - log.debug("Before creating tag {}", tagData); + log.debug("Before creating tag {}" , tagData); Either<TagData, TitanOperationStatus> createTagResult = titanGenericDao.createNode(tagData, TagData.class); if (createTagResult.isRight()) { TitanOperationStatus status = createTagResult.right().value(); - log.error("Cannot create {} in the graph. Status is {}", tagData, status); + log.error("Cannot create {} in the graph. status is {}", tagData, status); result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); } @@ -216,7 +215,7 @@ public abstract class ComponentOperation { public Either<Component, StorageOperationStatus> getLatestComponentByUuid(NodeTypeEnum nodeType, String uuid) { Either<Component, StorageOperationStatus> getComponentResult = null; - Either<ComponentMetadataData, StorageOperationStatus> latestComponentMetadataRes = getLatestComponentMetadataByUuid(nodeType, uuid); + Either<ComponentMetadataData, StorageOperationStatus> latestComponentMetadataRes = getLatestComponentMetadataByUuid(nodeType, uuid, false); if (latestComponentMetadataRes.isRight()) { getComponentResult = Either.right(latestComponentMetadataRes.right().value()); } @@ -234,7 +233,7 @@ public abstract class ComponentOperation { return getComponentResult; } - public Either<ComponentMetadataData, StorageOperationStatus> getLatestComponentMetadataByUuid(NodeTypeEnum nodeType, String uuid) { + public Either<ComponentMetadataData, StorageOperationStatus> getLatestComponentMetadataByUuid(NodeTypeEnum nodeType, String uuid, boolean inTransaction) { Either<ComponentMetadataData, StorageOperationStatus> getComponentResult = null; List<ComponentMetadataData> latestVersionList = null; @@ -243,24 +242,31 @@ public abstract class ComponentOperation { Map<String, Object> propertiesToMatch = new HashMap<String, Object>(); propertiesToMatch.put(GraphPropertiesDictionary.UUID.getProperty(), uuid); propertiesToMatch.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true); - - Either<List<ComponentMetadataData>, TitanOperationStatus> getComponentEither = titanGenericDao.getByCriteria(nodeType, propertiesToMatch, ComponentMetadataData.class); - if (getComponentEither.isRight()) { - log.debug("Couldn't fetch metadata for component with type {} and uuid {}, error: {}", nodeType, uuid, getComponentEither.right().value()); - getComponentResult = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentEither.right().value())); - - } - if (getComponentResult == null) { - latestVersionList = getComponentEither.left().value(); - if (latestVersionList.isEmpty()) { - log.debug("Component with type {} and uuid {} was not found", nodeType, uuid); - getComponentResult = Either.right(StorageOperationStatus.NOT_FOUND); + try{ + Either<List<ComponentMetadataData>, TitanOperationStatus> getComponentEither = titanGenericDao.getByCriteria(nodeType, propertiesToMatch, ComponentMetadataData.class); + if (getComponentEither.isRight()) { + log.debug("Couldn't fetch metadata for component with type {} and uuid {}, error: {}", nodeType, uuid, getComponentEither.right().value()); + getComponentResult = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentEither.right().value())); + + } + if (getComponentResult == null) { + latestVersionList = getComponentEither.left().value(); + if (latestVersionList.isEmpty()) { + log.debug("Component with type {} and uuid {} was not found", nodeType, uuid); + getComponentResult = Either.right(StorageOperationStatus.NOT_FOUND); + } + } + if (getComponentResult == null) { + 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(); + getComponentResult = Either.left(latestVersion); + } + } catch (Exception e){ + log.debug("Failed to get latest component metadata with type {} by uuid {}. ", nodeType.getName(), uuid, e); + }finally { + if (!inTransaction) { + titanGenericDao.commit(); } - } - if (getComponentResult == null) { - 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(); - getComponentResult = Either.left(latestVersion); } return getComponentResult; } @@ -284,32 +290,6 @@ public abstract class ComponentOperation { return Either.left(serviceData); } - // protected <T extends GraphNode> Either<T, StorageOperationStatus> - // getComponentByLabelAndId_tx(String uniqueId, NodeTypeEnum nodeType, - // Class<T> clazz) { - // - // Map<String, Object> propertiesToMatch = new HashMap<String, Object>(); - // propertiesToMatch.put(UniqueIdBuilder.getKeyByNodeType(nodeType), - // uniqueId); - // Either<List<T>, TitanOperationStatus> getResponse = - // titanGenericDao.getByCriteria_tx(nodeType, propertiesToMatch, clazz); - // if (getResponse.isRight()) { - // log.debug("Couldn't fetch component with type {} and unique id {}, error: - // {}", nodeType, uniqueId, getResponse.right().value()); - // return - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getResponse.right().value())); - // - // } - // List<T> serviceDataList = getResponse.left().value(); - // if (serviceDataList.isEmpty()) { - // log.debug("Component with type {} and unique id {} was not found", - // nodeType, uniqueId); - // return Either.right(StorageOperationStatus.NOT_FOUND); - // } - // T serviceData = serviceDataList.get(0); - // return Either.left(serviceData); - // } - /** * * @param component @@ -415,28 +395,28 @@ public abstract class ComponentOperation { Map<String, Object> props = new HashMap<String, Object>(); props.put(GraphPropertiesDictionary.STATE.getProperty(), componentData.getMetadataDataDefinition().getState()); Either<GraphRelation, TitanOperationStatus> result = titanGenericDao.createRelation(updater, componentData, GraphEdgeLabels.STATE, props); - log.debug("After associating user {} to component {}. Edge type is {}", updater, componentData.getUniqueId(), GraphEdgeLabels.STATE); + log.debug("After associating user {} to component {}. Edge type is {}" , updater, componentData.getUniqueId(), GraphEdgeLabels.STATE); if (result.isRight()) { return result.right().value(); } result = titanGenericDao.createRelation(updater, componentData, GraphEdgeLabels.LAST_MODIFIER, null); - log.debug("After associating user {} to component {}. Edge type is {}", updater, componentData.getUniqueId(), GraphEdgeLabels.LAST_MODIFIER); + log.debug("After associating user {} to component {}. Edge type is {}", updater, componentData.getUniqueId(), GraphEdgeLabels.LAST_MODIFIER); if (result.isRight()) { - log.error("Failed to associate user " + updater + " to component " + componentData.getUniqueId() + ". Edge type is " + GraphEdgeLabels.LAST_MODIFIER); + log.error("Failed to associate user {} to component {}. Edge type is {}", updater, componentData.getUniqueId(), GraphEdgeLabels.LAST_MODIFIER); return result.right().value(); } result = titanGenericDao.createRelation(userData, componentData, GraphEdgeLabels.CREATOR, null); - log.debug("After associating user {} to component {}. Edge type is {}", userData, componentData.getUniqueId(), GraphEdgeLabels.CREATOR); + log.debug("After associating user {} to component {}. Edge type is {}" , userData, componentData.getUniqueId(), GraphEdgeLabels.CREATOR); if (result.isRight()) { - log.error("Failed to associate user " + userData + " to component " + componentData.getUniqueId() + ". Edge type is " + GraphEdgeLabels.CREATOR); + log.error("Failed to associate user {} to component {}. Edge type is {}", userData, componentData.getUniqueId(), GraphEdgeLabels.CREATOR); return result.right().value(); } if (derivedResources != null) { for (ResourceMetadataData derivedResource : derivedResources) { - log.debug("After associating component {} to parent component {}. Egde type is {}", componentData.getUniqueId(), derivedResource.getUniqueId(), GraphEdgeLabels.DERIVED_FROM); + log.debug("After associating component {} to parent component {}. Edge type is {}" ,componentData.getUniqueId(), derivedResource.getUniqueId(), GraphEdgeLabels.DERIVED_FROM); result = titanGenericDao.createRelation(componentData, derivedResource, GraphEdgeLabels.DERIVED_FROM, null); if (result.isRight()) { log.error("Failed to associate user {} to component {}. Edge type is {}", userData, componentData.getUniqueId(), GraphEdgeLabels.CREATOR); @@ -464,11 +444,7 @@ public abstract class ComponentOperation { ArtifactDefinition artifactDefinition = entry.getValue(); Either<ArtifactDefinition, StorageOperationStatus> addArifactToResource = Either.left(artifactDefinition); - // if ((artifactDefinition.getUniqueId() != null) && - // !artifactDefinition.getUniqueId().isEmpty()) { addArifactToResource = artifactOperation.addArifactToComponent(artifactDefinition, (String) componentData.getUniqueId(), nodeType, false, true); - // } - if (addArifactToResource.isRight()) { return addArifactToResource.right().value(); } @@ -497,68 +473,68 @@ public abstract class ComponentOperation { for (ResourceMetadataData resourceData : resourceList) { builder.append(resourceData.getUniqueId() + "|"); } - log.debug("resources with property name: {} exists in graph. Found {}", name, builder.toString()); + log.debug("resources with property name:{} exists in graph. found {}",name, builder.toString()); } return Either.left(false); } else { - log.debug("resources with property name:" + name + " does not exists in graph"); + log.debug("resources with property name:{} does not exists in graph", name); return Either.left(true); } } - - protected Either<Boolean, StorageOperationStatus> validateToscaResourceNameUniqueness(String name, TitanGenericDao titanGenericDao) { + + protected Either<Boolean, StorageOperationStatus> validateServiceNameUniqueness(String name, TitanGenericDao titanGenericDao) { Map<String, Object> properties = new HashMap<>(); + String normalizedName = ValidationUtils.normaliseComponentName(name); + properties.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), normalizedName); - properties.put(GraphPropertiesDictionary.TOSCA_RESOURCE_NAME.getProperty(), name); - - Either<List<ResourceMetadataData>, TitanOperationStatus> resources = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, properties, ResourceMetadataData.class); - 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())); + Either<List<ServiceMetadataData>, TitanOperationStatus> services = titanGenericDao.getByCriteria(NodeTypeEnum.Service, properties, ServiceMetadataData.class); + if (services.isRight() && services.right().value() != TitanOperationStatus.NOT_FOUND) { + log.debug("failed to get services from graph with property name: {}" , name); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(services.right().value())); } - List<ResourceMetadataData> resourceList = (resources.isLeft() ? resources.left().value() : null); - if (resourceList != null && resourceList.size() > 0) { + List<ServiceMetadataData> serviceList = (services.isLeft() ? services.left().value() : null); + if (serviceList != null && serviceList.size() > 0) { if (log.isDebugEnabled()) { StringBuilder builder = new StringBuilder(); - for (ResourceMetadataData resourceData : resourceList) { - builder.append(resourceData.getUniqueId() + "|"); + for (ServiceMetadataData serviceData : serviceList) { + builder.append(serviceData.getUniqueId() + "|"); } - log.debug("resources with property name:" + name + " exists in graph. found " + builder.toString()); + log.debug("Service with property name:{} exists in graph. found {}" , name, builder.toString()); } + return Either.left(false); } else { - log.debug("resources with property name: {} dows not exists in the graph", name); + log.debug("Service with property name:{} does not exists in graph", name); return Either.left(true); } - } - - protected Either<Boolean, StorageOperationStatus> validateServiceNameUniqueness(String name, TitanGenericDao titanGenericDao) { + + protected Either<Boolean, StorageOperationStatus> validateToscaResourceNameUniqueness(String name, TitanGenericDao titanGenericDao) { Map<String, Object> properties = new HashMap<>(); - String normalizedName = ValidationUtils.normaliseComponentName(name); - properties.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), normalizedName); - Either<List<ServiceMetadataData>, TitanOperationStatus> services = titanGenericDao.getByCriteria(NodeTypeEnum.Service, properties, ServiceMetadataData.class); - if (services.isRight() && services.right().value() != TitanOperationStatus.NOT_FOUND) { - log.debug("failed to get services from graph with property name: {}", name); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(services.right().value())); + properties.put(GraphPropertiesDictionary.TOSCA_RESOURCE_NAME.getProperty(), name); + + Either<List<ResourceMetadataData>, TitanOperationStatus> resources = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, properties, ResourceMetadataData.class); + 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<ServiceMetadataData> serviceList = (services.isLeft() ? services.left().value() : null); - if (serviceList != null && serviceList.size() > 0) { + List<ResourceMetadataData> resourceList = (resources.isLeft() ? resources.left().value() : null); + if (resourceList != null && resourceList.size() > 0) { if (log.isDebugEnabled()) { StringBuilder builder = new StringBuilder(); - for (ServiceMetadataData serviceData : serviceList) { - builder.append(serviceData.getUniqueId() + "|"); + for (ResourceMetadataData resourceData : resourceList) { + builder.append(resourceData.getUniqueId() + "|"); } - log.debug("Service with property name: {} exists in graph. Found {}", name, builder.toString()); + log.debug("resources with property name:{} exists in graph. found {}" , name, builder.toString()); } - return Either.left(false); } else { - log.debug("Service with property name: {} dows not exists in graph", name); + log.debug("resources with property name:{} does not exists in graph", name); return Either.left(true); } + } protected Either<Boolean, StorageOperationStatus> validateComponentNameUniqueness(String name, TitanGenericDao titanGenericDao, NodeTypeEnum type) { @@ -568,7 +544,7 @@ public abstract class ComponentOperation { Either<List<ComponentMetadataData>, TitanOperationStatus> components = titanGenericDao.getByCriteria(type, properties, ComponentMetadataData.class); if (components.isRight() && components.right().value() != TitanOperationStatus.NOT_FOUND) { - log.debug("failed to get components from graph with property name: {}", name); + log.debug("failed to get components from graph with property name: {}" , name); return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(components.right().value())); } List<ComponentMetadataData> componentList = (components.isLeft() ? components.left().value() : null); @@ -578,58 +554,16 @@ public abstract class ComponentOperation { for (ComponentMetadataData componentData : componentList) { builder.append(componentData.getUniqueId() + "|"); } - log.debug("Component with property name: {} exists in graph. Found {}", name, builder.toString()); + log.debug("Component with property name:{} exists in graph. found {}" , name, builder.toString()); } return Either.left(false); } else { - log.debug("Component with property name: {} does not exists in graph", name); + log.debug("Component with property name:{} does not exists in graph", name); return Either.left(true); } } - // protected TitanOperationStatus setComponentCategoryFromGraph(String - // uniqueId, Component component, TitanGenericDao titanGenericDao, - // NodeTypeEnum categoryType) { - // - // Either<List<ImmutablePair<CategoryData, GraphEdge>>, - // TitanOperationStatus> parentNode = - // titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), - // uniqueId, GraphEdgeLabels.CATEGORY, categoryType, - // CategoryData.class); - // if (parentNode.isRight()) { - // return parentNode.right().value(); - // } - // - // List<ImmutablePair<CategoryData, GraphEdge>> listValue = - // parentNode.left().value(); - // log.debug("Result after looking for category nodes pointed by resource " - // + uniqueId + ". status is " + listValue); - // if (listValue.size() > 1) { - // log.error("Multiple edges foud between resource " + uniqueId + " to - // category nodes."); - // } - // ImmutablePair<CategoryData, GraphEdge> value = listValue.get(0); - // log.debug("Found parent node {}", value); - // - // CategoryData categoryData = value.getKey(); - // String categoryStr = null; - // if - // (NodeTypeEnum.ResourceCategory.name().equalsIgnoreCase(categoryData.getLabel())) - // { - // StringBuilder sb = new StringBuilder(); - // sb.append(((ResourceCategoryData) categoryData).getCategoryName()); - // sb.append("/"); - // sb.append(categoryData.getName()); - // categoryStr = sb.toString(); - // } else { - // categoryStr = categoryData.getName(); - // } - // - // component.setCategory(categoryStr); - // return TitanOperationStatus.OK; - // } - protected StorageOperationStatus setArtifactFromGraph(String uniqueId, Component component, NodeTypeEnum type, IArtifactOperation artifactOperation) { StorageOperationStatus result = StorageOperationStatus.OK; Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = artifactOperation.getArtifacts(uniqueId, type, true); @@ -686,15 +620,16 @@ public abstract class ComponentOperation { return component; } - private <T, S extends ComponentMetadataData> Either<List<T>, StorageOperationStatus> collectComponents(TitanGraph graph, NodeTypeEnum neededType, String categoryUid, NodeTypeEnum categoryType, Class<S> clazz) { + private <T, S extends ComponentMetadataData> Either<List<T>, StorageOperationStatus> collectComponents(TitanGraph graph, NodeTypeEnum neededType, String categoryUid, NodeTypeEnum categoryType, Class<S> clazz, ResourceTypeEnum resourceType) { List<T> components = new ArrayList<>(); Either<List<ImmutablePair<S, GraphEdge>>, TitanOperationStatus> parentNodes = titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(categoryType), categoryUid, GraphEdgeLabels.CATEGORY, neededType, clazz); if (parentNodes.isLeft()) { for (ImmutablePair<S, GraphEdge> component : parentNodes.left().value()) { ComponentMetadataDataDefinition componentData = component.getLeft().getMetadataDataDefinition(); Boolean isHighest = componentData.isHighestVersion(); - Boolean isComplex = neededType == NodeTypeEnum.Resource ? ResourceTypeEnum.VF.equals(((ResourceMetadataDataDefinition) componentData).getResourceType()) : true; - if (isHighest && isComplex) { + boolean isMatchingResourceType = isMatchingByResourceType(neededType, resourceType, componentData); + + if (isHighest && isMatchingResourceType) { Either<T, StorageOperationStatus> result = getLightComponent(componentData.getUniqueId(), true); if (result.isRight()) { return Either.right(result.right().value()); @@ -706,15 +641,31 @@ public abstract class ComponentOperation { return Either.left(components); } + private boolean isMatchingByResourceType(NodeTypeEnum componentType, ResourceTypeEnum resourceType, + ComponentMetadataDataDefinition componentData) { + + boolean isMatching; + if (componentType == NodeTypeEnum.Resource) { + if (resourceType == null) { + isMatching = true; + } else { + isMatching = resourceType == ((ResourceMetadataDataDefinition)componentData).getResourceType(); + } + } else { + isMatching = true; + } + return isMatching; + } + protected <T, S extends ComponentMetadataData> Either<List<T>, StorageOperationStatus> fetchByCategoryOrSubCategoryUid(String categoryUid, NodeTypeEnum categoryType, String categoryLabel, NodeTypeEnum neededType, boolean inTransaction, - Class<S> clazz) { + Class<S> clazz, ResourceTypeEnum resourceType) { try { Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph(); if (graph.isRight()) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value())); } - return collectComponents(graph.left().value(), neededType, categoryUid, categoryType, clazz); + return collectComponents(graph.left().value(), neededType, categoryUid, categoryType, clazz, resourceType); } finally { if (false == inTransaction) { @@ -724,12 +675,12 @@ public abstract class ComponentOperation { } protected <T, S extends ComponentMetadataData> Either<List<T>, StorageOperationStatus> fetchByCategoryOrSubCategoryName(String categoryName, NodeTypeEnum categoryType, String categoryLabel, NodeTypeEnum neededType, boolean inTransaction, - Class<S> clazz) { + Class<S> clazz, ResourceTypeEnum resourceType) { List<T> components = new ArrayList<>(); try { Class categoryClazz = categoryType == NodeTypeEnum.ServiceNewCategory ? CategoryData.class : SubCategoryData.class; Map<String, Object> props = new HashMap<String, Object>(); - props.put(GraphPropertiesDictionary.NAME.getProperty(), categoryName); + props.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), ValidationUtils.normalizeCategoryName4Uniqueness(categoryName)); Either<List<GraphNode>, TitanOperationStatus> getCategory = titanGenericDao.getByCriteria(categoryType, props, categoryClazz); if (getCategory.isRight()) { return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND); @@ -740,7 +691,7 @@ public abstract class ComponentOperation { } for (GraphNode category : getCategory.left().value()) { - Either<List<T>, StorageOperationStatus> result = collectComponents(graph.left().value(), neededType, (String) category.getUniqueId(), categoryType, clazz); + Either<List<T>, StorageOperationStatus> result = collectComponents(graph.left().value(), neededType, (String) category.getUniqueId(), categoryType, clazz, resourceType); if (result.isRight()) { return result; } @@ -784,7 +735,6 @@ public abstract class ComponentOperation { } else { // for Designer retrieve specific user String key = UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User); - // users = graph.left().value().getVertices(key, userId); users = graph.left().value().query().has(key, userId).vertices(); } Iterator<TitanVertex> userIterator = users.iterator(); @@ -852,7 +802,7 @@ public abstract class ComponentOperation { String stateStr = edge.value(GraphEdgePropertiesDictionary.STATE.getProperty()); LifecycleStateEnum state = LifecycleStateEnum.findState(stateStr); if (state == null) { - log.debug("not supported STATE for element {}", stateStr); + log.debug("not supported STATE for element {}" , stateStr); continue; } if (lifecycleStates != null && lifecycleStates.contains(state)) { @@ -902,7 +852,7 @@ public abstract class ComponentOperation { if (id != null) { Either<T, StorageOperationStatus> component = getLightComponent(id, inTransaction); if (component.isRight()) { - log.debug("Failed to get component for id = {} error: {} skip resource", id, component.right().value()); + log.debug("Failed to get component for id = {} error : {} skip resource", id, component.right().value()); } else { components.add(component.left().value()); } @@ -929,8 +879,11 @@ public abstract class ComponentOperation { } private Either<ArtifactData, StorageOperationStatus> generateAndUpdateToscaFileName(String componentType, String componentName, String componentId, NodeTypeEnum type, ArtifactDefinition artifactInfo) { - Map<String, Object> getConfig = (Map<String, Object>) ConfigurationManager.getConfigurationManager().getConfiguration().getToscaArtifacts().entrySet().stream().filter(p -> p.getKey().equalsIgnoreCase(artifactInfo.getArtifactLabel())) - .findAny().get().getValue(); + Map<String, Object> getConfig = (Map<String, Object>) ConfigurationManager.getConfigurationManager().getConfiguration().getToscaArtifacts().entrySet().stream() + .filter(p -> p.getKey().equalsIgnoreCase(artifactInfo.getArtifactLabel())) + .findAny() + .get() + .getValue(); artifactInfo.setArtifactName(componentType + "-" + componentName + getConfig.get("artifactName")); return artifactOperation.updateToscaArtifactNameOnGraph(artifactInfo, artifactInfo.getUniqueId(), type, componentId); } @@ -961,7 +914,7 @@ public abstract class ComponentOperation { Either<CategoryData, StorageOperationStatus> categoryResult = elementOperation.getNewCategoryData(newCategory.getName(), NodeTypeEnum.ServiceNewCategory, CategoryData.class); if (categoryResult.isRight()) { StorageOperationStatus status = categoryResult.right().value(); - log.error("Cannot find category " + newCategory.getName() + " in the graph. status is " + status); + log.error("Cannot find category {} in the graph. status is {}", newCategory.getName(), status); return status; } @@ -1008,9 +961,6 @@ public abstract class ComponentOperation { public abstract <T> Either<T, StorageOperationStatus> getComponent(String id, ComponentParametersView componentParametersView, boolean inTrasnaction); - // public abstract <T> Either<T, StorageOperationStatus> - // getComponent_tx(String id, boolean inTransaction); - protected abstract <T> Either<T, StorageOperationStatus> getComponentByNameAndVersion(String name, String version, Map<String, Object> additionalParams, boolean inTransaction); public abstract <T> Either<T, StorageOperationStatus> getLightComponent(String id, boolean inTransaction); @@ -1129,7 +1079,7 @@ public abstract class ComponentOperation { log.debug("No nodes in graph for criteria : from type = {} and properties = {}", type, props); return Either.left(result); } catch (Exception e) { - log.debug("Failed get by criteria for type = {} and properties = {}. {}", type, props, e); + log.debug("Failed get by criteria for type = {} and properties = {}", type, props, e); return Either.right(TitanGraphClient.handleTitanException(e)); } } @@ -1190,7 +1140,7 @@ public abstract class ComponentOperation { // inTransaction); Either<T, StorageOperationStatus> component = getLightComponent((String) componentData.getUniqueId(), inTransaction); if (component.isRight()) { - log.debug("Failed to get component for id = {} error : {} skip resource", componentData.getUniqueId(), component.right().value()); + log.debug("Failed to get component for id = {} error : {} skip resource", componentData.getUniqueId(), component.right().value()); // return Either.right(service.right().value()); } else { result.add(component.left().value()); @@ -1304,6 +1254,7 @@ public abstract class ComponentOperation { for (ProductMetadataData data : componentsP) { versionMap.put(data.getMetadataDataDefinition().getVersion(), (String) data.getUniqueId()); } + break; default: break; } @@ -1334,7 +1285,7 @@ public abstract class ComponentOperation { return DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus); } - log.trace("After adding additional information to component {}. Result is {}", componentId, status.left().value()); + log.trace("After adding additional information to component {}. Result is {}" , componentId ,status.left().value()); return StorageOperationStatus.OK; @@ -1619,7 +1570,7 @@ public abstract class ComponentOperation { // } valueUid = valuedProperty.getValueUniqueUid(); - log.trace("Found value {} under resource instance whice override the default value {}", value, defaultValue); + log.trace("Found value {} under resource instance which override the default value {}" , value, defaultValue); } ComponentInstanceProperty resourceInstanceProperty = new ComponentInstanceProperty(propertyDefinition, value, valueUid); @@ -1681,7 +1632,7 @@ public abstract class ComponentOperation { StorageOperationStatus updateComponent; if (updateNode.isRight()) { - log.debug("Failed to update component {}. Status is {}", componentMetaData.getUniqueId(), updateNode.right().value()); + log.debug("Failed to update component {}. status is {}", componentMetaData.getUniqueId(), updateNode.right().value()); updateComponent = DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value()); result = Either.right(updateComponent); return result; @@ -1706,14 +1657,13 @@ public abstract class ComponentOperation { } private Either<List<RequirementDefinition>, TitanOperationStatus> convertReqDataListToReqDefList(ComponentInstance componentInstance, List<ImmutablePair<RequirementData, GraphEdge>> requirementData) { - ConvertDataToDef<RequirementDefinition, RequirementData> convertor = (data, edge) -> convertReqDataToReqDef(data, edge); + ConvertDataToDef<RequirementDefinition, RequirementData> convertor = (instance, data, edge) -> convertReqDataToReqDef(instance, data, edge); AddOwnerData<RequirementDefinition> dataAdder = (reqDef, compInstance) -> addOwnerDataReq(reqDef, compInstance); - return convertDataToDefinition(componentInstance, requirementData, convertor, dataAdder); } private Either<List<CapabilityDefinition>, TitanOperationStatus> convertCapDataListToCapDefList(ComponentInstance componentInstance, List<ImmutablePair<CapabilityData, GraphEdge>> capabilityData) { - ConvertDataToDef<CapabilityDefinition, CapabilityData> convertor = (data, edge) -> convertCapDataToCapDef(data, edge); + ConvertDataToDef<CapabilityDefinition, CapabilityData> convertor = (instance, data, edge) -> convertCapDataToCapDef(instance, data, edge); AddOwnerData<CapabilityDefinition> dataAdder = (capDef, compInstance) -> addOwnerDataCap(capDef, compInstance); Either<List<CapabilityDefinition>, TitanOperationStatus> convertationResult = convertDataToDefinition(componentInstance, capabilityData, convertor, dataAdder); if (convertationResult.isLeft()) { @@ -1722,7 +1672,7 @@ public abstract class ComponentOperation { return convertationResult; } - private Either<CapabilityDefinition, TitanOperationStatus> convertCapDataToCapDef(CapabilityData data, GraphEdge edge) { + private Either<CapabilityDefinition, TitanOperationStatus> convertCapDataToCapDef(ComponentInstance componentInstance, CapabilityData data, GraphEdge edge) { Either<CapabilityDefinition, TitanOperationStatus> eitherDef = capabilityOperation.getCapabilityByCapabilityData(data); if (eitherDef.isLeft()) { @@ -1735,6 +1685,7 @@ public abstract class ComponentOperation { capabilityOperation.getCapabilitySourcesList(source, sourcesList); capDef.setName(name); capDef.setCapabilitySources(sourcesList); + capDef.setPath(toscaDefinitionPathCalculator.calculateToscaDefinitionPath(componentInstance, edge)); String requiredOccurrences = (String) properties.get(GraphEdgePropertiesDictionary.REQUIRED_OCCURRENCES.getProperty()); if (requiredOccurrences != null) { @@ -1751,7 +1702,7 @@ public abstract class ComponentOperation { return eitherDef; } - private Either<RequirementDefinition, TitanOperationStatus> convertReqDataToReqDef(RequirementData data, GraphEdge edge) { + private Either<RequirementDefinition, TitanOperationStatus> convertReqDataToReqDef(ComponentInstance componentInstance, RequirementData data, GraphEdge edge) { Either<RequirementDefinition, TitanOperationStatus> eitherDef = requirementOperation.getRequirement(data.getUniqueId()); if (eitherDef.isLeft()) { @@ -1764,6 +1715,7 @@ public abstract class ComponentOperation { if (requiredOccurrences != null) { requirementDef.setMinOccurrences(requiredOccurrences); } + requirementDef.setPath(toscaDefinitionPathCalculator.calculateToscaDefinitionPath(componentInstance, edge)); String leftOccurrences = (String) properties.get(GraphEdgePropertiesDictionary.LEFT_OCCURRENCES.getProperty()); if (leftOccurrences != null) { requirementDef.setMaxOccurrences(leftOccurrences); @@ -1777,7 +1729,7 @@ public abstract class ComponentOperation { private <Def, Data> Either<List<Def>, TitanOperationStatus> convertDataToDefinition(ComponentInstance componentInstance, List<ImmutablePair<Data, GraphEdge>> requirementData, ConvertDataToDef<Def, Data> convertor, AddOwnerData<Def> dataAdder) { Either<List<Def>, TitanOperationStatus> eitherResult; // Convert Data To Definition - Stream<Either<Def, TitanOperationStatus>> reqDefStream = requirementData.stream().map(e -> convertor.convert(e.left, e.right)); + Stream<Either<Def, TitanOperationStatus>> reqDefStream = requirementData.stream().map(e -> convertor.convert(componentInstance, e.left, e.right)); // Collect But Stop After First Error List<Either<Def, TitanOperationStatus>> filteredReqDefList = StreamUtils.takeWhilePlusOne(reqDefStream, p -> p.isLeft()).collect(Collectors.toList()); @@ -1796,7 +1748,7 @@ public abstract class ComponentOperation { } interface ConvertDataToDef<Def, Data> { - Either<Def, TitanOperationStatus> convert(Data d, GraphEdge edge); + Either<Def, TitanOperationStatus> convert(ComponentInstance compInstance, Data d, GraphEdge edge); } interface AddOwnerData<Def> { @@ -1979,7 +1931,7 @@ public abstract class ComponentOperation { NodeTypeEnum label = NodeTypeEnum.getByName(metadataData.getLabel()); switch (label) { case Resource: - pair = new ImmutablePair<String, String>(metadataData.getMetadataDataDefinition().getName(), ((ResourceMetadataDataDefinition) metadataData.getMetadataDataDefinition()).getResourceType().getValue()); + pair = new ImmutablePair<String, String>(metadataData.getMetadataDataDefinition().getName(), ((ResourceMetadataDataDefinition) metadataData.getMetadataDataDefinition()).getResourceType().name()); break; default: pair = new ImmutablePair<String, String>(metadataData.getMetadataDataDefinition().getName(), metadataData.getLabel()); @@ -2004,13 +1956,14 @@ public abstract class ComponentOperation { switch (internalComponentType.toLowerCase()) { case "vf": properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VF.name())); - properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VL.name())); +// properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VL.name())); // hasNotPpropertiesToMatch.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), // ResourceTypeEnum.VF.name()); break; case "service": properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VFC.name())); - properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VL.name())); + properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VFCMT.name())); +// properties.add(new ImmutableTriple<>(QueryType.HAS_NOT, GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VL.name())); // hasNotPpropertiesToMatch.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), // ResourceTypeEnum.VFC.name()); break; @@ -2104,11 +2057,7 @@ public abstract class ComponentOperation { manager.addJob(new Job() { @Override public Either<Component, StorageOperationStatus> doWork() { - // long start = System.currentTimeMillis(); Either<Component, StorageOperationStatus> component = getComponent(componentUid, componentParametersView, false); - // long stop = System.currentTimeMillis(); - // log.info("********** Time calculation in ms: - // getComponent single {}", (stop-start)); return component; } }); @@ -2205,10 +2154,7 @@ public abstract class ComponentOperation { } <T> Either<T, StorageOperationStatus> getLightComponent(String id, NodeTypeEnum nodeType, boolean inTransaction) { - Either<Component, StorageOperationStatus> metadataComponent = getMetadataComponent(id, nodeType, inTransaction); - if (metadataComponent.isRight()) { - } T component = null; try { log.debug("Starting to build light component of type {}, id {}", nodeType, id); @@ -2333,7 +2279,7 @@ public abstract class ComponentOperation { return Either.left(instanceCounter); } - protected TitanOperationStatus setComponentInstancesPropertiesFromGraph(String uniqueId, Component component) { + protected TitanOperationStatus setComponentInstancesPropertiesFromGraph(Component component) { List<ComponentInstance> resourceInstances = component.getComponentInstances(); @@ -2390,7 +2336,7 @@ public abstract class ComponentOperation { return TitanOperationStatus.OK; } - + protected TitanOperationStatus setComponentInstancesInputsFromGraph(String uniqueId, Component component) { Map<String, List<ComponentInstanceInput>> resourceInstancesInputs = new HashMap<>(); @@ -2546,8 +2492,7 @@ public abstract class ComponentOperation { Instant start = Instant.now(); Either<List<ComponentInstance>, StorageOperationStatus> resourceInstancesOfService = componentInstanceOperation.getAllComponentInstancesMetadataOnly(componentId, nodeType); Instant end = Instant.now(); - log.debug("TOTAL TIME BL GET INSTANCES: {}", Duration.between(start, end)); // prints - // PT1M3.553S + log.debug("TOTAL TIME BL GET INSTANCES: {}", Duration.between(start, end)); return resourceInstancesOfService; } @@ -2648,12 +2593,7 @@ public abstract class ComponentOperation { break; } if (clazz1 != null) { - // long startGetAllVersions = - // System.currentTimeMillis(); Either<Map<String, String>, TitanOperationStatus> versionList = getVersionList(componentTypeEnum.getNodeType(), cachedComponent.getVersion(), cachedComponent.getUUID(), cachedComponent.getSystemName(), clazz1); - // log.debug("Fetch all versions for component {} took - // {} ms", cachedComponent.getUniqueId(), - // System.currentTimeMillis() - startGetAllVersions); if (versionList.isRight()) { return Either.right(ActionStatus.GENERAL_ERROR); } @@ -2732,7 +2672,7 @@ public abstract class ComponentOperation { if (counterStatus.isRight()) { - log.error("Cannot find componentInstanceCounter for component {} in the graph. Status is {}", componentData.getUniqueId(), counterStatus); + log.error("Cannot find componentInstanceCounter for component {} in the graph. status is {}", componentData.getUniqueId(), counterStatus); // result = sendError(status, // StorageOperationStatus.USER_NOT_FOUND); return result; @@ -2742,7 +2682,7 @@ public abstract class ComponentOperation { String modifierUserId = component.getLastUpdaterUserId(); if (modifierUserId == null || modifierUserId.isEmpty()) { - log.error("userId is missing in the request."); + log.error("UserId is missing in the request."); result = Either.right(StorageOperationStatus.BAD_REQUEST); return result; } @@ -2750,7 +2690,7 @@ public abstract class ComponentOperation { 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); // result = sendError(status, // StorageOperationStatus.USER_NOT_FOUND); return result; @@ -2780,7 +2720,7 @@ public abstract class ComponentOperation { } else { log.debug("Going to update the last modifier user of the resource from {} to {}", currentModifier, modifierUserId); StorageOperationStatus status = moveLastModifierEdge(component, componentData, modifierUserData, type); - log.debug("Finish to update the last modifier user of the resource from {} to {}. Status is {}", currentModifier, modifierUserId, status); + log.debug("Finish to update the last modifier user of the resource from {} to {}. status is {}", currentModifier, modifierUserId, status); if (status != StorageOperationStatus.OK) { result = Either.right(status); return result; @@ -2811,7 +2751,7 @@ public abstract class ComponentOperation { Either<TagData, TitanOperationStatus> createTagResult = titanGenericDao.createNode(tagData, TagData.class); if (createTagResult.isRight()) { TitanOperationStatus status = createTagResult.right().value(); - log.error("Cannot find tag {} in the graph. Status is {}", tagData, status); + log.error("Cannot find tag {} in the graph. status is {}", tagData, status); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); return result; } @@ -2823,7 +2763,7 @@ public abstract class ComponentOperation { Either<ComponentMetadataData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(componentData, ComponentMetadataData.class); if (updateNode.isRight()) { - log.error("Failed to update resource {}. Status is {}", component.getUniqueId(), updateNode.right().value()); + log.error("Failed to update resource {}. status is {}", component.getUniqueId(), updateNode.right().value()); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value())); return result; } @@ -2834,7 +2774,8 @@ public abstract class ComponentOperation { // DE230195 in case resource name changed update TOSCA artifacts // file names accordingly String newSystemName = updatedResourceData.getMetadataDataDefinition().getSystemName(); - if (newSystemName != null && !newSystemName.equals(currentComponent.getSystemName())) { + String prevSystemName = currentComponent.getSystemName(); + if (newSystemName != null && !newSystemName.equals(prevSystemName)) { Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts(); if (toscaArtifacts != null) { for (Entry<String, ArtifactDefinition> artifact : toscaArtifacts.entrySet()) { @@ -2846,8 +2787,15 @@ public abstract class ComponentOperation { } } } - + //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 == component.getComponentType()) { + //update method logs success/error and returns boolean (true if nothing fails) + updateServiceNameInVLIsNetworkRolePropertyValues(component, prevSystemName, newSystemName); + } } + if (component.getComponentType().equals(ComponentTypeEnum.RESOURCE)) { updateDerived(component, currentComponent, componentData, component.getClass()); @@ -2863,13 +2811,7 @@ public abstract class ComponentOperation { T updatedResourceValue = updatedResource.left().value(); result = Either.left(updatedResourceValue); - if (log.isDebugEnabled()) { - // String json = prettyJson.toJson(result.left().value()); - // log.debug("Resource retrieved after update is {}", json); - } - return result; - } finally { if (false == inTransaction) { @@ -2883,4 +2825,139 @@ public abstract class ComponentOperation { } } } + + private boolean updateServiceNameInVLIsNetworkRolePropertyValues (Component component, String prevSystemName, String newSystemName) { + // find VLIs in service + boolean res = true; + if(null == component.getComponentInstances() || component.getComponentInstances().isEmpty()){ + return res; + } + + List <ComponentInstance> vlInstances = + component.getComponentInstances().stream() + .filter(p -> OriginTypeEnum.VL == p.getOriginType()) + .collect(Collectors.toList()); + if (!vlInstances.isEmpty()) { + for (ComponentInstance vlInstance : vlInstances){ + // find network_role property + Optional <ComponentInstanceProperty> networkRoleProperty = component.getComponentInstancesProperties().get(vlInstance.getUniqueId()).stream() + .filter(p -> PropertyNames.NETWORK_ROLE.getPropertyName().equalsIgnoreCase(p.getName())) + .findAny(); + res = res && updateNetworkRolePropertyValue(prevSystemName, newSystemName, vlInstance, networkRoleProperty); + } + } + return res; + } + + private boolean updateNetworkRolePropertyValue(String prevSystemName, String newSystemName, ComponentInstance vlInstance, Optional<ComponentInstanceProperty> networkRoleProperty) { + if (networkRoleProperty.isPresent() && !StringUtils.isEmpty(networkRoleProperty.get().getValue()) ) { + ComponentInstanceProperty property = networkRoleProperty.get(); + String updatedValue = property.getValue().replaceFirst(prevSystemName, newSystemName); + property.setValue(updatedValue); + StorageOperationStatus updateCustomizationUUID; + //disregard property value rule + property.setRules(null); + Either<ComponentInstanceProperty, StorageOperationStatus> result = componentInstanceOperation.updatePropertyValueInResourceInstance(property, vlInstance.getUniqueId(), true); + if (result.isLeft()) { + log.debug("Property value {} was updated on graph.", property.getValueUniqueUid()); + updateCustomizationUUID = componentInstanceOperation.updateCustomizationUUID(vlInstance.getUniqueId()); + } else { + updateCustomizationUUID = StorageOperationStatus.EXEUCTION_FAILED; + log.debug("Failed to update property value: {} in resource instance {}", updatedValue, vlInstance.getUniqueId()); + } + return result.isLeft() && StorageOperationStatus.OK == updateCustomizationUUID; + } + return true; + } + + public Either<ComponentMetadataData, StorageOperationStatus> updateComponentLastUpdateDateAndLastModifierOnGraph( Component component, User modifier, NodeTypeEnum componentType, boolean inTransaction) { + + log.debug("Going to update last update date and last modifier info of component {}. ", component.getName()); + Either<ComponentMetadataData, StorageOperationStatus> result = null; + try{ + String modifierUserId = modifier.getUserId(); + ComponentMetadataData componentData = getMetaDataFromComponent(component); + String currentUser = component.getLastUpdaterUserId(); + UserData modifierUserData = new UserData(); + modifierUserData.setUserId(modifierUserId); + if (currentUser.equals(modifierUserId)) { + log.debug("Graph last modifier edge should not be changed since the modifier is the same as the last modifier."); + } else { + log.debug("Going to update the last modifier user of the component from {} to {}", currentUser, modifierUserId); + StorageOperationStatus status = moveLastModifierEdge(component, componentData, modifierUserData, componentType); + log.debug("Finish to update the last modifier user of the resource from {} to {}. status is {}", currentUser, modifierUserId, status); + if (status != StorageOperationStatus.OK) { + result = Either.right(status); + } + } + Either<ComponentMetadataData, TitanOperationStatus> updateNode = null; + if(result == null){ + log.debug("Going to update the component {} with new last update date. ", component.getName()); + componentData.getMetadataDataDefinition().setLastUpdateDate(System.currentTimeMillis()); + updateNode = titanGenericDao.updateNode(componentData, ComponentMetadataData.class); + if (updateNode.isRight()) { + log.error("Failed to update component {}. status is {}", component.getUniqueId(), updateNode.right().value()); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value())); + } + } + if(result == null){ + result = Either.left(updateNode.left().value()); + } + }catch(Exception e){ + log.error("Exception occured during update last update date and last modifier info of component {}. The message is {}. ", component.getName(), e.getMessage()); + }finally { + if(!inTransaction){ + if (result == null || result.isRight()) { + log.error("Going to execute rollback on graph."); + titanGenericDao.rollback(); + } else { + log.debug("Going to execute commit on graph."); + titanGenericDao.commit(); + } + } + } + return result; + } + /** + * updates component lastUpdateDate on graph node + * @param component + * @param componentType + * @param lastUpdateDate + * @param inTransaction + * @return + */ + public Either<ComponentMetadataData, StorageOperationStatus> updateComponentLastUpdateDateOnGraph( Component component, NodeTypeEnum componentType, Long lastUpdateDate, boolean inTransaction) { + + log.debug("Going to update last update date of component {}. ", component.getName()); + Either<ComponentMetadataData, StorageOperationStatus> result = null; + try{ + ComponentMetadataData componentData = getMetaDataFromComponent(component); + Either<ComponentMetadataData, TitanOperationStatus> updateNode = null; + if(result == null){ + log.debug("Going to update the component {} with new last update date. ", component.getName()); + componentData.getMetadataDataDefinition().setLastUpdateDate(lastUpdateDate); + updateNode = titanGenericDao.updateNode(componentData, ComponentMetadataData.class); + if (updateNode.isRight()) { + log.error("Failed to update component {}. status is {}", component.getUniqueId(), updateNode.right().value()); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value())); + } + } + if(result == null){ + result = Either.left(updateNode.left().value()); + } + }catch(Exception e){ + log.error("Exception occured during update last update date of component {}. The message is {}. ", component.getName(), e.getMessage()); + }finally { + if(!inTransaction){ + if (result == null || result.isRight()) { + log.error("Going to execute rollback on graph."); + titanGenericDao.rollback(); + } else { + log.debug("Going to execute commit on graph."); + titanGenericDao.commit(); + } + } + } + return result; + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ConsumerOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ConsumerOperation.java index aafa4ba444..215a1464a6 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ConsumerOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ConsumerOperation.java @@ -46,11 +46,11 @@ public class ConsumerOperation implements IConsumerOperation { @Override public Either<ConsumerData, StorageOperationStatus> getCredentials(String consumerName) { Either<ConsumerData, StorageOperationStatus> result = null; - log.debug("retriving Credentials for: {}.", consumerName); + log.debug("retriving Credentials for: {}", consumerName); Either<ConsumerData, TitanOperationStatus> getNode = titanGenericDao.getNode(GraphPropertiesDictionary.CONSUMER_NAME.getProperty(), consumerName, ConsumerData.class); if (getNode.isRight()) { TitanOperationStatus status = getNode.right().value(); - log.error("Error returned after get Consumer Data node " + consumerName + ". status returned is " + status); + log.error("Error returned after get Consumer Data node {}. status returned is {}", consumerName, status); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); return result; } @@ -67,11 +67,11 @@ public class ConsumerOperation implements IConsumerOperation { public Either<ConsumerData, StorageOperationStatus> createCredentials(ConsumerData consumerData, boolean inTransaction) { Either<ConsumerData, StorageOperationStatus> result = null; try { - log.debug("creating Credentials for: {}.", consumerData.getUniqueId()); + log.debug("creating Credentials for: {}", consumerData.getUniqueId()); Either<ConsumerData, TitanOperationStatus> createNode = titanGenericDao.createNode(consumerData, ConsumerData.class); if (createNode.isRight()) { TitanOperationStatus status = createNode.right().value(); - log.error("Error returned after creating Consumer Data node " + consumerData.getUniqueId() + ". status returned is " + status); + log.error("Error returned after creating Consumer Data node {}. status returned is {}", consumerData.getUniqueId(), status); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); return result; } @@ -96,7 +96,7 @@ public class ConsumerOperation implements IConsumerOperation { Either<ConsumerData, TitanOperationStatus> deleteNode = titanGenericDao.deleteNode(GraphPropertiesDictionary.CONSUMER_NAME.getProperty(), consumerName, ConsumerData.class); if (deleteNode.isRight()) { TitanOperationStatus status = deleteNode.right().value(); - log.error("Error returned after delete Consumer Data node {}. Status returned is {}", consumerName, status); + log.error("Error returned after delete Consumer Data node {}. status returned is {}", consumerName, status); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); return result; } @@ -120,11 +120,11 @@ public class ConsumerOperation implements IConsumerOperation { Either<ConsumerData, StorageOperationStatus> result = null; try { - log.debug("update Credentials for: {}.", consumerData.getUniqueId()); + log.debug("update Credentials for: {}", consumerData.getUniqueId()); Either<ConsumerData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(consumerData, ConsumerData.class); if (updateNode.isRight()) { TitanOperationStatus status = updateNode.right().value(); - log.error("Error returned after delete Consumer Data node {}. Status returned is {}", consumerData.getUniqueId(), status); + log.error("Error returned after delete Consumer Data node {}. status returned is {}", consumerData.getUniqueId(), status); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); return result; } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CsarOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CsarOperation.java index 1420ce08d8..815eb5be0e 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CsarOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CsarOperation.java @@ -61,7 +61,6 @@ public class CsarOperation { } - // Mock returning a file from the file system until we have API from onboarding public Either<Map<String, byte[]>, StorageOperationStatus> getMockCsar(String csarUuid) { File dir = new File("/var/tmp/mockCsar"); FileFilter fileFilter = new WildcardFileFilter("*.csar"); @@ -93,11 +92,10 @@ public class CsarOperation { */ public Either<Map<String, byte[]>, StorageOperationStatus> getCsar(String csarUuid, User user) { - Either<Map<String, byte[]>, StorageOperationStatus> result = onboardingClient.getCsar(csarUuid, - user.getUserId()); + Either<Map<String, byte[]>, StorageOperationStatus> result = onboardingClient.getCsar(csarUuid, user.getUserId()); if (result.isRight()) { - log.debug("Cannot find csar {}. Status returned is {}", csarUuid, result.right().value()); + log.debug("Cannot find csar {}. Staus returned is {}", csarUuid, result.right().value()); } else { Map<String, byte[]> values = result.left().value(); if (values != null) { diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/DaoStatusConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/DaoStatusConverter.java index b887c5b212..260763cced 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/DaoStatusConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/DaoStatusConverter.java @@ -100,8 +100,7 @@ public class DaoStatusConverter { } - public static StorageOperationStatus convertRsrcUploadStatusToStorageStatus( - ResourceUploadStatus resourceUploadStatus) { + public static StorageOperationStatus convertRsrcUploadStatusToStorageStatus(ResourceUploadStatus resourceUploadStatus) { if (resourceUploadStatus == null) { return StorageOperationStatus.GENERAL_ERROR; } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ElementOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ElementOperation.java index 248a1d0460..ea42c6d76b 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ElementOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ElementOperation.java @@ -29,7 +29,7 @@ import java.util.Map; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.be.config.Configuration.DeploymentArtifactTypeConfig; +import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; @@ -55,8 +55,10 @@ import org.openecomp.sdc.be.resources.data.TagData; import org.openecomp.sdc.be.resources.data.category.CategoryData; import org.openecomp.sdc.be.resources.data.category.GroupingData; import org.openecomp.sdc.be.resources.data.category.SubCategoryData; +import org.openecomp.sdc.common.util.ValidationUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import com.thinkaurelius.titan.core.TitanGraph; @@ -68,11 +70,11 @@ import fj.data.Either; @Component("element-operation") public class ElementOperation implements IElementOperation { - @javax.annotation.Resource private TitanGenericDao titanGenericDao; - public ElementOperation() { + public ElementOperation(@Qualifier("titan-generic-dao") TitanGenericDao titanGenericDao) { super(); + this.titanGenericDao = titanGenericDao; } private static Logger log = LoggerFactory.getLogger(ElementOperation.class.getName()); @@ -107,15 +109,13 @@ public class ElementOperation implements IElementOperation { } @Override - public Either<CategoryDefinition, ActionStatus> createCategory(CategoryDefinition category, NodeTypeEnum nodeType, - boolean inTransaction) { + public Either<CategoryDefinition, ActionStatus> createCategory(CategoryDefinition category, NodeTypeEnum nodeType, boolean inTransaction) { Either<CategoryDefinition, ActionStatus> result = null; category.setUniqueId(UniqueIdBuilder.buildCategoryUid(category.getNormalizedName(), nodeType)); CategoryData categoryData = new CategoryData(nodeType, category); try { - Either<CategoryData, TitanOperationStatus> createNode = titanGenericDao.createNode(categoryData, - CategoryData.class); + Either<CategoryData, TitanOperationStatus> createNode = titanGenericDao.createNode(categoryData, CategoryData.class); if (createNode.isRight()) { TitanOperationStatus value = createNode.right().value(); ActionStatus actionStatus = ActionStatus.GENERAL_ERROR; @@ -141,21 +141,18 @@ public class ElementOperation implements IElementOperation { } @Override - public Either<SubCategoryDefinition, ActionStatus> createSubCategory(String categoryId, - SubCategoryDefinition subCategory, NodeTypeEnum nodeType) { + public Either<SubCategoryDefinition, ActionStatus> createSubCategory(String categoryId, SubCategoryDefinition subCategory, NodeTypeEnum nodeType) { return createSubCategory(categoryId, subCategory, nodeType, false); } @Override - public Either<SubCategoryDefinition, ActionStatus> createSubCategory(String categoryId, - SubCategoryDefinition subCategory, NodeTypeEnum nodeType, boolean inTransaction) { + public Either<SubCategoryDefinition, ActionStatus> createSubCategory(String categoryId, SubCategoryDefinition subCategory, NodeTypeEnum nodeType, boolean inTransaction) { Either<SubCategoryDefinition, ActionStatus> result = null; try { // create edge from category to sub-category - Either<CategoryData, TitanOperationStatus> categoryNode = titanGenericDao - .getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), categoryId, CategoryData.class); + Either<CategoryData, TitanOperationStatus> categoryNode = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), categoryId, CategoryData.class); ActionStatus actionStatus = ActionStatus.GENERAL_ERROR; if (categoryNode.isRight()) { TitanOperationStatus titanOperationStatus = categoryNode.right().value(); @@ -168,12 +165,10 @@ public class ElementOperation implements IElementOperation { } CategoryDataDefinition categoryDataDefinition = categoryNode.left().value().getCategoryDataDefinition(); - subCategory.setUniqueId(UniqueIdBuilder.buildSubCategoryUid(categoryDataDefinition.getUniqueId(), - subCategory.getNormalizedName())); + subCategory.setUniqueId(UniqueIdBuilder.buildSubCategoryUid(categoryDataDefinition.getUniqueId(), subCategory.getNormalizedName())); SubCategoryData subCategoryData = new SubCategoryData(nodeType, subCategory); - Either<SubCategoryData, TitanOperationStatus> subCategoryNode = titanGenericDao.createNode(subCategoryData, - SubCategoryData.class); + Either<SubCategoryData, TitanOperationStatus> subCategoryNode = titanGenericDao.createNode(subCategoryData, SubCategoryData.class); if (subCategoryNode.isRight()) { TitanOperationStatus titanOperationStatus = subCategoryNode.right().value(); log.debug("Problem while creating category, reason {}", titanOperationStatus); @@ -184,15 +179,13 @@ public class ElementOperation implements IElementOperation { return result; } - Either<GraphRelation, TitanOperationStatus> relation = titanGenericDao.createRelation( - categoryNode.left().value(), subCategoryNode.left().value(), GraphEdgeLabels.SUB_CATEGORY, null); + Either<GraphRelation, TitanOperationStatus> relation = titanGenericDao.createRelation(categoryNode.left().value(), subCategoryNode.left().value(), GraphEdgeLabels.SUB_CATEGORY, null); if (relation.isRight()) { log.debug("Problem while create relation between category and sub-category ", relation.right().value()); result = Either.right(actionStatus); return result; } - SubCategoryDefinition subCategoryCreated = new SubCategoryDefinition( - subCategoryNode.left().value().getSubCategoryDataDefinition()); + SubCategoryDefinition subCategoryCreated = new SubCategoryDefinition(subCategoryNode.left().value().getSubCategoryDataDefinition()); result = Either.left(subCategoryCreated); return result; } finally { @@ -207,15 +200,13 @@ public class ElementOperation implements IElementOperation { } @Override - public Either<GroupingDefinition, ActionStatus> createGrouping(String subCategoryId, GroupingDefinition grouping, - NodeTypeEnum nodeType) { + public Either<GroupingDefinition, ActionStatus> createGrouping(String subCategoryId, GroupingDefinition grouping, NodeTypeEnum nodeType) { Either<GroupingDefinition, ActionStatus> result = null; try { // create edge from sub-category to grouping - Either<SubCategoryData, TitanOperationStatus> subCategoryNode = titanGenericDao - .getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId, SubCategoryData.class); + Either<SubCategoryData, TitanOperationStatus> subCategoryNode = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId, SubCategoryData.class); ActionStatus actionStatus = ActionStatus.GENERAL_ERROR; if (subCategoryNode.isRight()) { TitanOperationStatus titanOperationStatus = subCategoryNode.right().value(); @@ -228,12 +219,10 @@ public class ElementOperation implements IElementOperation { } SubCategoryDataDefinition subCatData = subCategoryNode.left().value().getSubCategoryDataDefinition(); - grouping.setUniqueId( - UniqueIdBuilder.buildGroupingUid(subCatData.getUniqueId(), grouping.getNormalizedName())); + grouping.setUniqueId(UniqueIdBuilder.buildGroupingUid(subCatData.getUniqueId(), grouping.getNormalizedName())); GroupingData groupingData = new GroupingData(nodeType, grouping); - Either<GroupingData, TitanOperationStatus> groupingNode = titanGenericDao.createNode(groupingData, - GroupingData.class); + Either<GroupingData, TitanOperationStatus> groupingNode = titanGenericDao.createNode(groupingData, GroupingData.class); if (groupingNode.isRight()) { TitanOperationStatus titanOperationStatus = groupingNode.right().value(); log.debug("Problem while creating grouping, reason {}", titanOperationStatus); @@ -244,15 +233,13 @@ public class ElementOperation implements IElementOperation { return result; } - Either<GraphRelation, TitanOperationStatus> relation = titanGenericDao.createRelation( - subCategoryNode.left().value(), groupingNode.left().value(), GraphEdgeLabels.GROUPING, null); + Either<GraphRelation, TitanOperationStatus> relation = titanGenericDao.createRelation(subCategoryNode.left().value(), groupingNode.left().value(), GraphEdgeLabels.GROUPING, null); if (relation.isRight()) { log.debug("Problem while create relation between sub-category and grouping", relation.right().value()); result = Either.right(actionStatus); return result; } - GroupingDefinition groupingCreated = new GroupingDefinition( - groupingNode.left().value().getGroupingDataDefinition()); + GroupingDefinition groupingCreated = new GroupingDefinition(groupingNode.left().value().getGroupingDataDefinition()); result = Either.left(groupingCreated); return result; } finally { @@ -265,17 +252,14 @@ public class ElementOperation implements IElementOperation { } @Override - public Either<List<CategoryDefinition>, ActionStatus> getAllCategories(NodeTypeEnum nodeType, - boolean inTransaction) { + public Either<List<CategoryDefinition>, ActionStatus> getAllCategories(NodeTypeEnum nodeType, boolean inTransaction) { try { - if (nodeType != NodeTypeEnum.ResourceNewCategory && nodeType != NodeTypeEnum.ServiceNewCategory - && nodeType != NodeTypeEnum.ProductCategory) { + if (nodeType != NodeTypeEnum.ResourceNewCategory && nodeType != NodeTypeEnum.ServiceNewCategory && nodeType != NodeTypeEnum.ProductCategory) { log.debug("Unknown category type {}", nodeType.name()); return Either.right(ActionStatus.GENERAL_ERROR); } - Either<List<org.openecomp.sdc.be.resources.data.category.CategoryData>, TitanOperationStatus> either = titanGenericDao - .getAll(nodeType, org.openecomp.sdc.be.resources.data.category.CategoryData.class); + Either<List<org.openecomp.sdc.be.resources.data.category.CategoryData>, TitanOperationStatus> either = titanGenericDao.getAll(nodeType, org.openecomp.sdc.be.resources.data.category.CategoryData.class); if (either.isRight() && (either.right().value() != TitanOperationStatus.NOT_FOUND)) { log.debug("Problem while get all categories. reason - {}", either.right().value()); return Either.right(ActionStatus.GENERAL_ERROR); @@ -291,8 +275,7 @@ public class ElementOperation implements IElementOperation { log.trace("Found category {}, category type {}", categoryName, nodeType); TitanOperationStatus setSubCategories = setSubCategories(nodeType, categoryDefinition); if (setSubCategories != TitanOperationStatus.OK) { - log.debug("Failed to set sub-categories for category {}, category type {}, error {}", - categoryName, nodeType, setSubCategories); + log.debug("Failed to set sub-categories for category {}, category type {}, error {}", categoryName, nodeType, setSubCategories); return Either.right(ActionStatus.GENERAL_ERROR); } categoryList.add(categoryDefinition); @@ -311,14 +294,12 @@ public class ElementOperation implements IElementOperation { if (childNodeType != null) { String categoryName = parentCategory.getName(); log.trace("Getting sub-categories for category {}, category type {}", categoryName, parentNodeType); - Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, TitanOperationStatus> parentNode = titanGenericDao - .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(parentNodeType), parentCategory.getUniqueId(), - GraphEdgeLabels.SUB_CATEGORY, childNodeType, SubCategoryData.class); + Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, TitanOperationStatus> parentNode = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(parentNodeType), parentCategory.getUniqueId(), GraphEdgeLabels.SUB_CATEGORY, + childNodeType, SubCategoryData.class); if (parentNode.isRight()) { TitanOperationStatus titanOperationStatus = parentNode.right().value(); if (titanOperationStatus == TitanOperationStatus.NOT_FOUND) { - log.trace("Didn't find subcategories for category {}, category type {}", categoryName, - parentNodeType); + log.trace("Didn't find subcategories for category {}, category type {}", categoryName, parentNodeType); titanOperationStatus = TitanOperationStatus.OK; } return titanOperationStatus; @@ -326,16 +307,13 @@ public class ElementOperation implements IElementOperation { List<ImmutablePair<SubCategoryData, GraphEdge>> subsCategoriesData = parentNode.left().value(); List<SubCategoryDefinition> subCategoriesDefinitions = new ArrayList<>(); for (ImmutablePair<SubCategoryData, GraphEdge> subCatPair : subsCategoriesData) { - SubCategoryDataDefinition subCategoryDataDefinition = subCatPair.getLeft() - .getSubCategoryDataDefinition(); + SubCategoryDataDefinition subCategoryDataDefinition = subCatPair.getLeft().getSubCategoryDataDefinition(); SubCategoryDefinition subCategoryDefinition = new SubCategoryDefinition(subCategoryDataDefinition); - log.trace("Found sub-category {} for category {}, category type {}", - subCategoryDataDefinition.getName(), categoryName, parentNodeType); + log.trace("Found sub-category {} for category {}, category type {}", subCategoryDataDefinition.getName(), categoryName, parentNodeType); TitanOperationStatus setGroupings = setGroupings(childNodeType, subCategoryDefinition); if (setGroupings != TitanOperationStatus.OK) { - log.debug("Failed to set groupings for sub-category {}, sub-category type {}, error {}", - subCategoryDataDefinition.getName(), childNodeType, setGroupings); + log.debug("Failed to set groupings for sub-category {}, sub-category type {}, error {}", subCategoryDataDefinition.getName(), childNodeType, setGroupings); return TitanOperationStatus.GENERAL_ERROR; } subCategoriesDefinitions.add(subCategoryDefinition); @@ -350,14 +328,12 @@ public class ElementOperation implements IElementOperation { if (childNodeType != null) { String subCategoryName = parentSubCategory.getName(); log.trace("Getting groupings for subcategory {}, subcategory type {}", subCategoryName, parentNodeType); - Either<List<ImmutablePair<GroupingData, GraphEdge>>, TitanOperationStatus> parentNode = titanGenericDao - .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(parentNodeType), parentSubCategory.getUniqueId(), - GraphEdgeLabels.GROUPING, childNodeType, GroupingData.class); + Either<List<ImmutablePair<GroupingData, GraphEdge>>, TitanOperationStatus> parentNode = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(parentNodeType), parentSubCategory.getUniqueId(), GraphEdgeLabels.GROUPING, + childNodeType, GroupingData.class); if (parentNode.isRight()) { TitanOperationStatus titanOperationStatus = parentNode.right().value(); if (titanOperationStatus == TitanOperationStatus.NOT_FOUND) { - log.trace("Didn't find groupings for subcategory {}, subcategory type {}", subCategoryName, - parentNodeType); + log.trace("Didn't find groupings for subcategory {}, subcategory type {}", subCategoryName, parentNodeType); titanOperationStatus = TitanOperationStatus.OK; } return titanOperationStatus; @@ -366,8 +342,7 @@ public class ElementOperation implements IElementOperation { List<GroupingDefinition> groupingDefinitions = new ArrayList<>(); for (ImmutablePair<GroupingData, GraphEdge> groupPair : groupingData) { GroupingDataDefinition groupingDataDefinition = groupPair.getLeft().getGroupingDataDefinition(); - log.trace("Found grouping {} for sub-category {}, sub-category type {}", - groupingDataDefinition.getName(), subCategoryName, parentNodeType); + log.trace("Found grouping {} for sub-category {}, sub-category type {}", groupingDataDefinition.getName(), subCategoryName, parentNodeType); groupingDefinitions.add(new GroupingDefinition(groupingDataDefinition)); } parentSubCategory.setGroupings(groupingDefinitions); @@ -396,14 +371,12 @@ public class ElementOperation implements IElementOperation { @Override public Either<CategoryDefinition, ActionStatus> getCategory(NodeTypeEnum nodeType, String categoryId) { try { - if (nodeType != NodeTypeEnum.ResourceNewCategory && nodeType != NodeTypeEnum.ServiceNewCategory - && nodeType != NodeTypeEnum.ProductCategory) { + if (nodeType != NodeTypeEnum.ResourceNewCategory && nodeType != NodeTypeEnum.ServiceNewCategory && nodeType != NodeTypeEnum.ProductCategory) { log.debug("Unknown category type {}", nodeType.name()); return Either.right(ActionStatus.GENERAL_ERROR); } - Either<CategoryData, TitanOperationStatus> categoryDataEither = titanGenericDao - .getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), categoryId, CategoryData.class); + Either<CategoryData, TitanOperationStatus> categoryDataEither = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), categoryId, CategoryData.class); if (categoryDataEither.isRight()) { TitanOperationStatus titanOperationStatus = categoryDataEither.right().value(); log.debug("Problem while get category by id {}. reason {}", categoryId, titanOperationStatus); @@ -412,8 +385,7 @@ public class ElementOperation implements IElementOperation { } return Either.right(ActionStatus.GENERAL_ERROR); } - CategoryDataDefinition categoryDataDefinition = categoryDataEither.left().value() - .getCategoryDataDefinition(); + CategoryDataDefinition categoryDataDefinition = categoryDataEither.left().value().getCategoryDataDefinition(); return Either.left(new CategoryDefinition(categoryDataDefinition)); } finally { titanGenericDao.commit(); @@ -428,8 +400,7 @@ public class ElementOperation implements IElementOperation { return Either.right(ActionStatus.GENERAL_ERROR); } - Either<SubCategoryData, TitanOperationStatus> subCategoryDataEither = titanGenericDao - .getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId, SubCategoryData.class); + Either<SubCategoryData, TitanOperationStatus> subCategoryDataEither = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId, SubCategoryData.class); if (subCategoryDataEither.isRight()) { TitanOperationStatus titanOperationStatus = subCategoryDataEither.right().value(); log.debug("Problem while get sub-category by id {}. reason {}", subCategoryId, titanOperationStatus); @@ -438,8 +409,7 @@ public class ElementOperation implements IElementOperation { } return Either.right(ActionStatus.GENERAL_ERROR); } - SubCategoryDataDefinition subCategoryDataDefinition = subCategoryDataEither.left().value() - .getSubCategoryDataDefinition(); + SubCategoryDataDefinition subCategoryDataDefinition = subCategoryDataEither.left().value().getSubCategoryDataDefinition(); return Either.left(new SubCategoryDefinition(subCategoryDataDefinition)); } finally { titanGenericDao.commit(); @@ -450,14 +420,12 @@ public class ElementOperation implements IElementOperation { public Either<CategoryDefinition, ActionStatus> deleteCategory(NodeTypeEnum nodeType, String categoryId) { Either<CategoryDefinition, ActionStatus> result = null; try { - if (nodeType != NodeTypeEnum.ResourceNewCategory && nodeType != NodeTypeEnum.ServiceNewCategory - && nodeType != NodeTypeEnum.ProductCategory) { + if (nodeType != NodeTypeEnum.ResourceNewCategory && nodeType != NodeTypeEnum.ServiceNewCategory && nodeType != NodeTypeEnum.ProductCategory) { log.debug("Unknown category type {}", nodeType.name()); result = Either.right(ActionStatus.GENERAL_ERROR); return result; } - Either<CategoryData, TitanOperationStatus> categoryDataEither = titanGenericDao - .getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), categoryId, CategoryData.class); + Either<CategoryData, TitanOperationStatus> categoryDataEither = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), categoryId, CategoryData.class); if (categoryDataEither.isRight()) { log.debug("Failed to retrieve category for id {} ", categoryId); result = Either.right(ActionStatus.GENERAL_ERROR); @@ -473,8 +441,7 @@ public class ElementOperation implements IElementOperation { TitanGraph tGraph = graph.left().value(); - Iterable<TitanVertex> verticesArtifact = tGraph.query() - .has(UniqueIdBuilder.getKeyByNodeType(nodeType), categoryId).vertices(); + Iterable<TitanVertex> verticesArtifact = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(nodeType), categoryId).vertices(); Iterator<TitanVertex> iterator = verticesArtifact.iterator(); if (!iterator.hasNext()) { log.debug("No category node for id = {}", categoryId); @@ -483,8 +450,7 @@ public class ElementOperation implements IElementOperation { } Vertex artifactV = iterator.next(); artifactV.remove(); - CategoryDefinition deleted = new CategoryDefinition( - categoryDataEither.left().value().getCategoryDataDefinition()); + CategoryDefinition deleted = new CategoryDefinition(categoryDataEither.left().value().getCategoryDataDefinition()); result = Either.left(deleted); return result; } finally { @@ -505,8 +471,7 @@ public class ElementOperation implements IElementOperation { result = Either.right(ActionStatus.GENERAL_ERROR); return result; } - Either<SubCategoryData, TitanOperationStatus> subCategoryDataEither = titanGenericDao - .getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId, SubCategoryData.class); + Either<SubCategoryData, TitanOperationStatus> subCategoryDataEither = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId, SubCategoryData.class); if (subCategoryDataEither.isRight()) { log.debug("Failed to retrieve sub-category for id {}", subCategoryId); result = Either.right(ActionStatus.GENERAL_ERROR); @@ -522,8 +487,7 @@ public class ElementOperation implements IElementOperation { TitanGraph tGraph = graph.left().value(); - Iterable<TitanVertex> verticesArtifact = tGraph.query() - .has(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId).vertices(); + Iterable<TitanVertex> verticesArtifact = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId).vertices(); Iterator<TitanVertex> iterator = verticesArtifact.iterator(); if (!iterator.hasNext()) { log.debug("No sub-category node for id {}", subCategoryId); @@ -533,8 +497,7 @@ public class ElementOperation implements IElementOperation { Vertex artifactV = iterator.next(); artifactV.remove(); ; - SubCategoryDefinition deleted = new SubCategoryDefinition( - subCategoryDataEither.left().value().getSubCategoryDataDefinition()); + SubCategoryDefinition deleted = new SubCategoryDefinition(subCategoryDataEither.left().value().getSubCategoryDataDefinition()); result = Either.left(deleted); return result; } finally { @@ -556,8 +519,7 @@ public class ElementOperation implements IElementOperation { result = Either.right(ActionStatus.GENERAL_ERROR); return result; } - Either<GroupingData, TitanOperationStatus> groupingDataEither = titanGenericDao - .getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), groupingId, GroupingData.class); + Either<GroupingData, TitanOperationStatus> groupingDataEither = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), groupingId, GroupingData.class); if (groupingDataEither.isRight()) { log.debug("Failed to retrieve grouping for id {}", groupingId); result = Either.right(ActionStatus.GENERAL_ERROR); @@ -573,8 +535,7 @@ public class ElementOperation implements IElementOperation { TitanGraph tGraph = graph.left().value(); - Iterable<TitanVertex> verticesArtifact = tGraph.query() - .has(UniqueIdBuilder.getKeyByNodeType(nodeType), groupingId).vertices(); + Iterable<TitanVertex> verticesArtifact = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(nodeType), groupingId).vertices(); Iterator<TitanVertex> iterator = verticesArtifact.iterator(); if (!iterator.hasNext()) { log.debug("No grouping node for id {}", groupingId); @@ -584,8 +545,7 @@ public class ElementOperation implements IElementOperation { Vertex artifactV = iterator.next(); artifactV.remove(); ; - GroupingDefinition deleted = new GroupingDefinition( - groupingDataEither.left().value().getGroupingDataDefinition()); + GroupingDefinition deleted = new GroupingDefinition(groupingDataEither.left().value().getGroupingDataDefinition()); result = Either.left(deleted); return result; } finally { @@ -603,25 +563,21 @@ public class ElementOperation implements IElementOperation { Map<String, Object> properties = new HashMap<>(); properties.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), normalizedName); try { - Either<List<CategoryData>, TitanOperationStatus> categoryEither = titanGenericDao.getByCriteria(nodeType, - properties, CategoryData.class); + Either<List<CategoryData>, TitanOperationStatus> categoryEither = titanGenericDao.getByCriteria(nodeType, properties, CategoryData.class); if (categoryEither.isRight() && categoryEither.right().value() != TitanOperationStatus.NOT_FOUND) { - log.debug("Failed to get categories, nodeType {}, normalizedName {}, error {}", nodeType, - normalizedName, categoryEither.right().value()); + log.debug("Failed to get categories, nodeType {}, normalizedName {}, error {}", nodeType, normalizedName, categoryEither.right().value()); return Either.right(ActionStatus.GENERAL_ERROR); } List<CategoryData> categoryList = (categoryEither.isLeft() ? categoryEither.left().value() : null); if (categoryList != null && categoryList.size() > 0) { log.debug("Found category for nodeType {} with normalizedName {}", nodeType, normalizedName); if (categoryList.size() > 1) { - log.debug("Found more than 1 unique categories for nodeType {} with normalizedName", nodeType, - normalizedName); + log.debug("Found more than 1 unique categories for nodeType {} with normalizedName", nodeType, normalizedName); return Either.right(ActionStatus.GENERAL_ERROR); } return Either.left(false); } else { - log.debug("Category for nodeType {} with normalizedName {} doesn't exist in graph", nodeType, - normalizedName); + log.debug("Category for nodeType {} with normalizedName {} doesn't exist in graph", nodeType, normalizedName); return Either.left(true); } } finally { @@ -630,21 +586,16 @@ public class ElementOperation implements IElementOperation { } @Override - public Either<Boolean, ActionStatus> isSubCategoryUniqueForCategory(NodeTypeEnum nodeType, - String subCategoryNormName, String parentCategoryId) { + public Either<Boolean, ActionStatus> isSubCategoryUniqueForCategory(NodeTypeEnum nodeType, String subCategoryNormName, String parentCategoryId) { String subCategoryId = UniqueIdBuilder.buildSubCategoryUid(parentCategoryId, subCategoryNormName); try { - Either<SubCategoryData, TitanOperationStatus> subCategoryDataEither = titanGenericDao - .getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId, SubCategoryData.class); - if (subCategoryDataEither.isRight() - && subCategoryDataEither.right().value() != TitanOperationStatus.NOT_FOUND) { - log.debug("Failed to get sub-category with id {}, error {}", subCategoryId, - subCategoryDataEither.right().value()); + Either<SubCategoryData, TitanOperationStatus> subCategoryDataEither = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId, SubCategoryData.class); + if (subCategoryDataEither.isRight() && subCategoryDataEither.right().value() != TitanOperationStatus.NOT_FOUND) { + log.debug("Failed to get sub-category with id {}, error {}", subCategoryId, subCategoryDataEither.right().value()); return Either.right(ActionStatus.GENERAL_ERROR); } - SubCategoryData subCategoryData = (subCategoryDataEither.isLeft() ? subCategoryDataEither.left().value() - : null); + SubCategoryData subCategoryData = (subCategoryDataEither.isLeft() ? subCategoryDataEither.left().value() : null); if (subCategoryData != null) { log.debug("Found sub-category with id {}", subCategoryId); return Either.left(false); @@ -658,16 +609,13 @@ public class ElementOperation implements IElementOperation { } @Override - public Either<Boolean, ActionStatus> isGroupingUniqueForSubCategory(NodeTypeEnum nodeType, String groupingNormName, - String parentSubCategoryId) { + public Either<Boolean, ActionStatus> isGroupingUniqueForSubCategory(NodeTypeEnum nodeType, String groupingNormName, String parentSubCategoryId) { String groupingId = UniqueIdBuilder.buildGroupingUid(parentSubCategoryId, groupingNormName); try { - Either<GroupingData, TitanOperationStatus> groupingDataEither = titanGenericDao - .getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), groupingId, GroupingData.class); + Either<GroupingData, TitanOperationStatus> groupingDataEither = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), groupingId, GroupingData.class); if (groupingDataEither.isRight() && groupingDataEither.right().value() != TitanOperationStatus.NOT_FOUND) { - log.debug("Failed to get grouping with id {}, error {}", groupingId, - groupingDataEither.right().value()); + log.debug("Failed to get grouping with id {}, error {}", groupingId, groupingDataEither.right().value()); return Either.right(ActionStatus.GENERAL_ERROR); } GroupingData groupingData = (groupingDataEither.isLeft() ? groupingDataEither.left().value() : null); @@ -684,29 +632,23 @@ public class ElementOperation implements IElementOperation { } @Override - public Either<SubCategoryDefinition, ActionStatus> getSubCategoryUniqueForType(NodeTypeEnum nodeType, - String normalizedName) { + public Either<SubCategoryDefinition, ActionStatus> getSubCategoryUniqueForType(NodeTypeEnum nodeType, String normalizedName) { Map<String, Object> properties = new HashMap<>(); properties.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), normalizedName); try { - Either<List<SubCategoryData>, TitanOperationStatus> subCategoryEither = titanGenericDao - .getByCriteria(nodeType, properties, SubCategoryData.class); + Either<List<SubCategoryData>, TitanOperationStatus> subCategoryEither = titanGenericDao.getByCriteria(nodeType, properties, SubCategoryData.class); if (subCategoryEither.isRight() && subCategoryEither.right().value() != TitanOperationStatus.NOT_FOUND) { - log.debug("Failed to get sub-categories, nodeType {}, normalizedName {}, error {}", nodeType, - normalizedName, subCategoryEither.right().value()); + log.debug("Failed to get sub-categories, nodeType {}, normalizedName {}, error {}", nodeType, normalizedName, subCategoryEither.right().value()); return Either.right(ActionStatus.GENERAL_ERROR); } - List<SubCategoryData> subCategoryList = (subCategoryEither.isLeft() ? subCategoryEither.left().value() - : null); + List<SubCategoryData> subCategoryList = (subCategoryEither.isLeft() ? subCategoryEither.left().value() : null); if (subCategoryList != null && subCategoryList.size() > 0) { log.debug("Found sub-category for nodeType {} with normalizedName {}", nodeType, normalizedName); SubCategoryData subCategoryData = subCategoryList.get(0); - SubCategoryDefinition subCategoryDefinition = new SubCategoryDefinition( - subCategoryData.getSubCategoryDataDefinition()); + SubCategoryDefinition subCategoryDefinition = new SubCategoryDefinition(subCategoryData.getSubCategoryDataDefinition()); return Either.left(subCategoryDefinition); } else { - log.debug("Sub-category for nodeType {} with normalizedName {} doesn't exist in graph", nodeType, - normalizedName); + log.debug("Sub-category for nodeType {} with normalizedName {} doesn't exist in graph", nodeType, normalizedName); return Either.left(null); } } finally { @@ -715,28 +657,23 @@ public class ElementOperation implements IElementOperation { } @Override - public Either<GroupingDefinition, ActionStatus> getGroupingUniqueForType(NodeTypeEnum nodeType, - String groupingNormalizedName) { + public Either<GroupingDefinition, ActionStatus> getGroupingUniqueForType(NodeTypeEnum nodeType, String groupingNormalizedName) { Map<String, Object> properties = new HashMap<>(); properties.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), groupingNormalizedName); try { - Either<List<GroupingData>, TitanOperationStatus> groupingEither = titanGenericDao.getByCriteria(nodeType, - properties, GroupingData.class); + Either<List<GroupingData>, TitanOperationStatus> groupingEither = titanGenericDao.getByCriteria(nodeType, properties, GroupingData.class); if (groupingEither.isRight() && groupingEither.right().value() != TitanOperationStatus.NOT_FOUND) { - log.debug("Failed to get grouping, nodeType {}, normalizedName {}, error {}", nodeType, - groupingNormalizedName, groupingEither.right().value()); + log.debug("Failed to get grouping, nodeType {}, normalizedName {}, error {}", nodeType, groupingNormalizedName, groupingEither.right().value()); return Either.right(ActionStatus.GENERAL_ERROR); } List<GroupingData> groupingList = (groupingEither.isLeft() ? groupingEither.left().value() : null); if (groupingList != null && groupingList.size() > 0) { log.debug("Found grouping for nodeType {} with normalizedName {}", nodeType, groupingNormalizedName); GroupingData groupingData = groupingList.get(0); - GroupingDefinition groupingDefinition = new GroupingDefinition( - groupingData.getGroupingDataDefinition()); + GroupingDefinition groupingDefinition = new GroupingDefinition(groupingData.getGroupingDataDefinition()); return Either.left(groupingDefinition); } else { - log.debug("Grouping for nodeType {} with normalizedName {} doesn't exist in graph", nodeType, - groupingNormalizedName); + log.debug("Grouping for nodeType {} with normalizedName {} doesn't exist in graph", nodeType, groupingNormalizedName); return Either.left(null); } } finally { @@ -751,8 +688,7 @@ public class ElementOperation implements IElementOperation { @Override public Either<List<Tag>, ActionStatus> getAllTags() { try { - Either<List<TagData>, TitanOperationStatus> either = titanGenericDao.getAll(NodeTypeEnum.Tag, - TagData.class); + Either<List<TagData>, TitanOperationStatus> either = titanGenericDao.getAll(NodeTypeEnum.Tag, TagData.class); if (either.isRight()) { log.debug("Problem while get all tags. reason - {}", either.right().value()); return Either.right(ActionStatus.GENERAL_ERROR); @@ -766,8 +702,7 @@ public class ElementOperation implements IElementOperation { } @Override - public <T extends GraphNode> Either<org.openecomp.sdc.be.resources.data.CategoryData, StorageOperationStatus> getCategoryData( - String name, NodeTypeEnum type, Class<T> clazz) { + public <T extends GraphNode> Either<org.openecomp.sdc.be.resources.data.CategoryData, StorageOperationStatus> getCategoryData(String name, NodeTypeEnum type, Class<T> clazz) { if (name != null) { String categoryUid = null; if (type == NodeTypeEnum.ResourceCategory) { @@ -779,8 +714,7 @@ public class ElementOperation implements IElementOperation { } else { categoryUid = UniqueIdBuilder.buildServiceCategoryUid(name, type); } - Either<T, TitanOperationStatus> either = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(type), - categoryUid, clazz); + Either<T, TitanOperationStatus> either = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(type), categoryUid, clazz); if (either.isRight()) { TitanOperationStatus titanOperationStatus = either.right().value(); @@ -827,8 +761,7 @@ public class ElementOperation implements IElementOperation { public Either<List<ArtifactType>, ActionStatus> getAllArtifactTypes() { List<ArtifactType> artifactTypes = new ArrayList<ArtifactType>(); - List<String> artifactTypesList = ConfigurationManager.getConfigurationManager().getConfiguration() - .getArtifactTypes(); + List<String> artifactTypesList = ConfigurationManager.getConfigurationManager().getConfiguration().getArtifactTypes(); for (String artifactType : artifactTypesList) { ArtifactType artifactT = new ArtifactType(); artifactT.setName(artifactType); @@ -841,12 +774,9 @@ public class ElementOperation implements IElementOperation { public Either<Map<String, Object>, ActionStatus> getAllDeploymentArtifactTypes() { Map<String, Object> artifactTypes = new HashMap<String, Object>(); - Map<String, DeploymentArtifactTypeConfig> artifactResourceTypes = ConfigurationManager.getConfigurationManager() - .getConfiguration().getResourceDeploymentArtifacts(); - Map<String, DeploymentArtifactTypeConfig> artifactServiceTypes = ConfigurationManager.getConfigurationManager() - .getConfiguration().getServiceDeploymentArtifacts(); - Map<String, DeploymentArtifactTypeConfig> artifactResourceInstanceTypes = ConfigurationManager - .getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts(); + Map<String, ArtifactTypeConfig> artifactResourceTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts(); + Map<String, ArtifactTypeConfig> artifactServiceTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts(); + Map<String, ArtifactTypeConfig> artifactResourceInstanceTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts(); artifactTypes.put("resourceDeploymentArtifacts", artifactResourceTypes); artifactTypes.put("serviceDeploymentArtifacts", artifactServiceTypes); @@ -858,8 +788,7 @@ public class ElementOperation implements IElementOperation { @Override public Either<Integer, ActionStatus> getDefaultHeatTimeout() { - return Either.left(ConfigurationManager.getConfigurationManager().getConfiguration() - .getDefaultHeatArtifactTimeoutMinutes()); + return Either.left(ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes()); } @Override @@ -876,12 +805,11 @@ public class ElementOperation implements IElementOperation { } @Override - public <T extends GraphNode> Either<CategoryData, StorageOperationStatus> getNewCategoryData(String name, - NodeTypeEnum type, Class<T> clazz) { + public <T extends GraphNode> Either<CategoryData, StorageOperationStatus> getNewCategoryData(String name, NodeTypeEnum type, Class<T> clazz) { if (name != null) { String categoryUid = UniqueIdBuilder.buildServiceCategoryUid(name, type); Map props = new HashMap<>(); - props.put(GraphPropertiesDictionary.NAME.getProperty(), name); + props.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), ValidationUtils.normalizeCategoryName4Uniqueness(name)); Either<List<T>, TitanOperationStatus> either = titanGenericDao.getByCriteria(type, props, clazz); if (either.isRight()) { diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GraphLockOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GraphLockOperation.java index 35541e6d46..89f8f71e2a 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GraphLockOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GraphLockOperation.java @@ -25,6 +25,7 @@ import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation; import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; @@ -32,6 +33,7 @@ import org.openecomp.sdc.be.resources.data.ComponentMetadataData; import org.openecomp.sdc.be.resources.data.ResourceMetadataData; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import fj.data.Either; @@ -42,9 +44,9 @@ public class GraphLockOperation implements IGraphLockOperation { @javax.annotation.Resource private TitanGenericDao titanGenericDao; - - @javax.annotation.Resource - private ResourceOperation resourceOperation; + + @Autowired + ToscaOperationFacade toscaOperationFacade; @javax.annotation.Resource private ICacheMangerOperation cacheManagerOperation; @@ -56,9 +58,7 @@ public class GraphLockOperation implements IGraphLockOperation { /* * (non-Javadoc) * - * @see org.openecomp.sdc.be.model.operations.impl.IGraphLockOperation# - * lockResource(java.lang.String, - * org.openecomp.sdc.be.model.operations.api.IResourceOperation) + * @see org.openecomp.sdc.be.model.operations.impl.IGraphLockOperation# lockResource(java.lang.String, org.openecomp.sdc.be.model.operations.api.IResourceOperation) */ @Override public StorageOperationStatus lockComponent(String componentId, NodeTypeEnum nodeType) { @@ -70,14 +70,13 @@ public class GraphLockOperation implements IGraphLockOperation { // In this way we mark the component as updated one (and component // won't be fetched from cache since the component in cache has // different timestamp) - Either<ComponentMetadataData, TitanOperationStatus> updateTime = updateModificationTimeOfComponent( - componentId, nodeType); - if (updateTime.isRight()) { - TitanOperationStatus operationStatus = updateTime.right().value(); - if (operationStatus != TitanOperationStatus.OK) { - return DaoStatusConverter.convertTitanStatusToStorageStatus(operationStatus); - } - } +// Either<ComponentMetadataData, TitanOperationStatus> updateTime = updateModificationTimeOfComponent(componentId, nodeType); +// if (updateTime.isRight()) { +// TitanOperationStatus operationStatus = updateTime.right().value(); +// if (operationStatus != TitanOperationStatus.OK) { +// return DaoStatusConverter.convertTitanStatusToStorageStatus(operationStatus); +// } +// } lockElementStatus = titanGenericDao.lockElement(componentId, nodeType); @@ -97,24 +96,21 @@ public class GraphLockOperation implements IGraphLockOperation { * @param nodeType * @return */ - private Either<ComponentMetadataData, TitanOperationStatus> updateModificationTimeOfComponent(String componentId, - NodeTypeEnum nodeType) { + private Either<ComponentMetadataData, TitanOperationStatus> updateModificationTimeOfComponent(String componentId, NodeTypeEnum nodeType) { if (nodeType == NodeTypeEnum.Resource || nodeType == NodeTypeEnum.Service || nodeType == NodeTypeEnum.Product) { // We fetch all node since update only timestamp make problems since // there is default resource type (VFC) which changes component // resource type when we update only timestamp(ResourceMetadataData // contains default value VFC on resourceType field). - Either<ComponentMetadataData, TitanOperationStatus> findComp = titanGenericDao - .getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, ComponentMetadataData.class); + Either<ComponentMetadataData, TitanOperationStatus> findComp = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, ComponentMetadataData.class); if (findComp.isRight()) { return Either.right(findComp.right().value()); } ComponentMetadataData componentMetadataData = findComp.left().value(); componentMetadataData.getMetadataDataDefinition().setLastUpdateDate(System.currentTimeMillis()); - Either<ComponentMetadataData, TitanOperationStatus> updateNode = titanGenericDao - .updateNode(componentMetadataData, ComponentMetadataData.class); + Either<ComponentMetadataData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(componentMetadataData, ComponentMetadataData.class); return updateNode; } return Either.right(TitanOperationStatus.OK); @@ -123,23 +119,20 @@ public class GraphLockOperation implements IGraphLockOperation { /* * (non-Javadoc) * - * @see org.openecomp.sdc.be.model.operations.impl.IGraphLockOperation# - * unlockResource(java.lang.String, - * org.openecomp.sdc.be.model.operations.api.IResourceOperation) + * @see org.openecomp.sdc.be.model.operations.impl.IGraphLockOperation# unlockResource(java.lang.String, org.openecomp.sdc.be.model.operations.api.IResourceOperation) */ @Override public StorageOperationStatus unlockComponent(String componentId, NodeTypeEnum nodeType) { - Either<Long, StorageOperationStatus> addComponentToCachePart1 = addComponentToCachePart1WithoutCommit( - componentId, nodeType); +// Either<Long, StorageOperationStatus> addComponentToCachePart1 = addComponentToCachePart1WithoutCommit(componentId, nodeType); TitanOperationStatus lockElementStatus = titanGenericDao.releaseElement(componentId, nodeType); - if (addComponentToCachePart1.isLeft()) { - Long lastUpdateDate = addComponentToCachePart1.left().value(); - addComponentToCachePart2(componentId, lastUpdateDate, nodeType); - } - +// if (addComponentToCachePart1.isLeft()) { +// Long lastUpdateDate = addComponentToCachePart1.left().value(); +// addComponentToCachePart2(componentId, lastUpdateDate, nodeType); +// } +// return DaoStatusConverter.convertTitanStatusToStorageStatus(lockElementStatus); } @@ -151,15 +144,14 @@ public class GraphLockOperation implements IGraphLockOperation { @Override public StorageOperationStatus unlockComponentByName(String name, String componentId, NodeTypeEnum nodeType) { - Either<Long, StorageOperationStatus> addComponentToCachePart1 = addComponentToCachePart1WithoutCommit( - componentId, nodeType); +// Either<Long, StorageOperationStatus> addComponentToCachePart1 = addComponentToCachePart1WithoutCommit(componentId, nodeType); TitanOperationStatus lockElementStatus = titanGenericDao.releaseElement(name, nodeType); - - if (addComponentToCachePart1.isLeft()) { - Long lastUpdateDate = addComponentToCachePart1.left().value(); - addComponentToCachePart2(componentId, lastUpdateDate, nodeType); - } +// +// if (addComponentToCachePart1.isLeft()) { +// Long lastUpdateDate = addComponentToCachePart1.left().value(); +// addComponentToCachePart2(componentId, lastUpdateDate, nodeType); +// } return DaoStatusConverter.convertTitanStatusToStorageStatus(lockElementStatus); } @@ -171,15 +163,12 @@ public class GraphLockOperation implements IGraphLockOperation { * @param nodeType * @return */ - private Either<Long, StorageOperationStatus> addComponentToCachePart1WithoutCommit(String componentId, - NodeTypeEnum nodeType) { + private Either<Long, StorageOperationStatus> addComponentToCachePart1WithoutCommit(String componentId, NodeTypeEnum nodeType) { if (componentId != null) { // In case of error, the componentId might be // empty. - if (nodeType == NodeTypeEnum.Resource || nodeType == NodeTypeEnum.Service - || nodeType == NodeTypeEnum.Product) { + if (nodeType == NodeTypeEnum.Resource || nodeType == NodeTypeEnum.Service || nodeType == NodeTypeEnum.Product) { Long lastUpdateDate = null; - Either<ComponentMetadataData, StorageOperationStatus> resResult = resourceOperation - .getComponentByLabelAndId(componentId, nodeType, ComponentMetadataData.class); + Either<ComponentMetadataData, StorageOperationStatus> resResult = toscaOperationFacade.getComponentMetadata(componentId); if (resResult.isLeft()) { ComponentMetadataData resourceMetadataData = resResult.left().value(); lastUpdateDate = resourceMetadataData.getMetadataDataDefinition().getLastUpdateDate(); @@ -201,12 +190,10 @@ public class GraphLockOperation implements IGraphLockOperation { * @param nodeType * @return */ - private Either<Long, StorageOperationStatus> addComponentToCachePart2(String componentId, Long lastUpdateDate, - NodeTypeEnum nodeType) { + private Either<Long, StorageOperationStatus> addComponentToCachePart2(String componentId, Long lastUpdateDate, NodeTypeEnum nodeType) { if (componentId != null) { // In case of error, the componentId might be // empty. - if (nodeType == NodeTypeEnum.Resource || nodeType == NodeTypeEnum.Service - || nodeType == NodeTypeEnum.Product) { + if (nodeType == NodeTypeEnum.Resource || nodeType == NodeTypeEnum.Service || nodeType == NodeTypeEnum.Product) { // add task to Q log.debug("Going to add component {} of type {} to cache", componentId, nodeType.name().toLowerCase()); cacheManagerOperation.updateComponentInCache(componentId, lastUpdateDate, nodeType); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupInstanceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupInstanceOperation.java new file mode 100644 index 0000000000..bd57689700 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupInstanceOperation.java @@ -0,0 +1,1701 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model.operations.impl; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.function.Supplier; +import java.util.stream.Collectors; + +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.tinkerpop.gremlin.structure.Direction; +import org.apache.tinkerpop.gremlin.structure.Edge; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.apache.tinkerpop.gremlin.structure.VertexProperty; +import org.openecomp.sdc.be.config.BeEcompErrorManager; +import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; +import org.openecomp.sdc.be.dao.graph.GraphElementFactory; +import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; +import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum; +import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; +import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation; +import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; + +import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; +import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.utils.Constants; +import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; + +import org.openecomp.sdc.be.model.ArtifactDefinition; + +import org.openecomp.sdc.be.model.ComponentInstance; + +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.DataTypeDefinition; +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.GroupTypeDefinition; +import org.openecomp.sdc.be.model.IComponentInstanceConnectedElement; +import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; +import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; + +import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; +import org.openecomp.sdc.be.resources.data.ArtifactData; +import org.openecomp.sdc.be.resources.data.AttributeValueData; +import org.openecomp.sdc.be.resources.data.ComponentInstanceData; +import org.openecomp.sdc.be.resources.data.GroupData; +import org.openecomp.sdc.be.resources.data.GroupInstanceData; +import org.openecomp.sdc.be.resources.data.PropertyData; +import org.openecomp.sdc.be.resources.data.PropertyValueData; +import org.openecomp.sdc.be.resources.data.UniqueIdData; +import org.openecomp.sdc.common.datastructure.Wrapper; +import org.openecomp.sdc.common.util.ValidationUtils; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.TitanVertex; + +import fj.data.Either; + +@org.springframework.stereotype.Component("group-instance-operation") +public class GroupInstanceOperation extends AbstractOperation implements IGroupInstanceOperation { + + private static String ADDING_GROUP = "AddingGroupInstance"; + + private static Logger log = LoggerFactory.getLogger(GroupInstanceOperation.class.getName()); + + @Autowired + TitanGenericDao titanGenericDao; + @Autowired + GroupOperation groupOperation; + + @Autowired + PropertyOperation propertyOperation; + + @javax.annotation.Resource + private ApplicationDataTypeCache dataTypeCache; + + @Override + public Either<GroupInstance, StorageOperationStatus> createGroupInstance(String componentInstId, GroupInstance groupInstance, boolean isCreateLogicalName) { + Either<GroupInstance, StorageOperationStatus> result = null; + + if (!ValidationUtils.validateStringNotEmpty(groupInstance.getCustomizationUUID())) { + generateCustomizationUUID(groupInstance); + } + + Either<GroupInstance, TitanOperationStatus> addRes = addGroupInstanceToComponentInstance(componentInstId, isCreateLogicalName, groupInstance); + if (addRes.isRight()) { + TitanOperationStatus status = addRes.right().value(); + log.error("Failed to add resource instance {} to service {}. status is {}", groupInstance, componentInstId, status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + return result; + } + + GroupInstance value = addRes.left().value(); + result = Either.left(value); + + return result; + + } + + @Override + public Either<GroupInstance, StorageOperationStatus> createGroupInstance(TitanVertex ciVertex, String componentInstId, GroupInstance groupInstance, boolean isCreateLogicalName) { + Either<GroupInstance, StorageOperationStatus> result = null; + + if (!ValidationUtils.validateStringNotEmpty(groupInstance.getCustomizationUUID())) { + generateCustomizationUUID(groupInstance); + } + + Either<TitanVertex, TitanOperationStatus> addComponentInstanceToContainerComponent = addGroupInstanceToContainerComponent(ciVertex, componentInstId, isCreateLogicalName, groupInstance); + + if (addComponentInstanceToContainerComponent.isRight()) { + TitanOperationStatus status = addComponentInstanceToContainerComponent.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + TitanVertex giVertex = addComponentInstanceToContainerComponent.left().value(); + Map<String, Object> properties = titanGenericDao.getProperties(giVertex); + GroupInstanceData createdGroupInstanceData = GraphElementFactory.createElement(NodeTypeEnum.GroupInstance.getName(), GraphElementTypeEnum.Node, properties, GroupInstanceData.class); + + GroupInstance createdGroupInstance = new GroupInstance(createdGroupInstanceData.getGroupDataDefinition()); + createdGroupInstance.setGroupName(groupInstance.getGroupName()); + + createdGroupInstance.setArtifacts(groupInstance.getArtifacts()); + + result = Either.left(createdGroupInstance); + + return result; + + } + + @Override + public Either<GroupInstance, StorageOperationStatus> deleteGroupInstanceInstance(NodeTypeEnum containerNodeType, String containerComponentId, String groupInstUid) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either<GroupInstance, StorageOperationStatus> updateGroupInstance(String serviceId, NodeTypeEnum nodeType, String resourceInstanceName, ComponentInstance resourceInstance) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either<List<GroupInstance>, StorageOperationStatus> getAllGroupInstances(String parentId, NodeTypeEnum parentType) { + Either<List<GroupInstance>, StorageOperationStatus> result = null; + List<GroupInstance> groupInstanceRes = new ArrayList<>(); + + Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph(); + if (graph.isRight()) { + log.debug("Failed to work with graph {}", graph.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value())); + } + TitanGraph tGraph = graph.left().value(); + @SuppressWarnings("unchecked") + Iterable<TitanVertex> vertices = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(parentType), parentId).vertices(); + if (vertices == null || vertices.iterator() == null || false == vertices.iterator().hasNext()) { + log.debug("No nodes for type {} for id = {}", parentType, parentId); + result = Either.right(StorageOperationStatus.NOT_FOUND); + return result; + } + + Iterator<TitanVertex> iterator = vertices.iterator(); + Vertex vertex = iterator.next(); + + Map<String, Object> edgeProperties = null; + + Either<List<ImmutablePair<GroupInstanceData, GraphEdge>>, TitanOperationStatus> childrenByEdgeCriteria = titanGenericDao.getChildrenByEdgeCriteria(vertex, parentId, GraphEdgeLabels.GROUP_INST, NodeTypeEnum.GroupInstance, + GroupInstanceData.class, edgeProperties); + + if (childrenByEdgeCriteria.isRight()) { + TitanOperationStatus status = childrenByEdgeCriteria.right().value(); + log.debug("Failed to find group instance {} on graph", childrenByEdgeCriteria.right().value()); + + if (status == TitanOperationStatus.NOT_FOUND) { + result = Either.left(groupInstanceRes); + return result; + } + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + + } + + List<ImmutablePair<GroupInstanceData, GraphEdge>> list = childrenByEdgeCriteria.left().value(); + + for (ImmutablePair<GroupInstanceData, GraphEdge> pair : list) { + GroupInstanceData groupInstData = pair.getLeft(); + GroupInstance groupInstance = new GroupInstance(groupInstData.getGroupDataDefinition()); + String instOriginGroupId = groupInstance.getGroupUid(); + Either<GroupDefinition, TitanOperationStatus> groupRes = groupOperation.getGroupFromGraph(instOriginGroupId, false, true, false); + + if (groupRes.isRight()) { + TitanOperationStatus status = groupRes.right().value(); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + + } + GroupDefinition groupDefinition = groupRes.left().value(); + Either<Map<String, PropertyValueData>, TitanOperationStatus> groupInstancePropertyValuesRes = getAllGroupInstancePropertyValuesData(groupInstData); + if(groupInstancePropertyValuesRes.isRight()){ + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(groupInstancePropertyValuesRes.right().value())); + } + buildGroupInstanceFromGroup(groupInstance, groupDefinition, groupInstancePropertyValuesRes.left().value()); + /* + * Either<List<GroupProperty>, TitanOperationStatus> groupInsPropStatus = getGroupInstanceProperties(groupInstance, groupDefinition); if (groupInsPropStatus.isRight()) { + * + * return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(groupInsPropStatus.right().value())); } + */ + + Either<List<ImmutablePair<String, String>>, TitanOperationStatus> artifactsRes = getGroupArtifactsPairs(groupInstance.getUniqueId()); + if (artifactsRes.isRight()) { + TitanOperationStatus status = artifactsRes.right().value(); + if (status != TitanOperationStatus.OK) { + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + return result; + } + } else { + List<String> artifactsUid = new ArrayList<>(); + List<String> artifactsUUID = new ArrayList<>(); + + List<ImmutablePair<String, String>> list1 = artifactsRes.left().value(); + if (list != null) { + for (ImmutablePair<String, String> pair1 : list1) { + String uid = pair1.left; + String UUID = pair1.right; + artifactsUid.add(uid); + artifactsUUID.add(UUID); + } + groupInstance.setGroupInstanceArtifacts(artifactsUid); + groupInstance.setGroupInstanceArtifactsUuid(artifactsUUID); + } + } + + groupInstanceRes.add(groupInstance); + log.debug("GroupInstance {} was added to list ", groupInstance.getUniqueId()); + } + + result = Either.left(groupInstanceRes); + return result; + + } + + @Override + public Either<GroupInstance, TitanOperationStatus> getGroupInstanceById(String groupResourceId) { + // TODO Auto-generated method stub + return getGroupInstanceFromGraph(groupResourceId, false, false); + } + + @Override + public TitanOperationStatus deleteAllGroupInstances(String componentInstId) { + + return deleteAssociatedGroupInstances(componentInstId); + } + + private TitanOperationStatus deleteAssociatedGroupInstances(String resourceInstanceUid) { + final GraphEdgeLabels edgeConectingToRI = GraphEdgeLabels.GROUP_INST; + final NodeTypeEnum elementTypeToDelete = NodeTypeEnum.GroupInstance; + return deleteAssociatedRIElements(elementTypeToDelete, edgeConectingToRI, resourceInstanceUid, () -> GroupInstanceData.class); + } + + private <T extends GraphNode> TitanOperationStatus deleteAssociatedRIElements(NodeTypeEnum elementTypeToDelete, GraphEdgeLabels edgeConectingToRI, String resourceInstanceUid, Supplier<Class<T>> classGen) { + + Either<List<ImmutablePair<T, GraphEdge>>, TitanOperationStatus> elementsNodesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceUid, edgeConectingToRI, elementTypeToDelete, + classGen.get()); + + if (elementsNodesRes.isRight()) { + TitanOperationStatus status = elementsNodesRes.right().value(); + if (status != TitanOperationStatus.NOT_FOUND) { + BeEcompErrorManager.getInstance().logInternalFlowError("deleteAssociatedRIElements", "Failed to find the elements of resource instance " + resourceInstanceUid + ". status is " + status, ErrorSeverity.ERROR); + return status; + } + } else { + + List<ImmutablePair<T, GraphEdge>> relationshipNodes = elementsNodesRes.left().value(); + if (relationshipNodes != null) { + for (ImmutablePair<T, GraphEdge> immutablePair : relationshipNodes) { + T elementValueDataData = immutablePair.getKey(); + Either<T, TitanOperationStatus> deleteNode = titanGenericDao.deleteNode(elementValueDataData, classGen.get()); + if (deleteNode.isRight()) { + TitanOperationStatus status = deleteNode.right().value(); + BeEcompErrorManager.getInstance().logInternalFlowError("deleteAssociatedRIElements", "Failed to delete element value node " + elementValueDataData + ". status is " + status, ErrorSeverity.ERROR); + return status; + } + } + } + + } + + return TitanOperationStatus.OK; + } + + @Override + public Either<Integer, StorageOperationStatus> increaseAndGetGroupInstancePropertyCounter(String groupInstanceId) { + Either<Integer, StorageOperationStatus> result = null; + + Either<TitanGraph, TitanOperationStatus> graphResult = titanGenericDao.getGraph(); + if (graphResult.isRight()) { + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value())); + return result; + } + Either<TitanVertex, TitanOperationStatus> vertexService = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupInstance), groupInstanceId); + if (vertexService.isRight()) { + log.debug("failed to fetch vertex of resource instance for id = {}", groupInstanceId); + TitanOperationStatus status = vertexService.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexService.right().value())); + return result; + } + Vertex vertex = vertexService.left().value(); + + VertexProperty<Object> vertexProperty = vertex.property(GraphPropertiesDictionary.PROPERTY_COUNTER.getProperty()); + Integer counter = 0; + if (vertexProperty.isPresent()) { + if (vertexProperty.value() != null) { + counter = (Integer) vertexProperty.value(); + } + } + + counter++; + vertex.property(GraphPropertiesDictionary.PROPERTY_COUNTER.getProperty(), counter); + + result = Either.left(counter); + return result; + + } + + @Override + public Either<Boolean, StorageOperationStatus> isGroupInstanceNameExist(String parentComponentId, NodeTypeEnum parentNodeType, String compInstId, String componentInstName) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either<ComponentInstance, StorageOperationStatus> getFullGroupInstance(ComponentInstance componentInstance, NodeTypeEnum compInstNodeType) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either<ComponentInstanceProperty, StorageOperationStatus> addPropertyValueToGroupInstance(ComponentInstanceProperty groupInstanceProperty, String groupInstanceId, Integer index, boolean inTransaction) { + /// #RULES SUPPORT + /// Ignore rules received from client till support + groupInstanceProperty.setRules(null); + /// + /// + + Either<ComponentInstanceProperty, StorageOperationStatus> result = null; + + try { + + Either<PropertyValueData, TitanOperationStatus> eitherStatus = addPropertyToGroupInstance(groupInstanceProperty, groupInstanceId, index); + + if (eitherStatus.isRight()) { + log.error("Failed to add property value {} to resource instance {} in Graph. status is {}", groupInstanceProperty, groupInstanceId, eitherStatus.right().value().name()); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherStatus.right().value())); + return result; + } else { + PropertyValueData propertyValueData = eitherStatus.left().value(); + + ComponentInstanceProperty propertyValueResult = propertyOperation.buildResourceInstanceProperty(propertyValueData, groupInstanceProperty); + log.debug("The returned GroupInstanceProperty is {}", propertyValueResult); + + Either<String, TitanOperationStatus> findDefaultValue = propertyOperation.findDefaultValueFromSecondPosition(groupInstanceProperty.getPath(), groupInstanceProperty.getUniqueId(), groupInstanceProperty.getDefaultValue()); + if (findDefaultValue.isRight()) { + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(findDefaultValue.right().value())); + return result; + } + String defaultValue = findDefaultValue.left().value(); + propertyValueResult.setDefaultValue(defaultValue); + log.debug("The returned default value in ResourceInstanceProperty is {}", defaultValue); + + result = Either.left(propertyValueResult); + return result; + } + } + + finally { + if (false == inTransaction) { + if (result == null || result.isRight()) { + log.error("Going to execute rollback on graph."); + titanGenericDao.rollback(); + } else { + log.debug("Going to execute commit on graph."); + titanGenericDao.commit(); + } + } + } + + } + + @Override + public Either<ComponentInstanceProperty, StorageOperationStatus> addPropertyValueToGroupInstance(ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, boolean isvalidate, Integer index, boolean inTransaction) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Either<ComponentInstanceProperty, StorageOperationStatus> updatePropertyValueInGroupInstance(ComponentInstanceProperty gropuInstanceProperty, String groupInstanceId, boolean inTransaction) { + // TODO Auto-generated method stub + // change Propety class + return null; + } + + @Override + public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> fetchCIEnvArtifacts(String componentInstanceId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public StorageOperationStatus updateCustomizationUUID(String groupInstanceId) { + Either<TitanVertex, TitanOperationStatus> vertexByProperty = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), groupInstanceId); + if (vertexByProperty.isRight()) { + log.debug("Failed to fetch component instance by id {} error {}", groupInstanceId, vertexByProperty.right().value()); + return DaoStatusConverter.convertTitanStatusToStorageStatus(vertexByProperty.right().value()); + } + UUID uuid = UUID.randomUUID(); + TitanVertex ciVertex = vertexByProperty.left().value(); + ciVertex.property(GraphPropertiesDictionary.CUSTOMIZATION_UUID.getProperty(), uuid.toString()); + + return StorageOperationStatus.OK; + } + + public void generateCustomizationUUID(GroupInstance groupInstance) { + UUID uuid = UUID.randomUUID(); + groupInstance.setCustomizationUUID(uuid.toString()); + } + + /** + * add property to resource instance + * + * @param resourceInstanceProperty + * @param resourceInstanceId + * @param index + * @return + */ + public Either<PropertyValueData, TitanOperationStatus> addPropertyToGroupInstance(ComponentInstanceProperty groupInstanceProperty, String groupInstanceId, Integer index) { + + Either<GroupInstanceData, TitanOperationStatus> findResInstanceRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupInstance), groupInstanceId, GroupInstanceData.class); + + if (findResInstanceRes.isRight()) { + TitanOperationStatus status = findResInstanceRes.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + return Either.right(status); + } + + String propertyId = groupInstanceProperty.getUniqueId(); + Either<PropertyData, TitanOperationStatus> findPropertyDefRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), propertyId, PropertyData.class); + + if (findPropertyDefRes.isRight()) { + TitanOperationStatus status = findPropertyDefRes.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + return Either.right(status); + } + + String valueUniqueUid = groupInstanceProperty.getValueUniqueUid(); + if (valueUniqueUid == null) { + + PropertyData propertyData = findPropertyDefRes.left().value(); + GroupInstanceData resourceInstanceData = findResInstanceRes.left().value(); + + ImmutablePair<TitanOperationStatus, String> isPropertyValueExists = propertyOperation.findPropertyValue(groupInstanceId, propertyId); + if (isPropertyValueExists.getLeft() == TitanOperationStatus.ALREADY_EXIST) { + log.debug("The property {} already added to the resource instance {}", propertyId, groupInstanceId); + groupInstanceProperty.setValueUniqueUid(isPropertyValueExists.getRight()); + Either<PropertyValueData, TitanOperationStatus> updatePropertyOfResourceInstance = updatePropertyOfGroupInstance(groupInstanceProperty, groupInstanceId); + if (updatePropertyOfResourceInstance.isRight()) { + BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + updatePropertyOfResourceInstance.right().value(), ErrorSeverity.ERROR); + return Either.right(updatePropertyOfResourceInstance.right().value()); + } + return Either.left(updatePropertyOfResourceInstance.left().value()); + } + + if (isPropertyValueExists.getLeft() != TitanOperationStatus.NOT_FOUND) { + log.debug("After finding property value of {} on componenet instance {}", propertyId, groupInstanceId); + return Either.right(isPropertyValueExists.getLeft()); + } + + String innerType = null; + + PropertyDataDefinition propDataDef = propertyData.getPropertyDataDefinition(); + String propertyType = propDataDef.getType(); + String value = groupInstanceProperty.getValue(); + ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); + + if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { + SchemaDefinition def = propDataDef.getSchema(); + if (def == null) { + log.debug("Schema doesn't exists for property of type {}", type); + return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + } + PropertyDataDefinition propDef = def.getProperty(); + if (propDef == null) { + log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); + return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + } + innerType = propDef.getType(); + } + + log.debug("Before validateAndUpdatePropertyValue"); + Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); + if (allDataTypes.isRight()) { + TitanOperationStatus status = allDataTypes.right().value(); + BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); + return Either.right(status); + } + Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes.left().value()); + log.debug("After validateAndUpdatePropertyValue. isValid = {}", isValid); + + String newValue = value; + if (isValid.isRight()) { + Boolean res = isValid.right().value(); + if (res == false) { + return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + } + } else { + Object object = isValid.left().value(); + if (object != null) { + newValue = object.toString(); + } + } + + String uniqueId = UniqueIdBuilder.buildResourceInstancePropertyValueUid(resourceInstanceData.getUniqueId(), index); + PropertyValueData propertyValueData = new PropertyValueData(); + propertyValueData.setUniqueId(uniqueId); + propertyValueData.setValue(newValue); + + log.debug("Before validateAndUpdateRules"); + ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, groupInstanceProperty.getRules(), innerType, allDataTypes.left().value(), false); + log.debug("After validateAndUpdateRules. pair = {}", pair); + if (pair.getRight() != null && pair.getRight() == false) { + BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), groupInstanceProperty.getName(), propertyType); + return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + } + propertyOperation.addRulesToNewPropertyValue(propertyValueData, groupInstanceProperty, groupInstanceId); + + log.debug("Before adding property value to graph {}", propertyValueData); + Either<PropertyValueData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(propertyValueData, PropertyValueData.class); + log.debug("After adding property value to graph {}", propertyValueData); + + if (createNodeResult.isRight()) { + TitanOperationStatus operationStatus = createNodeResult.right().value(); + return Either.right(operationStatus); + } + propertyValueData = createNodeResult.left().value(); + + Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(propertyValueData, propertyData, GraphEdgeLabels.PROPERTY_IMPL, null); + + if (createRelResult.isRight()) { + TitanOperationStatus operationStatus = createRelResult.right().value(); + log.error("Failed to associate property value {} to property {} in graph. status is {}", uniqueId, propertyId, operationStatus); + return Either.right(operationStatus); + } + + createRelResult = titanGenericDao.createRelation(resourceInstanceData, propertyValueData, GraphEdgeLabels.PROPERTY_VALUE, null); + + if (createRelResult.isRight()) { + TitanOperationStatus operationStatus = createRelResult.right().value(); + log.error("Failed to associate resource instance {} property value {} in graph. status is {}", groupInstanceId, uniqueId, operationStatus); + return Either.right(operationStatus); + } + + return Either.left(propertyValueData); + } else { + log.error("property value already exists."); + return Either.right(TitanOperationStatus.ALREADY_EXIST); + } + + } + + public Either<ComponentInstanceProperty, TitanOperationStatus> addPropertyToResourceInstance(ComponentInstanceProperty groupInstanceProperty, TitanVertex groupInstanceVertex, Integer index, String groupInstanceId) { + + String propertyId = groupInstanceProperty.getUniqueId(); + Either<PropertyData, TitanOperationStatus> findPropertyDefRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), propertyId, PropertyData.class); + + if (findPropertyDefRes.isRight()) { + TitanOperationStatus status = findPropertyDefRes.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + return Either.right(status); + } + + String valueUniqueUid = groupInstanceProperty.getValueUniqueUid(); + if (valueUniqueUid == null) { + + PropertyData propertyData = findPropertyDefRes.left().value(); + + ImmutablePair<TitanOperationStatus, String> isPropertyValueExists = propertyOperation.findPropertyValue(groupInstanceId, propertyId); + if (isPropertyValueExists.getLeft() == TitanOperationStatus.ALREADY_EXIST) { + log.trace("The property {} already added to the resource instance {}", propertyId, groupInstanceId); + groupInstanceProperty.setValueUniqueUid(isPropertyValueExists.getRight()); + Either<PropertyValueData, TitanOperationStatus> updatePropertyOfResourceInstance = updatePropertyOfGroupInstance(groupInstanceProperty, groupInstanceId); + if (updatePropertyOfResourceInstance.isRight()) { + BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + updatePropertyOfResourceInstance.right().value(), ErrorSeverity.ERROR); + return Either.right(updatePropertyOfResourceInstance.right().value()); + } + return Either.right(TitanOperationStatus.OK); + } + + if (isPropertyValueExists.getLeft() != TitanOperationStatus.NOT_FOUND) { + log.trace("After finding property value of {} on componenet instance {}", propertyId, groupInstanceId); + return Either.right(isPropertyValueExists.getLeft()); + } + + String innerType = null; + + PropertyDataDefinition propDataDef = propertyData.getPropertyDataDefinition(); + String propertyType = propDataDef.getType(); + String value = groupInstanceProperty.getValue(); + ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); + + if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { + SchemaDefinition def = propDataDef.getSchema(); + if (def == null) { + log.debug("Schema doesn't exists for property of type {}", type); + return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + } + PropertyDataDefinition propDef = def.getProperty(); + if (propDef == null) { + log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); + return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + } + innerType = propDef.getType(); + } + + log.trace("Before validateAndUpdatePropertyValue"); + Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); + if (allDataTypes.isRight()) { + TitanOperationStatus status = allDataTypes.right().value(); + BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); + return Either.right(status); + } + Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes.left().value()); + log.trace("After validateAndUpdatePropertyValue. isValid = {}", isValid); + + String newValue = value; + if (isValid.isRight()) { + Boolean res = isValid.right().value(); + if (res == false) { + return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + } + } else { + Object object = isValid.left().value(); + if (object != null) { + newValue = object.toString(); + } + } + + String uniqueId = UniqueIdBuilder.buildResourceInstancePropertyValueUid(groupInstanceId, index); + PropertyValueData propertyValueData = new PropertyValueData(); + propertyValueData.setUniqueId(uniqueId); + propertyValueData.setValue(newValue); + + log.trace("Before validateAndUpdateRules"); + ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, groupInstanceProperty.getRules(), innerType, allDataTypes.left().value(), false); + log.debug("After validateAndUpdateRules. pair = {} ", pair); + if (pair.getRight() != null && pair.getRight() == false) { + BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), groupInstanceProperty.getName(), propertyType); + return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + } + propertyOperation.addRulesToNewPropertyValue(propertyValueData, groupInstanceProperty, groupInstanceId); + + log.trace("Before adding property value to graph {}", propertyValueData); + Either<PropertyValueData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(propertyValueData, PropertyValueData.class); + log.trace("After adding property value to graph {}", propertyValueData); + + if (createNodeResult.isRight()) { + TitanOperationStatus operationStatus = createNodeResult.right().value(); + return Either.right(operationStatus); + } + propertyValueData = createNodeResult.left().value(); + + Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(propertyValueData, propertyData, GraphEdgeLabels.PROPERTY_IMPL, null); + + if (createRelResult.isRight()) { + TitanOperationStatus operationStatus = createRelResult.right().value(); + log.error("Failed to associate property value {} to property {} in graph. status is {}", uniqueId, propertyId, operationStatus); + return Either.right(operationStatus); + } + + TitanOperationStatus edgeResult = titanGenericDao.createEdge(groupInstanceVertex, propertyValueData, GraphEdgeLabels.PROPERTY_VALUE, null); + + if (edgeResult != TitanOperationStatus.OK) { + log.error("Failed to associate resource instance {} property value {} in graph. status is {}", groupInstanceId, uniqueId, edgeResult); + return Either.right(edgeResult); + } + + ComponentInstanceProperty propertyValueResult = propertyOperation.buildResourceInstanceProperty(propertyValueData, groupInstanceProperty); + log.debug("The returned ResourceInstanceProperty is {} ", propertyValueResult); + + return Either.left(propertyValueResult); + } else { + log.debug("property value already exists."); + return Either.right(TitanOperationStatus.ALREADY_EXIST); + } + + } + + public Either<GroupInstance, TitanOperationStatus> addGroupInstanceToComponentInstance(String componentInstanceId, boolean isCreateLogicaName, GroupInstance groupInstance) { + log.debug("Going to create group instance {} in componentInstance {}", groupInstance, componentInstanceId); + + Either<TitanVertex, TitanOperationStatus> metadataVertex = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), componentInstanceId); + if (metadataVertex.isRight()) { + TitanOperationStatus status = metadataVertex.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + return Either.right(status); + } + Either<TitanVertex, TitanOperationStatus> addComponentInstanceToContainerComponent = addGroupInstanceToContainerComponent(metadataVertex.left().value(), componentInstanceId, isCreateLogicaName, groupInstance); + + if (addComponentInstanceToContainerComponent.isRight()) { + TitanOperationStatus status = addComponentInstanceToContainerComponent.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + return Either.right(status); + } + TitanVertex ciVertex = addComponentInstanceToContainerComponent.left().value(); + Map<String, Object> properties = titanGenericDao.getProperties(ciVertex); + GroupInstanceData createdComponentInstance = GraphElementFactory.createElement(NodeTypeEnum.GroupInstance.getName(), GraphElementTypeEnum.Node, properties, GroupInstanceData.class); + + GroupInstance createdResourceInstance = new GroupInstance(createdComponentInstance.getGroupDataDefinition()); + + return Either.left(createdResourceInstance); + + } + + /** + * + * @param containerComponentId + * @param containerNodeType + * @param instanceNumber + * @param isCreateLogicaName + * @param componentInstance + * @param compInstNodeType + * @param metadataVertex + * @return + */ + public Either<TitanVertex, TitanOperationStatus> addGroupInstanceToContainerComponent(TitanVertex ciVertex, String componentInstanceId, boolean isCreateLogicaName, GroupInstance groupInstance) { + TitanOperationStatus status = null; + log.debug("Going to create group instance {} in component instance {}", groupInstance, componentInstanceId); + String instOriginGroupId = groupInstance.getGroupUid(); + String logicalName = groupInstance.getName(); + if (isCreateLogicaName){ + String instanceName = (String) titanGenericDao.getProperty(ciVertex, GraphPropertiesDictionary.NORMALIZED_NAME.getProperty()); + logicalName = createGroupInstLogicalName(instanceName, groupInstance.getGroupName()); + } + + GroupInstanceData groupInstanceData = buildGroupInstanceData(groupInstance, componentInstanceId, logicalName); + Either<TitanVertex, TitanOperationStatus> originVertexEither = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), instOriginGroupId); + if (originVertexEither.isRight()) { + log.debug("Failed to fetch vertex of origin resource for id {} error {}", instOriginGroupId, originVertexEither.right().value()); + return Either.right(originVertexEither.right().value()); + } + TitanVertex originVertex = originVertexEither.left().value(); + + // String originType = (String) titanGenericDao.getProperty(originVertex, GraphPropertiesDictionary.LABEL.getProperty()); + String groupType = (String) titanGenericDao.getProperty(originVertex, GraphPropertiesDictionary.TYPE.getProperty()); + // detectOriginType(originType, groupInstanceData, resourceType); + + log.trace("Before adding component instance to graph. componentInstanceData = {}", groupInstanceData); + // groupInstanceData.getGroupDataDefinition().setGroupUid(groupType); + + Either<TitanVertex, TitanOperationStatus> createGIResult = titanGenericDao.createNode(groupInstanceData); + + log.debug("After adding component instance to graph. status is = {}", createGIResult); + + if (createGIResult.isRight()) { + status = createGIResult.right().value(); + BeEcompErrorManager.getInstance().logBeDaoSystemError("Add Component Instance"); + log.debug("Failed to create group instance node in graph. status is {}", status); + return Either.right(status); + } + TitanVertex createdGroupInstanceVertex = createGIResult.left().value(); + TitanOperationStatus associateContainerRes = associateComponentInstanceToGroupInstance(ciVertex, createdGroupInstanceVertex, logicalName); + + String componentInstanceUniqueId = groupInstanceData.getUniqueId(); + if (associateContainerRes != TitanOperationStatus.OK) { + BeEcompErrorManager.getInstance().logBeDaoSystemError("Add Component Instance"); + log.debug("Failed to associate container component {} to component instance {}. Status is {}", componentInstanceId, componentInstanceUniqueId, associateContainerRes); + return Either.right(associateContainerRes); + } + // String originId = (String) titanGenericDao.getProperty(createdGroupInstanceVertex, GraphPropertiesDictionary.TYPE.getProperty()); + + TitanOperationStatus associateToInstOriginComponent = associateToInstOriginGroup(createdGroupInstanceVertex, originVertex, instOriginGroupId); + if (associateToInstOriginComponent != TitanOperationStatus.OK) { + BeEcompErrorManager.getInstance().logBeDaoSystemError("Add Component Instance"); + log.debug("Failed to associate component instance {} to its origin component {}. Status is {}", componentInstanceUniqueId, groupInstanceData.getGroupDataDefinition().getGroupUid(), associateToInstOriginComponent); + return Either.right(associateToInstOriginComponent); + } + + // Capability instance with property values implementation + + if (status == null) { + // ComponentInstance createdResourceInstance = new + // ComponentInstance(createdComponentInstance.getComponentInstDataDefinition()); + // + // String icon = (String) titanGenericDao.getProperty(originVertex, + // GraphPropertiesDictionary.ICON.getProperty()); + // createdResourceInstance.setIcon(icon); + return Either.left(createdGroupInstanceVertex); + } + return Either.right(status); + } + + private GroupInstanceData buildGroupInstanceData(GroupInstance groupInstance, String componentInstanceId, String logicalName) { + String ciOriginComponentUid = groupInstance.getGroupUid(); + + GroupInstanceDataDefinition dataDefinition = new GroupInstanceDataDefinition(groupInstance); + + Long creationDate = groupInstance.getCreationTime(); + if (creationDate == null) { + creationDate = System.currentTimeMillis(); + } + dataDefinition.setCreationTime(creationDate); + dataDefinition.setModificationTime(creationDate); + // dataDefinition.setResourceUid(resourceUid); + // String replacmentlogicalName = logicalName.replaceAll(" ", + // "_").toLowerCase(); + dataDefinition.setName(logicalName); + if (dataDefinition.getNormalizedName() == null) + dataDefinition.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(logicalName)); + dataDefinition.setUniqueId(UniqueIdBuilder.buildResourceInstanceUniuqeId(componentInstanceId, ciOriginComponentUid, dataDefinition.getNormalizedName())); + + GroupInstanceData resourceInstanceData = new GroupInstanceData(dataDefinition); + + return resourceInstanceData; + } + + @Override + public String createGroupInstLogicalName(String instanceName, String groupName) { + + String logicalName = buildGroupInstanceLogicalName(instanceName, groupName); + + return logicalName; + } + + private String buildGroupInstanceLogicalName(String instanceName, String groupName) { + return instanceName + ".." + groupName; + } + + /** + * Make a relation between service to resource instance. + * + * @param containerCompIdData + * @param componentInstanceData + * @param logicalName + * @return + */ + private Either<GraphRelation, TitanOperationStatus> associateComponentInstanceToGroupInstance(UniqueIdData compInstIdData, GroupInstanceData groupInstanceData, String logicalName) { + Map<String, Object> properties = new HashMap<String, Object>(); + + properties.put(GraphPropertiesDictionary.NAME.getProperty(), logicalName); + Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(compInstIdData, groupInstanceData, GraphEdgeLabels.GROUP_INST, properties); + + log.debug("After associating container component {} to resource instance {} with logical name {}. Status is {}", compInstIdData.getUniqueId(), groupInstanceData.getUniqueId(), logicalName, createRelation); + + return createRelation; + } + + private TitanOperationStatus associateComponentInstanceToGroupInstance(TitanVertex componentInstVertex, TitanVertex groupInstanceVertex, String logicalName) { + Map<String, Object> properties = new HashMap<String, Object>(); + + properties.put(GraphPropertiesDictionary.NAME.getProperty(), logicalName); + TitanOperationStatus createRelation = titanGenericDao.createEdge(componentInstVertex, groupInstanceVertex, GraphEdgeLabels.GROUP_INST, properties); + + return createRelation; + } + + private Either<GraphRelation, TitanOperationStatus> associateToInstOriginGroup(GroupInstanceData groupInstanceData, NodeTypeEnum compInstNodeType) { + + UniqueIdData groupIdData = new UniqueIdData(compInstNodeType, groupInstanceData.getGroupDataDefinition().getGroupUid()); + + Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(groupInstanceData, groupIdData, GraphEdgeLabels.INSTANCE_OF, null); + + log.debug("After associating group instance {} to group {}. status is {}", groupInstanceData.getUniqueId(), groupInstanceData.getGroupDataDefinition().getGroupUid(), createRelation); + + return createRelation; + } + + private TitanOperationStatus associateToInstOriginGroup(TitanVertex groupInstanceVertex, TitanVertex originVertex, String originId) { + + TitanOperationStatus createRelation = titanGenericDao.createEdge(groupInstanceVertex, originVertex, GraphEdgeLabels.INSTANCE_OF, null); + + log.debug("After associating group instance {} to group {}. status is {}", groupInstanceVertex, originId, createRelation); + + return createRelation; + } + + public Either<List<GroupProperty>, TitanOperationStatus> getGroupInstanceProperties(GroupInstance groupInstance, GroupDefinition groupDefinition) { + + // 1. Go over each instance + // 1.1 get all properties of from the parents of the instance + // 1.2 get all updated properties + // 1.3 find all instances included in the parent of this instance and + // run this method on them. + String groupInstanceId = groupInstance.getUniqueId(); + if (log.isDebugEnabled()) + log.debug("Going to update properties of group instance {}", groupInstanceId); + String groupUid = groupInstance.getGroupUid(); + List<GroupProperty> properties = groupDefinition.convertToGroupProperties(); + + if (log.isDebugEnabled()) + log.debug("After getting properties of group {} . Number of properties is {}", groupUid, (properties == null ? 0 : properties.size())); + List<GroupProperty> resourceInstancePropertyList = new ArrayList<>(); + if (properties != null && false == properties.isEmpty()) { + + // TODO: WE MAY HAVE INDIRECT PROPERTY VALUE ALSO IN CASE NO + // PROPERTY ON THIS COMPONENT + + // String resourceInstanceUid = resourceInstance.getUniqueId(); + + for (GroupProperty propertyDefinition : properties) { + + String defaultValue = propertyDefinition.getDefaultValue(); + String value = defaultValue; + String valueUid = null; + + // String propertyId = propertyDefinition.getUniqueId(); + + GroupProperty resourceInstanceProperty = new GroupProperty(propertyDefinition, value, valueUid); + + // resourceInstanceProperty.setPath(cloneList(path)); + + // TODO: currently ignore constraints since they are not inuse + // and cause to error in convertion to object. + resourceInstanceProperty.setConstraints(null); + + resourceInstancePropertyList.add(resourceInstanceProperty); + + } + + } + + return Either.left(resourceInstancePropertyList); + } + + /** + * update value of attribute on resource instance + * + * @param resourceInstanceProerty + * @param resourceInstanceId + * @return + */ + public Either<PropertyValueData, TitanOperationStatus> updatePropertyOfGroupInstance(ComponentInstanceProperty groupInstanceProerty, String groupInstanceId) { + + Wrapper<TitanOperationStatus> errorWrapper = new Wrapper<>(); + UpdateDataContainer<PropertyData, PropertyValueData> updateDataContainer = new UpdateDataContainer<>(GraphEdgeLabels.PROPERTY_IMPL, (() -> PropertyData.class), (() -> PropertyValueData.class), NodeTypeEnum.Property, + NodeTypeEnum.PropertyValue); + + preUpdateElementOfResourceInstanceValidations(updateDataContainer, groupInstanceProerty, groupInstanceId, errorWrapper); + if (!errorWrapper.isEmpty()) { + return Either.right(errorWrapper.getInnerElement()); + } + + else { + String value = groupInstanceProerty.getValue(); + // Specific Validation Logic + PropertyData propertyData = updateDataContainer.getDataWrapper().getInnerElement(); + + String innerType = null; + + PropertyDataDefinition propDataDef = propertyData.getPropertyDataDefinition(); + String propertyType = propDataDef.getType(); + ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); + log.debug("The type of the property {} is {}", propertyData.getUniqueId(), propertyType); + + if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { + SchemaDefinition def = propDataDef.getSchema(); + if (def == null) { + log.debug("Schema doesn't exists for property of type {}", type); + return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + } + PropertyDataDefinition propDef = def.getProperty(); + if (propDef == null) { + log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); + return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + } + innerType = propDef.getType(); + } + // Specific Update Logic + Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); + if (allDataTypes.isRight()) { + TitanOperationStatus status = allDataTypes.right().value(); + BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); + return Either.right(status); + } + Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes.left().value()); + + String newValue = value; + if (isValid.isRight()) { + Boolean res = isValid.right().value(); + if (res == false) { + return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + } + } else { + Object object = isValid.left().value(); + if (object != null) { + newValue = object.toString(); + } + } + PropertyValueData propertyValueData = updateDataContainer.getValueDataWrapper().getInnerElement(); + log.debug("Going to update property value from {} to {}", propertyValueData.getValue(), newValue); + propertyValueData.setValue(newValue); + + ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, groupInstanceProerty.getRules(), innerType, allDataTypes.left().value(), true); + if (pair.getRight() != null && pair.getRight() == false) { + BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), groupInstanceProerty.getName(), propertyType); + return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + } + propertyOperation.updateRulesInPropertyValue(propertyValueData, groupInstanceProerty, groupInstanceId); + + Either<PropertyValueData, TitanOperationStatus> updateRes = titanGenericDao.updateNode(propertyValueData, PropertyValueData.class); + if (updateRes.isRight()) { + TitanOperationStatus status = updateRes.right().value(); + return Either.right(status); + } else { + return Either.left(updateRes.left().value()); + } + } + + } + + private static final class UpdateDataContainer<SomeData, SomeValueData> { + final Wrapper<SomeValueData> valueDataWrapper; + final Wrapper<SomeData> dataWrapper; + final GraphEdgeLabels graphEdge; + final Supplier<Class<SomeData>> someDataClassGen; + final Supplier<Class<SomeValueData>> someValueDataClassGen; + final NodeTypeEnum nodeType; + final NodeTypeEnum nodeTypeValue; + + private UpdateDataContainer(GraphEdgeLabels graphEdge, Supplier<Class<SomeData>> someDataClassGen, Supplier<Class<SomeValueData>> someValueDataClassGen, NodeTypeEnum nodeType, NodeTypeEnum nodeTypeValue) { + super(); + this.valueDataWrapper = new Wrapper<>(); + this.dataWrapper = new Wrapper<>(); + this.graphEdge = graphEdge; + this.someDataClassGen = someDataClassGen; + this.someValueDataClassGen = someValueDataClassGen; + this.nodeType = nodeType; + this.nodeTypeValue = nodeTypeValue; + } + + public Wrapper<SomeValueData> getValueDataWrapper() { + return valueDataWrapper; + } + + public Wrapper<SomeData> getDataWrapper() { + return dataWrapper; + } + + public GraphEdgeLabels getGraphEdge() { + return graphEdge; + } + + public Supplier<Class<SomeData>> getSomeDataClassGen() { + return someDataClassGen; + } + + public Supplier<Class<SomeValueData>> getSomeValueDataClassGen() { + return someValueDataClassGen; + } + + public NodeTypeEnum getNodeType() { + return nodeType; + } + + public NodeTypeEnum getNodeTypeValue() { + return nodeTypeValue; + } + } + + private <SomeData extends GraphNode, SomeValueData extends GraphNode> void preUpdateElementOfResourceInstanceValidations(UpdateDataContainer<SomeData, SomeValueData> updateDataContainer, IComponentInstanceConnectedElement resourceInstanceProerty, + String resourceInstanceId, Wrapper<TitanOperationStatus> errorWrapper) { + + if (errorWrapper.isEmpty()) { + // Verify VFC instance Exist + validateGIExist(resourceInstanceId, errorWrapper); + } + + if (errorWrapper.isEmpty()) { + // Example: Verify Property connected to VFC exist + validateElementConnectedToComponentExist(updateDataContainer, resourceInstanceProerty, errorWrapper); + } + + if (errorWrapper.isEmpty()) { + // Example: Verify PropertyValue connected to VFC Instance exist + validateElementConnectedToComponentInstanceExist(updateDataContainer, resourceInstanceProerty, errorWrapper); + } + + if (errorWrapper.isEmpty()) { + // Example: Verify PropertyValue connected Property + validateElementConnectedToInstance(updateDataContainer, resourceInstanceProerty, errorWrapper); + } + } + + private <SomeData extends GraphNode, SomeValueData extends GraphNode> void validateElementConnectedToInstance(UpdateDataContainer<SomeData, SomeValueData> updateDataContainer, IComponentInstanceConnectedElement resourceInstanceProerty, + Wrapper<TitanOperationStatus> errorWrapper) { + Either<ImmutablePair<SomeData, GraphEdge>, TitanOperationStatus> child = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(updateDataContainer.getNodeTypeValue()), resourceInstanceProerty.getValueUniqueUid(), + updateDataContainer.getGraphEdge(), updateDataContainer.getNodeType(), updateDataContainer.getSomeDataClassGen().get()); + + if (child.isRight()) { + TitanOperationStatus status = child.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + errorWrapper.setInnerElement(status); + + } else { + updateDataContainer.getDataWrapper().setInnerElement(child.left().value().left); + } + } + + private <SomeValueData extends GraphNode, SomeData extends GraphNode> void validateElementConnectedToComponentInstanceExist(UpdateDataContainer<SomeData, SomeValueData> updateDataContainer, + IComponentInstanceConnectedElement resourceInstanceProerty, Wrapper<TitanOperationStatus> errorWrapper) { + String valueUniqueUid = resourceInstanceProerty.getValueUniqueUid(); + if (valueUniqueUid == null) { + errorWrapper.setInnerElement(TitanOperationStatus.INVALID_ID); + } else { + Either<SomeValueData, TitanOperationStatus> findPropertyValueRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(updateDataContainer.getNodeTypeValue()), valueUniqueUid, updateDataContainer.getSomeValueDataClassGen().get()); + if (findPropertyValueRes.isRight()) { + TitanOperationStatus status = findPropertyValueRes.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + errorWrapper.setInnerElement(status); + } else { + updateDataContainer.getValueDataWrapper().setInnerElement(findPropertyValueRes.left().value()); + } + } + } + + private <SomeData extends GraphNode, SomeValueData extends GraphNode> void validateElementConnectedToComponentExist(UpdateDataContainer<SomeData, SomeValueData> updateDataContainer, + IComponentInstanceConnectedElement resourceInstanceElementConnected, Wrapper<TitanOperationStatus> errorWrapper) { + String uniqueId = resourceInstanceElementConnected.getUniqueId(); + Either<SomeData, TitanOperationStatus> findPropertyDefRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(updateDataContainer.getNodeType()), uniqueId, updateDataContainer.getSomeDataClassGen().get()); + + if (findPropertyDefRes.isRight()) { + TitanOperationStatus status = findPropertyDefRes.right().value(); + errorWrapper.setInnerElement(status); + } + } + + private void validateGIExist(String resourceInstanceId, Wrapper<TitanOperationStatus> errorWrapper) { + validateGIExist(resourceInstanceId, null, errorWrapper); + } + + private void validateGIExist(String resourceInstanceId, Wrapper<GroupInstanceData> compInsDataWrapper, Wrapper<TitanOperationStatus> errorWrapper) { + validateElementExistInGraph(resourceInstanceId, NodeTypeEnum.GroupInstance, () -> GroupInstanceData.class, compInsDataWrapper, errorWrapper); + } + + public <ElementData extends GraphNode> void validateElementExistInGraph(String elementUniqueId, NodeTypeEnum elementNodeType, Supplier<Class<ElementData>> elementClassGen, Wrapper<ElementData> elementDataWrapper, + Wrapper<TitanOperationStatus> errorWrapper) { + Either<ElementData, TitanOperationStatus> findResInstanceRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(elementNodeType), elementUniqueId, elementClassGen.get()); + if (findResInstanceRes.isRight()) { + TitanOperationStatus status = findResInstanceRes.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + errorWrapper.setInnerElement(status); + } else { + if (elementDataWrapper != null) { + elementDataWrapper.setInnerElement(findResInstanceRes.left().value()); + } + } + } + + /** + * Associate artifacts to a given group + * + * @param groupId + * @param artifactsId + * @param inTransaction + * @return + */ + public Either<GroupInstance, StorageOperationStatus> associateArtifactsToGroupInstance(String groupId, List<String> artifactsId) { + + Either<GroupInstance, StorageOperationStatus> result = null; + + Either<GroupInstance, TitanOperationStatus> titanRes = this.associateArtifactsToGroupInstanceOnGraph(groupId, artifactsId); + + if (titanRes.isRight()) { + StorageOperationStatus status = DaoStatusConverter.convertTitanStatusToStorageStatus(titanRes.right().value()); + result = Either.right(status); + } + + result = Either.left(titanRes.left().value()); + return result; + + } + + public Either<GroupInstance, TitanOperationStatus> associateArtifactsToGroupInstanceOnGraph(String groupInstanceId, List<String> artifactsId) { + + if (artifactsId == null || artifactsId.isEmpty()) { + return Either.right(TitanOperationStatus.OK); + } + + for (String artifactId : artifactsId) { + Either<ArtifactData, TitanOperationStatus> findArtifactRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId, ArtifactData.class); + if (findArtifactRes.isRight()) { + TitanOperationStatus status = findArtifactRes.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + String description = "Failed to associate group " + groupInstanceId + " to artifact " + artifactId + " in graph. Status is " + status; + BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR); + return Either.right(status); + } + + Map<String, Object> props = new HashMap<String, Object>(); + props.put(GraphPropertiesDictionary.NAME.getProperty(), findArtifactRes.left().value().getLabel()); + + GraphNode groupData = new UniqueIdData(NodeTypeEnum.GroupInstance, groupInstanceId); + Either<GraphRelation, TitanOperationStatus> addArtifactsRefResult = titanGenericDao.createRelation(groupData, findArtifactRes.left().value(), GraphEdgeLabels.GROUP_ARTIFACT_REF, props); + + if (addArtifactsRefResult.isRight()) { + TitanOperationStatus status = addArtifactsRefResult.right().value(); + String description = "Failed to associate group " + groupData.getUniqueId() + " to artifact " + artifactId + " in graph. Status is " + status; + BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR); + return Either.right(status); + } + } + + Either<GroupInstance, TitanOperationStatus> groupFromGraph = this.getGroupInstanceFromGraph(groupInstanceId, true, false); + + return groupFromGraph; + } + + public Either<GroupInstance, TitanOperationStatus> getGroupInstanceFromGraph(String uniqueId, boolean skipProperties, boolean skipArtifacts) { + + Either<GroupInstance, TitanOperationStatus> result = null; + + Either<GroupInstanceData, TitanOperationStatus> groupInstRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupInstance), uniqueId, GroupInstanceData.class); + if (groupInstRes.isRight()) { + TitanOperationStatus status = groupInstRes.right().value(); + log.debug("Failed to retrieve group {} from graph. Status is {}", uniqueId, status); + BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("Fetch Group", uniqueId, String.valueOf(status)); + result = Either.right(status); + return result; + } + + GroupInstanceData groupInstData = groupInstRes.left().value(); + + GroupInstance groupInstance = new GroupInstance(groupInstData.getGroupDataDefinition()); + String instOriginGroupId = groupInstance.getGroupUid(); + Either<GroupDefinition, TitanOperationStatus> groupRes = groupOperation.getGroupFromGraph(instOriginGroupId, false, true, false); + + if (groupRes.isRight()) { + TitanOperationStatus status = groupRes.right().value(); + result = Either.right(status); + + } + GroupDefinition groupDefinition = groupRes.left().value(); + Either<Map<String, PropertyValueData>, TitanOperationStatus> groupInstancePropertyValuesRes = getAllGroupInstancePropertyValuesData(groupInstData); + if(groupInstancePropertyValuesRes.isRight()){ + result = Either.right(groupInstancePropertyValuesRes.right().value()); + } + buildGroupInstanceFromGroup(groupInstance, groupDefinition, groupInstancePropertyValuesRes.left().value()); + + /* + * if (false == skipProperties) { Either<List<GroupProperty>, TitanOperationStatus> propertiesRes = getGroupProperties(uniqueId); if (propertiesRes.isRight()) { TitanOperationStatus status = propertiesRes.right().value(); if (status != + * TitanOperationStatus.OK) { result = Either.right(status); return result; } } else { List<GroupProperty> properties = propertiesRes.left().value(); groupDefinition.setProperties(properties); } } + */ + + if (false == skipArtifacts) { + Either<List<ImmutablePair<String, String>>, TitanOperationStatus> artifactsRes = getGroupArtifactsPairs(uniqueId); + if (artifactsRes.isRight()) { + TitanOperationStatus status = artifactsRes.right().value(); + if (status != TitanOperationStatus.OK) { + result = Either.right(status); + return result; + } + } else { + List<String> artifactsUid = new ArrayList<>(); + List<String> artifactsUUID = new ArrayList<>(); + + List<ImmutablePair<String, String>> list = artifactsRes.left().value(); + if (list != null) { + for (ImmutablePair<String, String> pair : list) { + String uid = pair.left; + String UUID = pair.right; + artifactsUid.add(uid); + artifactsUUID.add(UUID); + } + groupInstance.setGroupInstanceArtifacts(artifactsUid); + groupInstance.setGroupInstanceArtifactsUuid(artifactsUUID); + } + } + } + result = Either.left(groupInstance); + + return result; + + } + + private void buildGroupInstanceFromGroup(GroupInstance groupInstance, GroupDefinition groupDefinition, Map<String, PropertyValueData> groupInstancePropertyValues) { + + groupInstance.setGroupName(groupDefinition.getName()); + groupInstance.setInvariantUUID(groupDefinition.getInvariantUUID()); + groupInstance.setDescription(groupDefinition.getDescription()); + groupInstance.setVersion(groupDefinition.getVersion()); + groupInstance.setArtifacts(groupDefinition.getArtifacts()); + groupInstance.setArtifactsUuid(groupDefinition.getArtifactsUuid()); + groupInstance.setType(groupDefinition.getType()); + groupInstance.setGroupUUID(groupDefinition.getGroupUUID()); + + List<GroupInstanceProperty> groupInstanceProperties = groupDefinition.convertToGroupProperties() + //converts List of GroupProperties to List of GroupInstanceProperties and updates it with group instance property data + .stream().map(p->getUpdatedConvertedProperty(p, groupInstancePropertyValues)).collect(Collectors.toList()); + groupInstance.convertFromGroupInstancesProperties(groupInstanceProperties); +} + + private GroupInstanceProperty getUpdatedConvertedProperty(GroupProperty groupProperty, Map<String, PropertyValueData> groupInstancePropertyValues){ + + GroupInstanceProperty updatedProperty = new GroupInstanceProperty(groupProperty, groupProperty.getValue()); + if(!MapUtils.isEmpty(groupInstancePropertyValues) && groupInstancePropertyValues.containsKey(groupProperty.getName())){ + PropertyValueData groupInstancePropertyValue = groupInstancePropertyValues.get(groupProperty.getName()); + updatedProperty.setValue(groupInstancePropertyValue.getValue()); + updatedProperty.setValueUniqueUid(groupInstancePropertyValue.getUniqueId()); + } + return updatedProperty; + } + + private Either<List<ImmutablePair<String, String>>, TitanOperationStatus> getGroupArtifactsPairs(String groupUniqueId) { + + Either<List<ImmutablePair<String, String>>, TitanOperationStatus> result = null; + + Either<List<ImmutablePair<ArtifactData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupInstance), groupUniqueId, GraphEdgeLabels.GROUP_ARTIFACT_REF, + NodeTypeEnum.ArtifactRef, ArtifactData.class); + if (childrenNodes.isRight()) { + TitanOperationStatus status = childrenNodes.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.OK; + } + result = Either.right(status); + + } else { + + List<ImmutablePair<String, String>> artifactsList = new ArrayList<>(); + List<ImmutablePair<ArtifactData, GraphEdge>> list = childrenNodes.left().value(); + if (list != null) { + for (ImmutablePair<ArtifactData, GraphEdge> pair : list) { + ArtifactData artifactData = pair.getKey(); + String uniqueId = artifactData.getArtifactDataDefinition().getUniqueId(); + String UUID = artifactData.getArtifactDataDefinition().getArtifactUUID(); + ImmutablePair<String, String> artifact = new ImmutablePair<String, String>(uniqueId, UUID); + artifactsList.add(artifact); + } + } + + log.debug("The artifacts list related to group {} is {}",groupUniqueId,artifactsList); + result = Either.left(artifactsList); + } + + return result; + + } + + @Override + public StorageOperationStatus dissociateAndAssociateGroupsInstanceFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact) { + + StorageOperationStatus result = null; + + return this.dissociateAndAssociateGroupsInstanceFromArtifactOnGraph(componentId, componentTypeEnum, oldArtifactId, newArtifact); + + } + + @Override + public StorageOperationStatus dissociateAndAssociateGroupsInstanceFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact) { + + Either<List<GroupInstance>, StorageOperationStatus> allGroupsFromGraph = getAllGroupInstances(componentId, componentTypeEnum); + if (allGroupsFromGraph.isRight()) { + StorageOperationStatus status = allGroupsFromGraph.right().value(); + return status; + } + + List<GroupInstance> allGroups = allGroupsFromGraph.left().value(); + if (allGroups == null || allGroups.isEmpty()) { + return StorageOperationStatus.OK; + } + + // Find all groups which contains this artifact id + List<GroupInstance> associatedGroups = allGroups.stream().filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts().contains(oldArtifactId)).collect(Collectors.toList()); + + if (associatedGroups != null && false == associatedGroups.isEmpty()) { + + log.debug("The groups {} contains the artifact {}",associatedGroups.stream().map(p -> p.getName()).collect(Collectors.toList()),oldArtifactId); + + UniqueIdData oldArtifactData = new UniqueIdData(NodeTypeEnum.ArtifactRef, oldArtifactId); + UniqueIdData newArtifactData = new UniqueIdData(NodeTypeEnum.ArtifactRef, newArtifact.getArtifactDataDefinition().getUniqueId()); + Map<String, Object> props = new HashMap<String, Object>(); + props.put(GraphPropertiesDictionary.NAME.getProperty(), newArtifactData.getLabel()); + + for (GroupInstance groupDefinition : associatedGroups) { + UniqueIdData groupData = new UniqueIdData(NodeTypeEnum.GroupInstance, groupDefinition.getUniqueId()); + + Either<GraphRelation, TitanOperationStatus> deleteRelation = titanGenericDao.deleteRelation(groupData, oldArtifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF); + log.trace("After dissociate group {} from artifact {}", groupDefinition.getName(), oldArtifactId); + if (deleteRelation.isRight()) { + TitanOperationStatus status = deleteRelation.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + return DaoStatusConverter.convertTitanStatusToStorageStatus(status); + } + + Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(groupData, newArtifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF, props); + log.trace("After associate group {} to artifact {}", groupDefinition.getName(), newArtifact.getUniqueIdKey()); + if (createRelation.isRight()) { + TitanOperationStatus status = createRelation.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + return DaoStatusConverter.convertTitanStatusToStorageStatus(status); + } + } + + } + return StorageOperationStatus.OK; + } + + @Override + public Either<GroupInstance, StorageOperationStatus> updateGroupInstancePropertyValues(GroupInstance oldGroupInstance, List<GroupInstanceProperty> newProperties, Boolean inTransaction) { + + Either<GroupInstance, StorageOperationStatus> updateRes = Either.left(oldGroupInstance); + try{ + if(!CollectionUtils.isEmpty(newProperties)){ + updateRes = updateGroupInstancePropertyValuesOnGraph(oldGroupInstance, newProperties); + } + }catch(Exception e){ + log.debug("The Exception occured during update of group instance {} property values. The message is {}. ", oldGroupInstance.getName(), e.getMessage(), e); + updateRes = Either.right(StorageOperationStatus.GENERAL_ERROR); + }finally { + handleTransactionCommitRollback(inTransaction, updateRes); + } + return updateRes; + } + + private Either<GroupInstance, StorageOperationStatus> updateGroupInstancePropertyValuesOnGraph( GroupInstance oldGroupInstance, List<GroupInstanceProperty> newProperties ) { + Either<GroupInstance, StorageOperationStatus> updateRes = null; + Either<Integer, StorageOperationStatus> nodeUpdateRes = null; + Vertex groupInstanceVertex = null; + Either<Vertex, StorageOperationStatus> groupInstanceVertexRes; + Map<String, Vertex> existingPropertyValueVertices = new HashMap<>(); + Map<String, Vertex> existingPropertyVertices = new HashMap<>(); + groupInstanceVertexRes = getVertexFromGraph(GraphPropertiesDictionary.UNIQUE_ID.getProperty(),oldGroupInstance.getUniqueId()); + try{ + if (groupInstanceVertexRes.isRight()) { + log.debug("Failed to fetch group instance vertex {} from graph. ", oldGroupInstance.getName()); + updateRes = Either.right(groupInstanceVertexRes.right().value()); + } else { + groupInstanceVertex = groupInstanceVertexRes.left().value(); + findExistingPropertyValueVertices(groupInstanceVertex, existingPropertyValueVertices); + nodeUpdateRes = handlePropertyValues(oldGroupInstance, oldGroupInstance.getPropertyValueCounter(), newProperties, groupInstanceVertex, existingPropertyValueVertices, existingPropertyVertices); + if(nodeUpdateRes.isRight()){ + log.debug("Failed to handle property values of group instance {}. ", oldGroupInstance.getName()); + updateRes = Either.right(nodeUpdateRes.right().value()); + } else { + updateRes = updateGroupInstanceVertexAndGetUpdatedGroupInstance(groupInstanceVertex, nodeUpdateRes.left().value(), oldGroupInstance); + } + } + } catch(Exception e){ + log.debug("The Exception occured during update group instance {} property values on graph. The message is {}. ", oldGroupInstance.getName(), e.getMessage(), e); + updateRes = Either.right(StorageOperationStatus.GENERAL_ERROR); + } + return updateRes; + } + + private Either<Integer, StorageOperationStatus> handlePropertyValues(GroupInstance oldGroupInstance, Integer propertyValueCounter, List<GroupInstanceProperty> newProperties, Vertex groupInstanceVertex, + Map<String, Vertex> existingPropertyValueVertices, Map<String, Vertex> existingPropertyVertices) { + + Either<Integer, StorageOperationStatus> nodeHandleRes = null; + int currCounter = propertyValueCounter; + for(GroupInstanceProperty currProperty : newProperties){ + nodeHandleRes = handlePropertyValueNode(oldGroupInstance, currCounter, currProperty, groupInstanceVertex, existingPropertyValueVertices, existingPropertyVertices); + if(nodeHandleRes.isRight()){ + break; + } + currCounter = nodeHandleRes.left().value(); + } + return nodeHandleRes; + } + + private Either<GroupInstance, StorageOperationStatus> updateGroupInstanceVertexAndGetUpdatedGroupInstance( Vertex groupInstanceVertex, Integer propertyValueCounter, GroupInstance oldGroupInstance) { + + TitanOperationStatus status; + Either<GroupInstance, StorageOperationStatus> actionResult; + status = updateGroupInstanceVertex(groupInstanceVertex, propertyValueCounter); + if(status != TitanOperationStatus.OK){ + log.debug("Failed to update group instance {}. ", oldGroupInstance.getName()); + actionResult = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + }else{ + Either<GroupInstance, TitanOperationStatus> updatedGroupInstanceRes = getGroupInstanceFromGraph(oldGroupInstance.getUniqueId(), false, false); + if(updatedGroupInstanceRes.isRight()){ + status = updatedGroupInstanceRes.right().value(); + log.debug("Failed to get updated group instance {}. Status is {}. ", oldGroupInstance.getName(), status); + actionResult = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + }else{ + actionResult = Either.left(updatedGroupInstanceRes.left().value()); + } + } + return actionResult; + } + + private Either<Integer, StorageOperationStatus> handlePropertyValueNode(GroupInstance oldGroupInstance, Integer propertyValueCounter, GroupInstanceProperty currProperty, Vertex groupInstanceVertex, Map<String, Vertex> existingPropertyValueVertices, Map<String, Vertex> existingPropertyVertices) { + + String groupInstanceName = oldGroupInstance.getName(); + TitanOperationStatus updateStatus; + TitanOperationStatus addStatus; + Vertex propertyValueVertex; + String propertyValueId; + propertyValueId = currProperty.getValueUniqueUid(); + Either<Integer, StorageOperationStatus> actionResult = null; + if(existingPropertyValueVertices.containsKey(propertyValueId)){ + updateStatus = updatePropertyValueVertex(existingPropertyValueVertices.get(propertyValueId), currProperty); + if(updateStatus != TitanOperationStatus.OK){ + log.debug("Failed to update property value {} of group instance {}. ", currProperty.getName(), groupInstanceName); + actionResult = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateStatus)); + } + } + else{ + if(MapUtils.isEmpty(existingPropertyVertices)){ + findExistingPropertyVertices(existingPropertyVertices, groupInstanceVertex); + } + propertyValueVertex = existingPropertyVertices.get(currProperty.getUniqueId()); + addStatus = addPropertyValueNodeToGroupInstance(currProperty, groupInstanceVertex, propertyValueVertex, oldGroupInstance.getUniqueId(), ++propertyValueCounter); + if(addStatus != TitanOperationStatus.OK){ + log.debug("Failed to add property value {} to group instance {}. ", currProperty.getName(), groupInstanceName); + actionResult = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(addStatus)); + } + } + if(actionResult == null){ + actionResult = Either.left(propertyValueCounter); + } + return actionResult; + } + + @SuppressWarnings("unchecked") + private Either<Vertex, StorageOperationStatus> getVertexFromGraph(String uniqueKeyName, String uniqueId) { + + Either<Vertex, StorageOperationStatus> actionResult = null; + try{ + Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph(); + Iterable<TitanVertex> vertices = null; + if (graph.isRight()) { + log.debug("Failed to get graph. Status is {}", graph.right().value()); + actionResult = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value())); + } + if(actionResult == null){ + TitanGraph tGraph = graph.left().value(); + vertices = tGraph.query().has(uniqueKeyName, uniqueId).vertices(); + if (vertices == null || vertices.iterator() == null || !vertices.iterator().hasNext()) { + log.debug("Failed to get nodes from graph for type {} for id = {}", NodeTypeEnum.GroupInstance, uniqueId); + actionResult = Either.right(StorageOperationStatus.NOT_FOUND); + } + } + if(actionResult == null && vertices != null){ + actionResult = Either.left(vertices.iterator().next()); + } + } catch(Exception e){ + log.debug("The Exception occured during get vertex {} from graph. The message is {}. ", uniqueId, e.getMessage(), e); + } + return actionResult; + } + + private void findExistingPropertyValueVertices(Vertex groupInstanceVertex, Map<String, Vertex> existingPropertyValueVertices) { + Iterator<Edge> propertyValueEdges = groupInstanceVertex.edges(Direction.OUT, GraphEdgeLabels.PROPERTY_VALUE.getProperty()); + Vertex propertyValueVertex; + while(propertyValueEdges.hasNext()){ + propertyValueVertex = propertyValueEdges.next().inVertex(); + existingPropertyValueVertices.put((String) propertyValueVertex.property(GraphPropertiesDictionary.UNIQUE_ID.getProperty()).value(), propertyValueVertex); + } + } + + private void findExistingPropertyVertices(Map<String, Vertex> existingPropertyVertices, Vertex groupInstanceVertex) { + Vertex groupVertex = groupInstanceVertex.edges(Direction.OUT, GraphEdgeLabels.INSTANCE_OF.getProperty()).next().inVertex(); + Vertex groupTypeVertex = groupVertex.edges(Direction.OUT, GraphEdgeLabels.TYPE_OF.getProperty()).next().inVertex(); + Iterator<Edge> groupTypePropertiesIterator = groupTypeVertex.edges(Direction.OUT, GraphEdgeLabels.PROPERTY.getProperty()); + while(groupTypePropertiesIterator.hasNext()){ + Vertex propertyValueVertex = groupTypePropertiesIterator.next().inVertex(); + existingPropertyVertices.put((String) propertyValueVertex.property(GraphPropertiesDictionary.UNIQUE_ID.getProperty()).value(), propertyValueVertex); + } + } + + private TitanOperationStatus addPropertyValueNodeToGroupInstance(GroupInstanceProperty currProperty, Vertex groupInstanceVertex, Vertex propertyVertex, String groupInstanceId, int index) { + TitanOperationStatus status = null; + TitanVertex propertyValueVertex = null; + PropertyValueData newPropertyValue = new PropertyValueData(); + Long creationTime = System.currentTimeMillis(); + newPropertyValue.setModificationTime(creationTime); + newPropertyValue.setCreationTime(creationTime); + newPropertyValue.setUniqueId(UniqueIdBuilder.buildGroupPropertyValueUid(groupInstanceId, index)); + newPropertyValue.setValue(currProperty.getValue()); + newPropertyValue.setType(currProperty.getType()); + Either<TitanVertex, TitanOperationStatus> propertyValueNodeRes = titanGenericDao.createNode(newPropertyValue); + if(propertyValueNodeRes.isRight()){ + status = propertyValueNodeRes.right().value(); + } + if(status == null){ + propertyValueVertex = propertyValueNodeRes.left().value(); + Map<String, Object> props = new HashMap<>(); + props.put(GraphPropertiesDictionary.PROPERTY_NAME.getProperty(), currProperty.getName()); + status = titanGenericDao.createEdge(groupInstanceVertex, propertyValueVertex, GraphEdgeLabels.PROPERTY_VALUE, props); + } + if(status == TitanOperationStatus.OK){ + status = titanGenericDao.createEdge(propertyValueVertex, propertyVertex, GraphEdgeLabels.PROPERTY_IMPL, null); + } + return status; + } + + private TitanOperationStatus updatePropertyValueVertex(Vertex propertyValueVertex, GroupInstanceProperty property) { + PropertyValueData propertyValue = new PropertyValueData(); + propertyValue.setUniqueId(property.getValue()); + propertyValue.setModificationTime(System.currentTimeMillis()); + propertyValue.setType(property.getType()); + propertyValue.setValue(property.getValue()); + return titanGenericDao.updateVertex(propertyValue, propertyValueVertex); + } + + private TitanOperationStatus updateGroupInstanceVertex(Vertex groupInstanceVertex, int propertyValueCounter) { + GroupInstanceData groupInstanceData = new GroupInstanceData(); + groupInstanceData.getGroupDataDefinition().setModificationTime(System.currentTimeMillis()); + groupInstanceData.getGroupDataDefinition().setCustomizationUUID(UUID.randomUUID().toString()); + groupInstanceData.getGroupDataDefinition().setPropertyValueCounter(propertyValueCounter); + return titanGenericDao.updateVertex(groupInstanceData, groupInstanceVertex); + } + + private Either<Map<String, PropertyValueData>, TitanOperationStatus> getAllGroupInstancePropertyValuesData(GroupInstanceData groupInstData) { + + Either<Map<String, PropertyValueData>, TitanOperationStatus> result = null; + try{ + Either<List<ImmutablePair<PropertyValueData, GraphEdge>>, TitanOperationStatus> getPropertyValueChildrenRes = + titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), groupInstData.getUniqueId(), GraphEdgeLabels.PROPERTY_VALUE, + NodeTypeEnum.PropertyValue, PropertyValueData.class, true); + if(getPropertyValueChildrenRes.isRight()){ + TitanOperationStatus status = getPropertyValueChildrenRes.right().value(); + log.debug("Failed to fetch property value nodes for group instance {}. Status is {}. ", groupInstData.getName(), status); + if(status == TitanOperationStatus.NOT_FOUND){ + result = Either.left(null); + }else{ + result = Either.right(status); + } + }else{ + result = Either.left(getPropertyValueChildrenRes.left().value().stream() + .collect(Collectors.toMap(pair->(String)(pair.getRight().getProperties().get(GraphPropertiesDictionary.PROPERTY_NAME.getProperty())), pair->pair.getLeft()))); + } + } catch(Exception e){ + log.debug("The Exception occured during fetch group instance () property values. The message is {}. ", groupInstData.getName(), e.getMessage(), e); + if(result == null){ + result = Either.right(TitanOperationStatus.GENERAL_ERROR); + } + } + return result; + } + @Override + public Either<GroupInstance, StorageOperationStatus> updateGroupInstancePropertyValues(GroupInstance groupInstance, List<GroupInstanceProperty> newProperties) { + return updateGroupInstancePropertyValues(groupInstance, newProperties, false); + } +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupOperation.java index 9312be45c1..52bcae36db 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupOperation.java @@ -25,8 +25,11 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; +import java.util.Optional; import java.util.stream.Collectors; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.math.NumberUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; @@ -44,6 +47,7 @@ import org.openecomp.sdc.be.model.GroupDefinition; import org.openecomp.sdc.be.model.GroupProperty; import org.openecomp.sdc.be.model.GroupTypeDefinition; import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; import org.openecomp.sdc.be.model.operations.api.IGroupOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; @@ -57,6 +61,7 @@ import org.openecomp.sdc.be.resources.data.PropertyValueData; import org.openecomp.sdc.be.resources.data.ResourceMetadataData; import org.openecomp.sdc.be.resources.data.ServiceMetadataData; import org.openecomp.sdc.be.resources.data.UniqueIdData; +import org.openecomp.sdc.common.datastructure.Wrapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @@ -82,15 +87,16 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation @javax.annotation.Resource private ApplicationDataTypeCache dataTypeCache; + @javax.annotation.Resource + protected ResourceOperation resourceOperation; + @Override - public Either<GroupData, TitanOperationStatus> addGroupToGraph(NodeTypeEnum nodeTypeEnum, String componentId, - GroupDefinition groupDefinition) { + public Either<GroupData, TitanOperationStatus> addGroupToGraph(NodeTypeEnum nodeTypeEnum, String componentId, GroupDefinition groupDefinition) { String groupTypeUid = groupDefinition.getTypeUid(); if (groupTypeUid == null) { - BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, "Group type id is empty", - ErrorSeverity.ERROR); + BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, "Group type id is empty", ErrorSeverity.ERROR); return Either.right(TitanOperationStatus.INVALID_ID); } @@ -112,41 +118,35 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation TitanOperationStatus status = null; // Adding group data node to graph log.debug("Before adding group to graph {}", groupData.toString()); - Either<GroupData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(groupData, - GroupData.class); + Either<GroupData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(groupData, GroupData.class); log.debug("After adding group to graph {}", groupData.toString()); if (createNodeResult.isRight()) { status = createNodeResult.right().value(); - log.error("Failed to add group {} to graph. Status is {}", groupDefinition.getName(), status); + log.error("Failed to add group {} to graph. status is {}", groupDefinition.getName(), status); return Either.right(status); } // Associate group to group type log.debug("Going to associate group {} to its groupType {}", groupDefinition.getName(), groupDefinition.getType()); - Either<GraphRelation, TitanOperationStatus> associateGroupTypeRes = associateGroupToGroupType(groupData, - groupTypeUid); - log.debug("After associating group {} to its groupType {}. Status is {}", groupDefinition.getName(), groupDefinition.getType(), associateGroupTypeRes); + Either<GraphRelation, TitanOperationStatus> associateGroupTypeRes = associateGroupToGroupType(groupData, groupTypeUid); + log.debug("After associating group {} to its groupType {}. status is {}", groupDefinition.getName(), groupDefinition.getType(), associateGroupTypeRes); if (associateGroupTypeRes.isRight()) { status = associateGroupTypeRes.right().value(); - String description = "Failed to associate group " + groupDefinition.getName() + " to its groupType " - + groupDefinition.getType() + " in graph."; + String description = "Failed to associate group " + groupDefinition.getName() + " to its groupType " + groupDefinition.getType() + " in graph."; BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR); return Either.right(status); } // Associate group to component RESOURCE/SERVICE/PRODUCT - Either<GraphRelation, TitanOperationStatus> associateComponentRes = associateGroupToComponent(groupData, - nodeTypeEnum, componentId); + Either<GraphRelation, TitanOperationStatus> associateComponentRes = associateGroupToComponent(groupData, nodeTypeEnum, componentId); if (associateComponentRes.isRight()) { status = associateComponentRes.right().value(); - String description = "Failed to associate group " + groupDefinition.getName() + " to " - + nodeTypeEnum.getName() + " " + componentId + ". status is " + status; + String description = "Failed to associate group " + groupDefinition.getName() + " to " + nodeTypeEnum.getName() + " " + componentId + ". status is " + status; BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR); return Either.right(status); } - Either<GroupTypeDefinition, TitanOperationStatus> groupTypeRes = groupTypeOperation - .getGroupTypeByUid(groupDefinition.getTypeUid()); + Either<GroupTypeDefinition, TitanOperationStatus> groupTypeRes = groupTypeOperation.getGroupTypeByUid(groupDefinition.getTypeUid()); if (groupTypeRes.isRight()) { TitanOperationStatus operationStatus = groupTypeRes.right().value(); log.debug("Failed to find group type {}", groupDefinition.getTypeUid()); @@ -164,18 +164,16 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation // points to the parent unique id // Adding properties to group - List<GroupProperty> properties = groupDefinition.getProperties(); + List<GroupProperty> properties = groupDefinition.convertToGroupProperties(); if (properties != null && false == properties.isEmpty()) { if (groupTypeProperties == null || true == groupTypeProperties.isEmpty()) { - BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP, - "group type does not have properties", ErrorSeverity.INFO); + BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP, "group type does not have properties", ErrorSeverity.INFO); return Either.right(TitanOperationStatus.MATCH_NOT_FOUND); } - Map<String, PropertyDefinition> groupTypePropertiesMap = groupTypeProperties.stream() - .collect(Collectors.toMap(p -> p.getName(), p -> p)); + Map<String, PropertyDefinition> groupTypePropertiesMap = groupTypeProperties.stream().collect(Collectors.toMap(p -> p.getName(), p -> p)); Either<PropertyValueData, TitanOperationStatus> addPropertyResult = null; int i = 1; @@ -183,10 +181,8 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation addPropertyResult = addPropertyToGroup(groupData, prop, groupTypePropertiesMap.get(prop.getName()), i); if (addPropertyResult.isRight()) { status = addPropertyResult.right().value(); - String description = "Failed to associate group " + groupData.getUniqueId() + " to property " - + prop.getName() + " in graph. Status is " + status; - BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, - ErrorSeverity.ERROR); + String description = "Failed to associate group " + groupData.getUniqueId() + " to property " + prop.getName() + " in graph. Status is " + status; + BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR); return Either.right(status); } i++; @@ -196,41 +192,22 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation // Associate artifacts to group List<String> artifacts = groupDefinition.getArtifacts(); - Either<GroupDefinition, TitanOperationStatus> associateArtifactsToGroupOnGraph = associateArtifactsToGroupOnGraph( - groupData.getGroupDataDefinition().getUniqueId(), artifacts); - if (associateArtifactsToGroupOnGraph.isRight() - && associateArtifactsToGroupOnGraph.right().value() != TitanOperationStatus.OK) { + Either<GroupDefinition, TitanOperationStatus> associateArtifactsToGroupOnGraph = associateArtifactsToGroupOnGraph(groupData.getGroupDataDefinition().getUniqueId(), artifacts); + if (associateArtifactsToGroupOnGraph.isRight() && associateArtifactsToGroupOnGraph.right().value() != TitanOperationStatus.OK) { return Either.right(status); } /* - * Either<GraphRelation, TitanOperationStatus> addArtifactsRefResult = - * null; if (artifacts != null) { for (String artifactId : artifacts) { - * Either<ArtifactData, TitanOperationStatus> findArtifactRes = - * titanGenericDao .getNode(UniqueIdBuilder - * .getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId, - * ArtifactData.class); if (findArtifactRes.isRight()) { status = - * findArtifactRes.right().value(); if (status == - * TitanOperationStatus.NOT_FOUND) { status = - * TitanOperationStatus.INVALID_ID; } String description = - * "Failed to associate group " + groupData.getUniqueId() + - * " to artifact " + artifactId + " in graph. Status is " + status; - * BeEcompErrorManager.getInstance().logInternalFlowError( ADDING_GROUP, - * description, ErrorSeverity.ERROR); return Either.right(status); } + * Either<GraphRelation, TitanOperationStatus> addArtifactsRefResult = null; if (artifacts != null) { for (String artifactId : artifacts) { Either<ArtifactData, TitanOperationStatus> findArtifactRes = titanGenericDao .getNode(UniqueIdBuilder + * .getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId, ArtifactData.class); if (findArtifactRes.isRight()) { status = findArtifactRes.right().value(); if (status == TitanOperationStatus.NOT_FOUND) { status = + * TitanOperationStatus.INVALID_ID; } String description = "Failed to associate group " + groupData.getUniqueId() + " to artifact " + artifactId + " in graph. Status is " + status; BeEcompErrorManager.getInstance().logInternalFlowError( + * ADDING_GROUP, description, ErrorSeverity.ERROR); return Either.right(status); } * - * Map<String, Object> props = new HashMap<String, Object>(); - * props.put(GraphPropertiesDictionary.NAME.getProperty(), - * findArtifactRes.left().value().getLabel()); + * Map<String, Object> props = new HashMap<String, Object>(); props.put(GraphPropertiesDictionary.NAME.getProperty(), findArtifactRes.left().value().getLabel()); * - * addArtifactsRefResult = titanGenericDao.createRelation( groupData, - * findArtifactRes.left().value(), GraphEdgeLabels.GROUP_ARTIFACT_REF, - * props); + * addArtifactsRefResult = titanGenericDao.createRelation( groupData, findArtifactRes.left().value(), GraphEdgeLabels.GROUP_ARTIFACT_REF, props); * - * if (addArtifactsRefResult.isRight()) { status = - * addArtifactsRefResult.right().value(); String description = - * "Failed to associate group " + groupData.getUniqueId() + - * " to artifact " + artifactId + " in graph. Status is " + status; - * BeEcompErrorManager.getInstance().logInternalFlowError( ADDING_GROUP, - * description, ErrorSeverity.ERROR); return Either.right(status); } } } + * if (addArtifactsRefResult.isRight()) { status = addArtifactsRefResult.right().value(); String description = "Failed to associate group " + groupData.getUniqueId() + " to artifact " + artifactId + " in graph. Status is " + status; + * BeEcompErrorManager.getInstance().logInternalFlowError( ADDING_GROUP, description, ErrorSeverity.ERROR); return Either.right(status); } } } */ // Associate group to members @@ -243,31 +220,24 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation if (member.getValue() == null || member.getValue().isEmpty()) { continue; } - Either<ComponentInstanceData, TitanOperationStatus> findComponentInstanceRes = titanGenericDao.getNode( - UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), member.getValue(), - ComponentInstanceData.class); + Either<ComponentInstanceData, TitanOperationStatus> findComponentInstanceRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), member.getValue(), ComponentInstanceData.class); if (findComponentInstanceRes.isRight()) { status = findComponentInstanceRes.right().value(); if (status == TitanOperationStatus.NOT_FOUND) { status = TitanOperationStatus.INVALID_ID; } - String description = "Failed to find to find member of group " + member.getValue() - + " in graph. Status is " + status; - BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, - ErrorSeverity.ERROR); + String description = "Failed to find to find member of group " + member.getValue() + " in graph. Status is " + status; + BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR); return Either.right(status); } Map<String, Object> props = new HashMap<String, Object>(); props.put(GraphPropertiesDictionary.NAME.getProperty(), member.getKey()); - addMembersRefResult = titanGenericDao.createRelation(groupData, findComponentInstanceRes.left().value(), - GraphEdgeLabels.GROUP_MEMBER, props); + addMembersRefResult = titanGenericDao.createRelation(groupData, findComponentInstanceRes.left().value(), GraphEdgeLabels.GROUP_MEMBER, props); if (addMembersRefResult.isRight()) { status = addMembersRefResult.right().value(); - String description = "Failed to associate group " + groupData.getUniqueId() - + " to component instance " + member.getValue() + " in graph. Status is " + status; - BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, - ErrorSeverity.ERROR); + String description = "Failed to associate group " + groupData.getUniqueId() + " to component instance " + member.getValue() + " in graph. Status is " + status; + BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR); return Either.right(status); } } @@ -275,8 +245,221 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation return Either.left(groupData); } + + private Either<PropertyDefinition, TitanOperationStatus> getPropertyDefFromGroupType(GroupProperty groupProperty) { + Either<PropertyDefinition, TitanOperationStatus> ret; + Either<GroupTypeDefinition, TitanOperationStatus> groupTypeRes = groupTypeOperation + .getGroupTypeByUid(groupProperty.getParentUniqueId()); + if (groupTypeRes.isRight()) { + TitanOperationStatus operationStatus = groupTypeRes.right().value(); + log.debug("Failed to find group type {}", groupProperty.getParentUniqueId()); + if (operationStatus == TitanOperationStatus.NOT_FOUND) { + ret = Either.right(TitanOperationStatus.INVALID_ID); + } else { + ret = Either.right(operationStatus); + } + } else { + GroupTypeDefinition groupTypeDefinition = groupTypeRes.left().value(); + List<PropertyDefinition> groupTypeProperties = groupTypeDefinition.getProperties(); + + Map<String, PropertyDefinition> groupTypePropertiesMap = groupTypeProperties.stream() + .collect(Collectors.toMap(p -> p.getName(), p -> p)); + if (groupTypeProperties == null || true == groupTypeProperties.isEmpty()) { + BeEcompErrorManager.getInstance().logInvalidInputError(ADDING_GROUP, + "group type does not have properties", ErrorSeverity.INFO); + ret = Either.right(TitanOperationStatus.MATCH_NOT_FOUND); + } else { + PropertyDefinition propertyDefinition = groupTypePropertiesMap.get(groupProperty.getName()); + ret = Either.left(propertyDefinition); + } + } + return ret; + } + + /** + * Updates GroupProperty Value + * @param componentId TODO + * @param groupId TODO + * @param groupProperties + * @param inTransaction TODO + * + * @return + */ + public Either<List<GroupProperty>, StorageOperationStatus> updateGroupProperties(String componentId, + String groupId, List<GroupProperty> groupProperties, boolean inTransaction) { + + Wrapper<Long> lastUpdateTimeWrapper = new Wrapper<>(); + TitanOperationStatus titanStatus = TitanOperationStatus.OK; + Either<List<GroupProperty>, StorageOperationStatus> result = null; + //Get Group Data + final GroupData groupData; + Either<GroupData, TitanOperationStatus> eitherGroupData = titanGenericDao + .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupId, GroupData.class); + if( eitherGroupData.isRight() ){ + log.debug("Error: Could not fetch group with groupId = {}", groupId); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherGroupData.right().value())); + } + else{ + groupData = eitherGroupData.left().value(); + } + + try { + Optional<TitanOperationStatus> optionalError = + //Stream of group properties to be updated + groupProperties.stream(). + //updating each property and mapping to the TitanOperationStatus + map(e -> updateGroupProperty(e, groupData, lastUpdateTimeWrapper)). + //filtering in errors if there are such + filter( e -> e != TitanOperationStatus.OK). + //collect + findFirst(); + if( optionalError.isPresent() ){ + titanStatus = optionalError.get(); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus)); + } + else{ + result = updateLastModificationTimeOnVf(componentId, groupId, groupProperties, lastUpdateTimeWrapper); + } + + } + finally { + handleTransactionCommitRollback(inTransaction, result); + } + + return result; + } + + private Either<List<GroupProperty>, StorageOperationStatus> updateLastModificationTimeOnVf(String componentId, + String groupId, List<GroupProperty> groupProperties, Wrapper<Long> lastUpdateTimeWrapper) { + Either<List<GroupProperty>, StorageOperationStatus> result; + Either<Resource, StorageOperationStatus> eitherResource = resourceOperation.getResource(componentId); + if( eitherResource.isRight() ){ + result = Either.right(eitherResource.right().value()); + } + else{ + Either<ComponentMetadataData, StorageOperationStatus> eitherLastUpdateDateUpdatedOnResource = resourceOperation + .updateComponentLastUpdateDateOnGraph(eitherResource.left().value(), NodeTypeEnum.Resource, + lastUpdateTimeWrapper.getInnerElement(), true); + if (eitherLastUpdateDateUpdatedOnResource.isLeft()) { + + groupProperties = + //Group Stream From VF + eitherResource.left().value().getGroups().stream(). + //Filter in Only the relevant group + filter( e -> e.getUniqueId().equals(groupId)). + //Get it + findAny().get(). + //Get Group Properties from it + convertToGroupProperties(); + + result = Either.left(groupProperties); + } + else{ + result = Either.right(eitherLastUpdateDateUpdatedOnResource.right().value()); + } + } + return result; + } + + + private TitanOperationStatus updateGroupProperty(GroupProperty groupProperty, GroupData groupData, + Wrapper<Long> lastUpdateTimeWrapper) { + TitanOperationStatus titanStatus = TitanOperationStatus.OK; + // PropertyValueData node does not exist + if (StringUtils.isEmpty(groupProperty.getValueUniqueUid())) { + // create new node + if (!StringUtils.isEmpty(groupProperty.getValue())) { + // Value does not exit and was not updated as well. no need + // to do anything + } else { + titanStatus = addGroupPropertyToGraph(groupProperty, groupData, lastUpdateTimeWrapper); - private Either<PropertyValueData, TitanOperationStatus> addPropertyToGroup(GroupData groupData, + } + } + + else { + titanStatus = updateGroupPropertyInGraph(groupProperty, lastUpdateTimeWrapper); + } + return titanStatus; + } + + private TitanOperationStatus updateGroupPropertyInGraph(GroupProperty groupProperty, + Wrapper<Long> lastUpdateTimeWrapper) { + TitanOperationStatus titanStatus; + Either<PropertyValueData, TitanOperationStatus> eitherGroupPropertyValue = titanGenericDao.getNode( + UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PropertyValue), groupProperty.getValueUniqueUid(), + PropertyValueData.class); + if (eitherGroupPropertyValue.isRight()) { + + titanStatus = eitherGroupPropertyValue.right().value(); + + } else { + PropertyValueData groupPropertyValue = eitherGroupPropertyValue.left().value(); + // Actual Update only if value changed + if (!StringUtils.equals(groupPropertyValue.getValue(), groupProperty.getValue())) { + long modificationTime = lastUpdateTimeWrapper.isEmpty() ? System.currentTimeMillis() + : lastUpdateTimeWrapper.getInnerElement(); + groupPropertyValue.setValue(groupProperty.getValue()); + groupPropertyValue.setModificationTime(modificationTime); + Either<PropertyValueData, TitanOperationStatus> eitherUpdateNode = titanGenericDao + .updateNode(groupPropertyValue, PropertyValueData.class); + if( eitherUpdateNode.isLeft() ){ + titanStatus = TitanOperationStatus.OK; + lastUpdateTimeWrapper.setInnerElement(modificationTime); + } + else{ + titanStatus = eitherUpdateNode.right().value(); + } + + } else { + titanStatus = TitanOperationStatus.OK; + } + } + return titanStatus; + } + + private TitanOperationStatus addGroupPropertyToGraph(GroupProperty groupProperty, GroupData groupData, + Wrapper<Long> lastUpdateTimeWrapper) { + PropertyDefinition propertyDefinition = null; + TitanOperationStatus ret = TitanOperationStatus.OK; + if (ret == TitanOperationStatus.OK) { + Either<PropertyDefinition, TitanOperationStatus> eitherPropertyDefFromGroupType = getPropertyDefFromGroupType( + groupProperty); + if (eitherPropertyDefFromGroupType.isRight()) { + log.debug("Error: Could not fetch group property from group Type with groupTypeId = {}", + groupProperty.getParentUniqueId()); + ret = eitherPropertyDefFromGroupType.right().value(); + } else { + propertyDefinition = eitherPropertyDefFromGroupType.left().value(); + } + } + if (ret == TitanOperationStatus.OK){ + final int groupPropCounter = groupData.getGroupDataDefinition().getPropertyValueCounter() + NumberUtils.INTEGER_ONE; + Either<PropertyValueData, TitanOperationStatus> eitherAddPropertyToGroup = addPropertyToGroup(groupData, + groupProperty, propertyDefinition, groupPropCounter); + + if( eitherAddPropertyToGroup.isLeft() ){ + ret = TitanOperationStatus.OK; + if( lastUpdateTimeWrapper.isEmpty() ){ + lastUpdateTimeWrapper.setInnerElement(eitherAddPropertyToGroup.left().value().getCreationTime()); + } + } + else{ + ret = eitherAddPropertyToGroup.right().value(); + } + if( ret == TitanOperationStatus.OK){ + groupData.getGroupDataDefinition().setPropertyValueCounter(groupPropCounter); + Either<GroupData, TitanOperationStatus> updateNode = titanGenericDao .updateNode(groupData, GroupData.class); + if( updateNode.isRight() ){ + ret = updateNode.right().value(); + } + } + + } + return ret; + } + + public Either<PropertyValueData, TitanOperationStatus> addPropertyToGroup(GroupData groupData, GroupProperty groupProperty, PropertyDefinition prop, Integer index) { if (prop == null) { @@ -312,15 +495,13 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); if (allDataTypes.isRight()) { TitanOperationStatus status = allDataTypes.right().value(); - BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToGroup", - "Failed to add property to group. Status is " + status, ErrorSeverity.ERROR); + BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToGroup", "Failed to add property to group. Status is " + status, ErrorSeverity.ERROR); return Either.right(status); } log.debug("Before validateAndUpdatePropertyValue"); - Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, - innerType, allDataTypes.left().value()); + Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes.left().value()); log.debug("After validateAndUpdatePropertyValue. isValid = {}", isValid); String newValue = value; @@ -341,9 +522,8 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation propertyValueData.setUniqueId(uniqueId); propertyValueData.setValue(newValue); - log.debug("Before adding property value to graph {}",propertyValueData); - Either<PropertyValueData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(propertyValueData, - PropertyValueData.class); + log.debug("Before adding property value to graph {}", propertyValueData); + Either<PropertyValueData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(propertyValueData, PropertyValueData.class); log.debug("After adding property value to graph {}", propertyValueData); if (createNodeResult.isRight()) { @@ -351,24 +531,20 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation return Either.right(operationStatus); } - Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(propertyValueData, - propertyData, GraphEdgeLabels.PROPERTY_IMPL, null); + Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(propertyValueData, propertyData, GraphEdgeLabels.PROPERTY_IMPL, null); if (createRelResult.isRight()) { TitanOperationStatus operationStatus = createRelResult.right().value(); - String description = "Failed to associate property value " + uniqueId + " to property " + propertyId - + " in graph. status is " + operationStatus; + String description = "Failed to associate property value " + uniqueId + " to property " + propertyId + " in graph. status is " + operationStatus; BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR); return Either.right(operationStatus); } - createRelResult = titanGenericDao.createRelation(groupData, propertyValueData, GraphEdgeLabels.PROPERTY_VALUE, - null); + createRelResult = titanGenericDao.createRelation(groupData, propertyValueData, GraphEdgeLabels.PROPERTY_VALUE, null); if (createRelResult.isRight()) { TitanOperationStatus operationStatus = createNodeResult.right().value(); - String description = "Failed to associate group " + groupData.getGroupDataDefinition().getName() - + " to property value " + uniqueId + " in graph. Status is " + operationStatus; + String description = "Failed to associate group " + groupData.getGroupDataDefinition().getName() + " to property value " + uniqueId + " in graph. Status is " + operationStatus; BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR); return Either.right(operationStatus); } @@ -376,16 +552,14 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation return Either.left(createNodeResult.left().value()); } - private Either<GraphRelation, TitanOperationStatus> associateGroupToComponent(GroupData groupData, - NodeTypeEnum nodeTypeEnum, String componentId) { + private Either<GraphRelation, TitanOperationStatus> associateGroupToComponent(GroupData groupData, NodeTypeEnum nodeTypeEnum, String componentId) { UniqueIdData componentIdData = new UniqueIdData(nodeTypeEnum, componentId); - log.debug("Before associating component {} to group {}.", componentId, groupData); + log.debug("Before associating component {} to group {}", componentId, groupData); Map<String, Object> props = new HashMap<String, Object>(); props.put(GraphPropertiesDictionary.NAME.getProperty(), groupData.getGroupDataDefinition().getName()); - Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(componentIdData, - groupData, GraphEdgeLabels.GROUP, props); - log.debug("After associating component {} to group {}. Status is {}", componentId, groupData, createRelResult); + Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(componentIdData, groupData, GraphEdgeLabels.GROUP, props); + log.debug("After associating component {} to group {}. status is {}", componentId, groupData, createRelResult); if (createRelResult.isRight()) { TitanOperationStatus operationStatus = createRelResult.right().value(); log.debug("Failed to associate component {} to group {} in graph. Status is {}", componentId, groupData, operationStatus); @@ -395,18 +569,13 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation return Either.left(createRelResult.left().value()); } - private Either<GraphRelation, TitanOperationStatus> associateGroupToGroupType(GroupData groupData, - String groupTypeUid) { + private Either<GraphRelation, TitanOperationStatus> associateGroupToGroupType(GroupData groupData, String groupTypeUid) { UniqueIdData groupTypeIdData = new UniqueIdData(NodeTypeEnum.GroupType, groupTypeUid); - log.debug("Before associating {} to group type {} (uid = {}).", groupData, groupData.getGroupDataDefinition().getType(), groupTypeUid); - Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(groupData, - groupTypeIdData, GraphEdgeLabels.TYPE_OF, null); - - if (log.isDebugEnabled()) { - log.debug("After associating {} to group type {} (uid = {}). Result is {}", groupData, groupData.getGroupDataDefinition().getType(), groupTypeUid, createRelResult); - } + log.debug("Before associating {} to group type {} (uid = {})", groupData, groupData.getGroupDataDefinition().getType(), groupTypeUid); + Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(groupData, groupTypeIdData, GraphEdgeLabels.TYPE_OF, null); + log.debug("After associating {} to group type {} (uid = {}). Result is {}", groupData, groupData.getGroupDataDefinition().getType(), groupTypeUid, createRelResult); if (createRelResult.isRight()) { TitanOperationStatus operationStatus = createRelResult.right().value(); return Either.right(operationStatus); @@ -415,19 +584,16 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation } @Override - public Either<GroupDefinition, StorageOperationStatus> addGroup(NodeTypeEnum nodeTypeEnum, String componentId, - GroupDefinition groupDefinition) { + public Either<GroupDefinition, StorageOperationStatus> addGroup(NodeTypeEnum nodeTypeEnum, String componentId, GroupDefinition groupDefinition) { return addGroup(nodeTypeEnum, componentId, groupDefinition, false); } @Override - public Either<GroupDefinition, StorageOperationStatus> addGroup(NodeTypeEnum nodeTypeEnum, String componentId, - GroupDefinition groupDefinition, boolean inTransaction) { + public Either<GroupDefinition, StorageOperationStatus> addGroup(NodeTypeEnum nodeTypeEnum, String componentId, GroupDefinition groupDefinition, boolean inTransaction) { Either<GroupDefinition, StorageOperationStatus> result = null; try { - Either<GroupData, TitanOperationStatus> addGroupRes = addGroupToGraph(nodeTypeEnum, componentId, - groupDefinition); + Either<GroupData, TitanOperationStatus> addGroupRes = addGroupToGraph(nodeTypeEnum, componentId, groupDefinition); if (addGroupRes.isRight()) { TitanOperationStatus status = addGroupRes.right().value(); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); @@ -506,52 +672,6 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation } /** - * get the list of artifacts related to a given group - * - * @param groupUniqueId - * @return - */ - // private Either<List<String>, TitanOperationStatus> getGroupArtifacts( - // String groupUniqueId) { - // - // Either<List<String>, TitanOperationStatus> result = null; - // - // Either<List<ImmutablePair<ArtifactData, GraphEdge>>, - // TitanOperationStatus> childrenNodes = titanGenericDao - // .getChildrenNodes( - // UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), - // groupUniqueId, GraphEdgeLabels.GROUP_ARTIFACT_REF, - // NodeTypeEnum.ArtifactRef, ArtifactData.class); - // if (childrenNodes.isRight()) { - // TitanOperationStatus status = childrenNodes.right().value(); - // if (status == TitanOperationStatus.NOT_FOUND) { - // status = TitanOperationStatus.OK; - // } - // result = Either.right(status); - // - // } else { - // - // List<String> artifactsList = new ArrayList<>(); - // List<ImmutablePair<ArtifactData, GraphEdge>> list = childrenNodes - // .left().value(); - // if (list != null) { - // for (ImmutablePair<ArtifactData, GraphEdge> pair : list) { - // ArtifactData artifactData = pair.getKey(); - // String uniqueId = artifactData.getArtifactDataDefinition() - // .getUniqueId(); - // artifactsList.add(uniqueId); - // } - // } - // - // log.debug("The artifacts list related to group {} is {}", groupUniqueId, artifactsList); - // result = Either.left(artifactsList); - // } - // - // return result; - // - // } - - /** * get members of group * * @param groupUniqueId @@ -561,9 +681,8 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation Either<Map<String, String>, TitanOperationStatus> result = null; - Either<List<ImmutablePair<ComponentInstanceData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao - .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupUniqueId, - GraphEdgeLabels.GROUP_MEMBER, NodeTypeEnum.ResourceInstance, ComponentInstanceData.class); + Either<List<ImmutablePair<ComponentInstanceData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupUniqueId, GraphEdgeLabels.GROUP_MEMBER, + NodeTypeEnum.ResourceInstance, ComponentInstanceData.class); if (childrenNodes.isRight()) { TitanOperationStatus status = childrenNodes.right().value(); @@ -594,23 +713,20 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation public Either<GroupTypeDefinition, TitanOperationStatus> getGroupTypeOfGroup(String groupUniqueId) { - Either<ImmutablePair<GroupTypeData, GraphEdge>, TitanOperationStatus> groupTypeRes = titanGenericDao.getChild( - UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupUniqueId, GraphEdgeLabels.TYPE_OF, - NodeTypeEnum.GroupType, GroupTypeData.class); + Either<ImmutablePair<GroupTypeData, GraphEdge>, TitanOperationStatus> groupTypeRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupUniqueId, GraphEdgeLabels.TYPE_OF, NodeTypeEnum.GroupType, + GroupTypeData.class); if (groupTypeRes.isRight()) { TitanOperationStatus status = groupTypeRes.right().value(); log.debug("Cannot find group type associated with capability {}. Status is {}", groupUniqueId, status); - BeEcompErrorManager.getInstance().logBeFailedFindAssociationError("Fetch Group type", - NodeTypeEnum.GroupType.getName(), groupUniqueId, String.valueOf(status)); + BeEcompErrorManager.getInstance().logBeFailedFindAssociationError("Fetch Group type", NodeTypeEnum.GroupType.getName(), groupUniqueId, String.valueOf(status)); return Either.right(groupTypeRes.right().value()); } GroupTypeData groupTypeData = groupTypeRes.left().value().getKey(); - Either<GroupTypeDefinition, TitanOperationStatus> groupTypeByUid = groupTypeOperation - .getGroupTypeByUid(groupTypeData.getGroupTypeDataDefinition().getUniqueId()); + Either<GroupTypeDefinition, TitanOperationStatus> groupTypeByUid = groupTypeOperation.getGroupTypeByUid(groupTypeData.getGroupTypeDataDefinition().getUniqueId()); return groupTypeByUid; @@ -644,19 +760,16 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation return Either.right(TitanOperationStatus.OK); } - Map<String, PropertyDefinition> uidToPropDefMap = groupTypeProperties.stream() - .collect(Collectors.toMap(p -> p.getUniqueId(), p -> p)); + Map<String, PropertyDefinition> uidToPropDefMap = groupTypeProperties.stream().collect(Collectors.toMap(p -> p.getUniqueId(), p -> p)); // Find all properties values on the group - Either<List<ImmutablePair<PropertyValueData, GraphEdge>>, TitanOperationStatus> propertyImplNodes = titanGenericDao - .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupUid, - GraphEdgeLabels.PROPERTY_VALUE, NodeTypeEnum.PropertyValue, PropertyValueData.class); + Either<List<ImmutablePair<PropertyValueData, GraphEdge>>, TitanOperationStatus> propertyImplNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupUid, GraphEdgeLabels.PROPERTY_VALUE, + NodeTypeEnum.PropertyValue, PropertyValueData.class); if (propertyImplNodes.isRight()) { TitanOperationStatus status = propertyImplNodes.right().value(); if (status == TitanOperationStatus.NOT_FOUND) { - groupPropertiesList = groupTypeProperties.stream() - .map(p -> new GroupProperty(p, p.getDefaultValue(), null)).collect(Collectors.toList()); + groupPropertiesList = groupTypeProperties.stream().map(p -> new GroupProperty(p, p.getDefaultValue(), null)).collect(Collectors.toList()); return Either.left(groupPropertiesList); } else { return Either.right(status); @@ -676,9 +789,8 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation String propertyValueUid = propertyValueData.getUniqueId(); String value = propertyValueData.getValue(); - Either<ImmutablePair<PropertyData, GraphEdge>, TitanOperationStatus> propertyDefRes = titanGenericDao - .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PropertyValue), propertyValueUid, - GraphEdgeLabels.PROPERTY_IMPL, NodeTypeEnum.Property, PropertyData.class); + Either<ImmutablePair<PropertyData, GraphEdge>, TitanOperationStatus> propertyDefRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PropertyValue), propertyValueUid, GraphEdgeLabels.PROPERTY_IMPL, + NodeTypeEnum.Property, PropertyData.class); if (propertyDefRes.isRight()) { TitanOperationStatus status = propertyDefRes.right().value(); if (status == TitanOperationStatus.NOT_FOUND) { @@ -704,8 +816,7 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation // Find all properties which does not have property value on the group. List<GroupProperty> leftProps = groupTypeProperties.stream() // filter out the group type properties which already processed - .filter(p -> false == processedProps.contains(p.getUniqueId())) - .map(p -> new GroupProperty(p, p.getDefaultValue(), null)).collect(Collectors.toList()); + .filter(p -> false == processedProps.contains(p.getUniqueId())).map(p -> new GroupProperty(p, p.getDefaultValue(), null)).collect(Collectors.toList()); if (leftProps != null) { groupPropertiesList.addAll(leftProps); } @@ -713,28 +824,24 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation return Either.left(groupPropertiesList); } - public Either<List<GroupDefinition>, TitanOperationStatus> getAllGroupsFromGraph(String componentId, - NodeTypeEnum componentTypeEnum) { + public Either<List<GroupDefinition>, TitanOperationStatus> getAllGroupsFromGraph(String componentId, NodeTypeEnum componentTypeEnum) { return getAllGroupsFromGraph(componentId, componentTypeEnum, false, false, false); } @Override - public Either<List<GroupDefinition>, StorageOperationStatus> getAllGroups(String componentId, - NodeTypeEnum compTypeEnum, boolean inTransaction) { + public Either<List<GroupDefinition>, StorageOperationStatus> getAllGroups(String componentId, NodeTypeEnum compTypeEnum, boolean inTransaction) { Either<List<GroupDefinition>, StorageOperationStatus> result = null; try { - Either<List<GroupDefinition>, TitanOperationStatus> allGroups = this.getAllGroupsFromGraph(componentId, - compTypeEnum); + Either<List<GroupDefinition>, TitanOperationStatus> allGroups = this.getAllGroupsFromGraph(componentId, compTypeEnum); if (allGroups.isRight()) { TitanOperationStatus status = allGroups.right().value(); - log.debug("Failed to retrieve all groups of component {} from graph. Status is {}", componentId, - status); + log.debug("Failed to retrieve all groups of component {} from graph. Status is {}", componentId, status); if (status == TitanOperationStatus.NOT_FOUND) { status = TitanOperationStatus.OK; } @@ -762,8 +869,7 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation } @Override - public Either<List<GroupDefinition>, StorageOperationStatus> getAllGroups(String componentId, - NodeTypeEnum compTypeEnum) { + public Either<List<GroupDefinition>, StorageOperationStatus> getAllGroups(String componentId, NodeTypeEnum compTypeEnum) { return getAllGroups(componentId, compTypeEnum, false); } @@ -778,27 +884,21 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation GroupDefinition groupDefinition = groupFromGraph.left().value(); // 1. delete all properties values nodes - List<GroupProperty> properties = groupDefinition.getProperties(); + List<GroupProperty> properties = groupDefinition.convertToGroupProperties(); if (properties != null) { for (GroupProperty groupProperty : properties) { String propValueUniqueId = groupProperty.getValueUniqueUid(); if (propValueUniqueId != null) { UniqueIdData uniqueIdData = new UniqueIdData(NodeTypeEnum.PropertyValue, propValueUniqueId); - Either<PropertyValueData, TitanOperationStatus> deleteNode = titanGenericDao - .deleteNode(uniqueIdData, PropertyValueData.class); + Either<PropertyValueData, TitanOperationStatus> deleteNode = titanGenericDao.deleteNode(uniqueIdData, PropertyValueData.class); if (deleteNode.isRight()) { TitanOperationStatus status = groupFromGraph.right().value(); - String description = String.format( - "Failed to delete property {} under group {}" + groupUniqueId - + " on graph. Status is {}", - propValueUniqueId, groupDefinition.getName(), status.name()); - log.debug(description); - BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError(DELETING_GROUP, propValueUniqueId, - status.name()); + log.debug("Failed to delete property {} under group {} {} on graph. Status is {}", propValueUniqueId, groupDefinition.getName(), groupUniqueId, status.name()); + BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError(DELETING_GROUP, propValueUniqueId, status.name()); return Either.right(status); } else { - log.trace("Property {} was deleted from geoup {}", propValueUniqueId, groupDefinition.getName()); + log.trace("Property {} was deleted from group {}" ,propValueUniqueId, groupDefinition.getName()); } } } @@ -809,10 +909,7 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation Either<GroupData, TitanOperationStatus> deleteNode = titanGenericDao.deleteNode(uniqueIdData, GroupData.class); if (deleteNode.isRight()) { TitanOperationStatus status = groupFromGraph.right().value(); - String description = String.format( - "Failed to delete group {} with uid " + groupUniqueId + " on graph. Status is {}", - groupDefinition.getName(), groupUniqueId, status.name()); - log.debug(description); + log.debug("Failed to delete group {} with uid {} on graph. Status is {}", groupDefinition.getName(), groupUniqueId, status.name()); BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError(DELETING_GROUP, groupUniqueId, status.name()); return Either.right(status); } else { @@ -863,18 +960,15 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation } @Override - public Either<List<GroupDefinition>, TitanOperationStatus> deleteAllGroupsFromGraph(String componentId, - NodeTypeEnum componentTypeEnum) { + public Either<List<GroupDefinition>, TitanOperationStatus> deleteAllGroupsFromGraph(String componentId, NodeTypeEnum componentTypeEnum) { - Either<List<ImmutablePair<GroupData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao - .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(componentTypeEnum), componentId, - GraphEdgeLabels.GROUP, NodeTypeEnum.Group, GroupData.class); + Either<List<ImmutablePair<GroupData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(componentTypeEnum), componentId, GraphEdgeLabels.GROUP, NodeTypeEnum.Group, + GroupData.class); if (childrenNodes.isRight()) { TitanOperationStatus status = childrenNodes.right().value(); if (status != TitanOperationStatus.NOT_FOUND) { - BeEcompErrorManager.getInstance().logBeFailedFindAllNodesError(DELETING_ALL_GROUPS, - NodeTypeEnum.Group.name(), componentId, status.name()); + BeEcompErrorManager.getInstance().logBeFailedFindAllNodesError(DELETING_ALL_GROUPS, NodeTypeEnum.Group.name(), componentId, status.name()); } return Either.right(status); } @@ -888,8 +982,7 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation Either<GroupData, TitanOperationStatus> deleteGroupFromGraph = deleteGroupFromGraph(uniqueId); if (deleteGroupFromGraph.isRight()) { TitanOperationStatus status = deleteGroupFromGraph.right().value(); - BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError(DELETING_ALL_GROUPS, uniqueId, - status.name()); + BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError(DELETING_ALL_GROUPS, uniqueId, status.name()); return Either.right(status); } GroupData groupData = deleteGroupFromGraph.left().value(); @@ -902,15 +995,13 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation } @Override - public Either<List<GroupDefinition>, StorageOperationStatus> deleteAllGroups(String componentId, - NodeTypeEnum compTypeEnum, boolean inTransaction) { + public Either<List<GroupDefinition>, StorageOperationStatus> deleteAllGroups(String componentId, NodeTypeEnum compTypeEnum, boolean inTransaction) { Either<List<GroupDefinition>, StorageOperationStatus> result = null; try { - Either<List<GroupDefinition>, TitanOperationStatus> allGroups = this.deleteAllGroupsFromGraph(componentId, - compTypeEnum); + Either<List<GroupDefinition>, TitanOperationStatus> allGroups = this.deleteAllGroupsFromGraph(componentId, compTypeEnum); if (allGroups.isRight()) { TitanOperationStatus status = allGroups.right().value(); @@ -942,14 +1033,11 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation } @Override - public Either<List<GroupDefinition>, StorageOperationStatus> deleteAllGroups(String componentId, - NodeTypeEnum compTypeEnum) { + public Either<List<GroupDefinition>, StorageOperationStatus> deleteAllGroups(String componentId, NodeTypeEnum compTypeEnum) { return deleteAllGroups(componentId, compTypeEnum, false); } - public Either<List<GroupDefinition>, StorageOperationStatus> prepareGroupsForCloning( - org.openecomp.sdc.be.model.Component origResource, - ImmutablePair<List<ComponentInstance>, Map<String, String>> cloneInstances) { + public Either<List<GroupDefinition>, StorageOperationStatus> prepareGroupsForCloning(org.openecomp.sdc.be.model.Component origResource, ImmutablePair<List<ComponentInstance>, Map<String, String>> cloneInstances) { List<GroupDefinition> groupsToCreate = new ArrayList<>(); Either<List<GroupDefinition>, StorageOperationStatus> result = Either.left(groupsToCreate); @@ -966,19 +1054,18 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation gdToCreate.setUniqueId(null); gdToCreate.setMembers(null); - List<GroupProperty> properties = groupDefinition.getProperties(); + List<GroupProperty> properties = groupDefinition.convertToGroupProperties(); if (properties != null) { // Take properties which was updated in the // group(getValueUniqueUid != null), // Then set null instead of the value(prepare for the // creation). - List<GroupProperty> propertiesToUpdate = properties.stream() - .filter(p -> p.getValueUniqueUid() != null).map(p -> { - p.setValueUniqueUid(null); - return p; - }).collect(Collectors.toList()); + List<GroupProperty> propertiesToUpdate = properties.stream().filter(p -> p.getValueUniqueUid() != null).map(p -> { + p.setValueUniqueUid(null); + return p; + }).collect(Collectors.toList()); - gdToCreate.setProperties(propertiesToUpdate); + gdToCreate.convertFromGroupProperties(propertiesToUpdate); } @@ -988,8 +1075,7 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation Map<String, String> oldCompUidToNew = cloneInstances.right; if (members != null && createdInstances != null) { - Map<String, String> compInstIdToName = createdInstances.stream() - .collect(Collectors.toMap(p -> p.getUniqueId(), p -> p.getName())); + Map<String, String> compInstIdToName = createdInstances.stream().collect(Collectors.toMap(p -> p.getUniqueId(), p -> p.getName())); Map<String, String> membersToCreate = new HashMap<>(); @@ -1018,8 +1104,7 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation } @Override - public Either<List<GroupDefinition>, StorageOperationStatus> addGroups(NodeTypeEnum nodeTypeEnum, - String componentId, List<GroupDefinition> groups, boolean inTransaction) { + public Either<List<GroupDefinition>, StorageOperationStatus> addGroups(NodeTypeEnum nodeTypeEnum, String componentId, List<GroupDefinition> groups, boolean inTransaction) { List<GroupDefinition> createdGroups = new ArrayList<>(); @@ -1029,8 +1114,7 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation if (groups != null) { for (GroupDefinition groupDefinition : groups) { - Either<GroupDefinition, StorageOperationStatus> addGroup = this.addGroup(nodeTypeEnum, componentId, - groupDefinition, true); + Either<GroupDefinition, StorageOperationStatus> addGroup = this.addGroup(nodeTypeEnum, componentId, groupDefinition, true); if (addGroup.isRight()) { StorageOperationStatus status = addGroup.right().value(); result = Either.right(status); @@ -1059,29 +1143,25 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation } @Override - public Either<List<String>, TitanOperationStatus> getAssociatedGroupsToComponentInstanceFromGraph( - String componentInstanceId) { + public Either<List<String>, TitanOperationStatus> getAssociatedGroupsToComponentInstanceFromGraph(String componentInstanceId) { List<String> groups = new ArrayList<>(); Either<List<String>, TitanOperationStatus> result = Either.left(groups); - Either<List<ImmutablePair<GroupData, GraphEdge>>, TitanOperationStatus> parentNodes = titanGenericDao - .getParentNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), componentInstanceId, - GraphEdgeLabels.GROUP_MEMBER, NodeTypeEnum.Group, GroupData.class); + Either<List<ImmutablePair<GroupData, GraphEdge>>, TitanOperationStatus> parentNodes = titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), componentInstanceId, GraphEdgeLabels.GROUP_MEMBER, + NodeTypeEnum.Group, GroupData.class); if (parentNodes.isRight()) { TitanOperationStatus status = parentNodes.right().value(); if (status != TitanOperationStatus.NOT_FOUND) { - BeEcompErrorManager.getInstance().logBeFailedFindParentError("FetchGroupMembers", componentInstanceId, - status.name()); + BeEcompErrorManager.getInstance().logBeFailedFindParentError("FetchGroupMembers", componentInstanceId, status.name()); } return Either.right(status); } List<ImmutablePair<GroupData, GraphEdge>> fetchedGroups = parentNodes.left().value(); if (fetchedGroups != null) { - List<String> list = fetchedGroups.stream().map(p -> p.left.getGroupDataDefinition().getUniqueId()) - .collect(Collectors.toList()); + List<String> list = fetchedGroups.stream().map(p -> p.left.getGroupDataDefinition().getUniqueId()).collect(Collectors.toList()); groups.addAll(list); } @@ -1090,15 +1170,13 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation } @Override - public Either<List<String>, StorageOperationStatus> getAssociatedGroupsToComponentInstance( - String componentInstanceId, boolean inTransaction) { + public Either<List<String>, StorageOperationStatus> getAssociatedGroupsToComponentInstance(String componentInstanceId, boolean inTransaction) { Either<List<String>, StorageOperationStatus> result = null; try { - Either<List<String>, TitanOperationStatus> groups = this - .getAssociatedGroupsToComponentInstanceFromGraph(componentInstanceId); + Either<List<String>, TitanOperationStatus> groups = this.getAssociatedGroupsToComponentInstanceFromGraph(componentInstanceId); if (groups.isRight()) { TitanOperationStatus status = groups.right().value(); @@ -1129,14 +1207,12 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation } @Override - public Either<List<String>, StorageOperationStatus> getAssociatedGroupsToComponentInstance( - String componentInstanceId) { + public Either<List<String>, StorageOperationStatus> getAssociatedGroupsToComponentInstance(String componentInstanceId) { return getAssociatedGroupsToComponentInstance(componentInstanceId, false); } @Override - public Either<List<GraphRelation>, TitanOperationStatus> associateGroupsToComponentInstanceOnGraph( - List<String> groups, String componentInstanceId, String compInstName) { + public Either<List<GraphRelation>, TitanOperationStatus> associateGroupsToComponentInstanceOnGraph(List<String> groups, String componentInstanceId, String compInstName) { List<GraphRelation> relations = new ArrayList<>(); Either<List<GraphRelation>, TitanOperationStatus> result = Either.left(relations); @@ -1150,14 +1226,11 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation Map<String, Object> props = new HashMap<String, Object>(); props.put(GraphPropertiesDictionary.NAME.getProperty(), compInstName); - Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(groupData, - compInstData, GraphEdgeLabels.GROUP_MEMBER, props); + Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(groupData, compInstData, GraphEdgeLabels.GROUP_MEMBER, props); if (createRelation.isRight()) { TitanOperationStatus status = createRelation.right().value(); - String description = "Failed to associate group " + groupData.getUniqueId() - + " to component instance " + compInstName + " in graph. Status is " + status; - BeEcompErrorManager.getInstance().logInternalFlowError(ASSOCIATING_GROUP_TO_COMP_INST, description, - ErrorSeverity.ERROR); + String description = "Failed to associate group " + groupData.getUniqueId() + " to component instance " + compInstName + " in graph. Status is " + status; + BeEcompErrorManager.getInstance().logInternalFlowError(ASSOCIATING_GROUP_TO_COMP_INST, description, ErrorSeverity.ERROR); result = Either.right(status); break; } @@ -1171,21 +1244,18 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation return result; } - public StorageOperationStatus associateGroupsToComponentInstance(List<String> groups, String componentInstanceId, - String compInstName) { + public StorageOperationStatus associateGroupsToComponentInstance(List<String> groups, String componentInstanceId, String compInstName) { return associateGroupsToComponentInstance(groups, componentInstanceId, compInstName, false); } @Override - public StorageOperationStatus associateGroupsToComponentInstance(List<String> groups, String componentInstanceId, - String compInstName, boolean inTransaction) { + public StorageOperationStatus associateGroupsToComponentInstance(List<String> groups, String componentInstanceId, String compInstName, boolean inTransaction) { StorageOperationStatus result = null; try { - Either<List<GraphRelation>, TitanOperationStatus> either = this - .associateGroupsToComponentInstanceOnGraph(groups, componentInstanceId, compInstName); + Either<List<GraphRelation>, TitanOperationStatus> either = this.associateGroupsToComponentInstanceOnGraph(groups, componentInstanceId, compInstName); if (either.isRight()) { TitanOperationStatus status = either.right().value(); @@ -1215,14 +1285,12 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation } @Override - public Either<List<GraphRelation>, TitanOperationStatus> dissociateAllGroupsFromArtifactOnGraph(String componentId, - NodeTypeEnum componentTypeEnum, String artifactId) { + public Either<List<GraphRelation>, TitanOperationStatus> dissociateAllGroupsFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String artifactId) { List<GraphRelation> relations = new ArrayList<>(); Either<List<GraphRelation>, TitanOperationStatus> result = Either.left(relations); - Either<List<GroupDefinition>, TitanOperationStatus> allGroupsFromGraph = getAllGroupsFromGraph(componentId, - componentTypeEnum, true, true, false); + Either<List<GroupDefinition>, TitanOperationStatus> allGroupsFromGraph = getAllGroupsFromGraph(componentId, componentTypeEnum, true, true, false); if (allGroupsFromGraph.isRight()) { TitanOperationStatus status = allGroupsFromGraph.right().value(); return Either.right(status); @@ -1234,9 +1302,7 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation } // Find all groups which contains this artifact id - List<GroupDefinition> associatedGroups = allGroups.stream() - .filter(p -> p.getArtifacts() != null && p.getArtifacts().contains(artifactId)) - .collect(Collectors.toList()); + List<GroupDefinition> associatedGroups = allGroups.stream().filter(p -> p.getArtifacts() != null && p.getArtifacts().contains(artifactId)).collect(Collectors.toList()); if (associatedGroups != null && false == associatedGroups.isEmpty()) { log.debug("The groups {} contains the artifact {}", associatedGroups.stream().map(p -> p.getName()).collect(Collectors.toList()), artifactId); @@ -1244,8 +1310,7 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation UniqueIdData artifactData = new UniqueIdData(NodeTypeEnum.ArtifactRef, artifactId); for (GroupDefinition groupDefinition : associatedGroups) { UniqueIdData groupData = new UniqueIdData(NodeTypeEnum.Group, groupDefinition.getUniqueId()); - Either<GraphRelation, TitanOperationStatus> deleteRelation = titanGenericDao.deleteRelation(groupData, - artifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF); + Either<GraphRelation, TitanOperationStatus> deleteRelation = titanGenericDao.deleteRelation(groupData, artifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF); if (deleteRelation.isRight()) { TitanOperationStatus status = deleteRelation.right().value(); if (status == TitanOperationStatus.NOT_FOUND) { @@ -1266,18 +1331,15 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation } - public Either<GroupDefinition, TitanOperationStatus> getGroupFromGraph(String uniqueId, boolean skipProperties, - boolean skipMembers, boolean skipArtifacts) { + public Either<GroupDefinition, TitanOperationStatus> getGroupFromGraph(String uniqueId, boolean skipProperties, boolean skipMembers, boolean skipArtifacts) { Either<GroupDefinition, TitanOperationStatus> result = null; - Either<GroupData, TitanOperationStatus> groupRes = titanGenericDao - .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), uniqueId, GroupData.class); + Either<GroupData, TitanOperationStatus> groupRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), uniqueId, GroupData.class); if (groupRes.isRight()) { TitanOperationStatus status = groupRes.right().value(); log.debug("Failed to retrieve group {} from graph. Status is {}", uniqueId, status); - BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("Fetch Group", uniqueId, - String.valueOf(status)); + BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("Fetch Group", uniqueId, String.valueOf(status)); result = Either.right(status); return result; } @@ -1324,13 +1386,12 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation } } else { List<GroupProperty> properties = propertiesRes.left().value(); - groupDefinition.setProperties(properties); + groupDefinition.convertFromGroupProperties(properties); } } if (false == skipArtifacts) { - Either<List<ImmutablePair<String, String>>, TitanOperationStatus> artifactsRes = getGroupArtifactsPairs( - uniqueId); + Either<List<ImmutablePair<String, String>>, TitanOperationStatus> artifactsRes = getGroupArtifactsPairs(uniqueId); if (artifactsRes.isRight()) { TitanOperationStatus status = artifactsRes.right().value(); if (status != TitanOperationStatus.OK) { @@ -1376,14 +1437,12 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation } } - protected Either<List<GroupDefinition>, TitanOperationStatus> getAllGroupsFromGraph(String componentId, - NodeTypeEnum componentTypeEnum, boolean skipProperties, boolean skipMembers, boolean skipArtifacts) { + protected Either<List<GroupDefinition>, TitanOperationStatus> getAllGroupsFromGraph(String componentId, NodeTypeEnum componentTypeEnum, boolean skipProperties, boolean skipMembers, boolean skipArtifacts) { List<GroupDefinition> groups = new ArrayList<GroupDefinition>(); - Either<List<ImmutablePair<GroupData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao - .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(componentTypeEnum), componentId, - GraphEdgeLabels.GROUP, NodeTypeEnum.Group, GroupData.class); + Either<List<ImmutablePair<GroupData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(componentTypeEnum), componentId, GraphEdgeLabels.GROUP, NodeTypeEnum.Group, + GroupData.class); if (childrenNodes.isRight()) { TitanOperationStatus status = childrenNodes.right().value(); @@ -1403,8 +1462,7 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation for (ImmutablePair<GroupData, GraphEdge> pair : graphGroups) { String groupUniqueId = pair.left.getGroupDataDefinition().getUniqueId(); - Either<GroupDefinition, TitanOperationStatus> groupRes = this.getGroupFromGraph(groupUniqueId, - skipProperties, skipMembers, skipArtifacts); + Either<GroupDefinition, TitanOperationStatus> groupRes = this.getGroupFromGraph(groupUniqueId, skipProperties, skipMembers, skipArtifacts); if (groupRes.isRight()) { TitanOperationStatus status = groupRes.right().value(); @@ -1422,14 +1480,12 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation } @Override - public StorageOperationStatus dissociateAllGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, - String artifactId, boolean inTransaction) { + public StorageOperationStatus dissociateAllGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String artifactId, boolean inTransaction) { StorageOperationStatus result = null; try { - Either<List<GraphRelation>, TitanOperationStatus> either = this - .dissociateAllGroupsFromArtifactOnGraph(componentId, componentTypeEnum, artifactId); + Either<List<GraphRelation>, TitanOperationStatus> either = this.dissociateAllGroupsFromArtifactOnGraph(componentId, componentTypeEnum, artifactId); if (either.isRight()) { TitanOperationStatus status = either.right().value(); @@ -1459,18 +1515,15 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation } @Override - public StorageOperationStatus dissociateAllGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, - String artifactId) { + public StorageOperationStatus dissociateAllGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String artifactId) { return dissociateAllGroupsFromArtifact(componentId, componentTypeEnum, artifactId, false); } @Override - public TitanOperationStatus dissociateAndAssociateGroupsFromArtifactOnGraph(String componentId, - NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact) { + public TitanOperationStatus dissociateAndAssociateGroupsFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact) { - Either<List<GroupDefinition>, TitanOperationStatus> allGroupsFromGraph = getAllGroupsFromGraph(componentId, - componentTypeEnum, true, true, false); + Either<List<GroupDefinition>, TitanOperationStatus> allGroupsFromGraph = getAllGroupsFromGraph(componentId, componentTypeEnum, true, true, false); if (allGroupsFromGraph.isRight()) { TitanOperationStatus status = allGroupsFromGraph.right().value(); return status; @@ -1482,26 +1535,22 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation } // Find all groups which contains this artifact id - List<GroupDefinition> associatedGroups = allGroups.stream() - .filter(p -> p.getArtifacts() != null && p.getArtifacts().contains(oldArtifactId)) - .collect(Collectors.toList()); + List<GroupDefinition> associatedGroups = allGroups.stream().filter(p -> p.getArtifacts() != null && p.getArtifacts().contains(oldArtifactId)).collect(Collectors.toList()); if (associatedGroups != null && false == associatedGroups.isEmpty()) { log.debug("The groups {} contains the artifact {}", associatedGroups.stream().map(p -> p.getName()).collect(Collectors.toList()), oldArtifactId); UniqueIdData oldArtifactData = new UniqueIdData(NodeTypeEnum.ArtifactRef, oldArtifactId); - UniqueIdData newArtifactData = new UniqueIdData(NodeTypeEnum.ArtifactRef, - newArtifact.getArtifactDataDefinition().getUniqueId()); + UniqueIdData newArtifactData = new UniqueIdData(NodeTypeEnum.ArtifactRef, newArtifact.getArtifactDataDefinition().getUniqueId()); Map<String, Object> props = new HashMap<String, Object>(); props.put(GraphPropertiesDictionary.NAME.getProperty(), newArtifactData.getLabel()); for (GroupDefinition groupDefinition : associatedGroups) { UniqueIdData groupData = new UniqueIdData(NodeTypeEnum.Group, groupDefinition.getUniqueId()); - Either<GraphRelation, TitanOperationStatus> deleteRelation = titanGenericDao.deleteRelation(groupData, - oldArtifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF); - log.trace("After dissociate group {} from artifac {}", groupDefinition.getName(), oldArtifactId); + Either<GraphRelation, TitanOperationStatus> deleteRelation = titanGenericDao.deleteRelation(groupData, oldArtifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF); + log.trace("After dissociate group {} from artifact {}" , groupDefinition.getName(), oldArtifactId); if (deleteRelation.isRight()) { TitanOperationStatus status = deleteRelation.right().value(); if (status == TitanOperationStatus.NOT_FOUND) { @@ -1510,9 +1559,8 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation return status; } - Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(groupData, - newArtifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF, props); - log.trace("After associate group {} to artifact {}", groupDefinition.getName(), newArtifact.getUniqueIdKey()); + Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(groupData, newArtifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF, props); + log.trace("After associate group {} to artifact {}" , groupDefinition.getName(), newArtifact.getUniqueIdKey()); if (createRelation.isRight()) { TitanOperationStatus status = createRelation.right().value(); if (status == TitanOperationStatus.NOT_FOUND) { @@ -1527,14 +1575,12 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation } @Override - public StorageOperationStatus dissociateAndAssociateGroupsFromArtifact(String componentId, - NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact, boolean inTransaction) { + public StorageOperationStatus dissociateAndAssociateGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact, boolean inTransaction) { StorageOperationStatus result = null; try { - TitanOperationStatus status = this.dissociateAndAssociateGroupsFromArtifactOnGraph(componentId, - componentTypeEnum, oldArtifactId, newArtifact); + TitanOperationStatus status = this.dissociateAndAssociateGroupsFromArtifactOnGraph(componentId, componentTypeEnum, oldArtifactId, newArtifact); if (status != TitanOperationStatus.OK && status != TitanOperationStatus.NOT_FOUND) { result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); @@ -1560,20 +1606,16 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation } @Override - public StorageOperationStatus dissociateAndAssociateGroupsFromArtifact(String componentId, - NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact) { - return dissociateAndAssociateGroupsFromArtifact(componentId, componentTypeEnum, oldArtifactId, newArtifact, - false); + public StorageOperationStatus dissociateAndAssociateGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact) { + return dissociateAndAssociateGroupsFromArtifact(componentId, componentTypeEnum, oldArtifactId, newArtifact, false); } - private Either<List<ImmutablePair<String, String>>, TitanOperationStatus> getGroupArtifactsPairs( - String groupUniqueId) { + private Either<List<ImmutablePair<String, String>>, TitanOperationStatus> getGroupArtifactsPairs(String groupUniqueId) { Either<List<ImmutablePair<String, String>>, TitanOperationStatus> result = null; - Either<List<ImmutablePair<ArtifactData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao - .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupUniqueId, - GraphEdgeLabels.GROUP_ARTIFACT_REF, NodeTypeEnum.ArtifactRef, ArtifactData.class); + Either<List<ImmutablePair<ArtifactData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupUniqueId, GraphEdgeLabels.GROUP_ARTIFACT_REF, + NodeTypeEnum.ArtifactRef, ArtifactData.class); if (childrenNodes.isRight()) { TitanOperationStatus status = childrenNodes.right().value(); if (status == TitanOperationStatus.NOT_FOUND) { @@ -1631,8 +1673,7 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation */ public Either<GroupDefinition, TitanOperationStatus> updateGroupVersionOnGraph(String groupUniqueId) { - Either<GroupDefinition, TitanOperationStatus> groupFromGraph = this.getGroupFromGraph(groupUniqueId, false, - false, false); + Either<GroupDefinition, TitanOperationStatus> groupFromGraph = this.getGroupFromGraph(groupUniqueId, false, false, false); if (groupFromGraph.isRight()) { TitanOperationStatus status = groupFromGraph.right().value(); @@ -1661,10 +1702,11 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation } } + + /** - * The version of the group is an integer. In order to support BC, we might - * get a version in a float format. + * 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 @@ -1680,23 +1722,20 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation } - public Either<GroupDefinition, TitanOperationStatus> associateArtifactsToGroupOnGraph(String groupId, - List<String> artifactsId) { + public Either<GroupDefinition, TitanOperationStatus> associateArtifactsToGroupOnGraph(String groupId, List<String> artifactsId) { if (artifactsId == null || artifactsId.isEmpty()) { return Either.right(TitanOperationStatus.OK); } for (String artifactId : artifactsId) { - Either<ArtifactData, TitanOperationStatus> findArtifactRes = titanGenericDao.getNode( - UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId, ArtifactData.class); + Either<ArtifactData, TitanOperationStatus> findArtifactRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId, ArtifactData.class); if (findArtifactRes.isRight()) { TitanOperationStatus status = findArtifactRes.right().value(); if (status == TitanOperationStatus.NOT_FOUND) { status = TitanOperationStatus.INVALID_ID; } - String description = "Failed to associate group " + groupId + " to artifact " + artifactId - + " in graph. Status is " + status; + String description = "Failed to associate group " + groupId + " to artifact " + artifactId + " in graph. Status is " + status; BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR); return Either.right(status); } @@ -1705,69 +1744,56 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation props.put(GraphPropertiesDictionary.NAME.getProperty(), findArtifactRes.left().value().getLabel()); GraphNode groupData = new UniqueIdData(NodeTypeEnum.Group, groupId); - Either<GraphRelation, TitanOperationStatus> addArtifactsRefResult = titanGenericDao.createRelation( - groupData, findArtifactRes.left().value(), GraphEdgeLabels.GROUP_ARTIFACT_REF, props); + Either<GraphRelation, TitanOperationStatus> addArtifactsRefResult = titanGenericDao.createRelation(groupData, findArtifactRes.left().value(), GraphEdgeLabels.GROUP_ARTIFACT_REF, props); if (addArtifactsRefResult.isRight()) { TitanOperationStatus status = addArtifactsRefResult.right().value(); - String description = "Failed to associate group " + groupData.getUniqueId() + " to artifact " - + artifactId + " in graph. Status is " + status; + String description = "Failed to associate group " + groupData.getUniqueId() + " to artifact " + artifactId + " in graph. Status is " + status; BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR); return Either.right(status); } } - Either<GroupDefinition, TitanOperationStatus> groupFromGraph = this.getGroupFromGraph(groupId, true, true, - false); + Either<GroupDefinition, TitanOperationStatus> groupFromGraph = this.getGroupFromGraph(groupId, true, true, false); return groupFromGraph; } - public Either<GroupDefinition, TitanOperationStatus> associateMembersToGroupOnGraph(String groupId, - Map<String, String> members) { + public Either<GroupDefinition, TitanOperationStatus> associateMembersToGroupOnGraph(String groupId, Map<String, String> members) { if (members != null && false == members.isEmpty()) { Either<GraphRelation, TitanOperationStatus> addMembersRefResult = null; for (Entry<String, String> member : members.entrySet()) { - Either<ComponentInstanceData, TitanOperationStatus> findComponentInstanceRes = titanGenericDao.getNode( - UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), member.getValue(), - ComponentInstanceData.class); + Either<ComponentInstanceData, TitanOperationStatus> findComponentInstanceRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), member.getValue(), ComponentInstanceData.class); if (findComponentInstanceRes.isRight()) { TitanOperationStatus status = findComponentInstanceRes.right().value(); if (status == TitanOperationStatus.NOT_FOUND) { status = TitanOperationStatus.INVALID_ID; } - String description = "Failed to find to find component instance group " + member.getValue() - + " in graph. Status is " + status; - BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, - ErrorSeverity.ERROR); + String description = "Failed to find to find component instance group " + member.getValue() + " in graph. Status is " + status; + BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR); return Either.right(status); } Map<String, Object> props = new HashMap<String, Object>(); props.put(GraphPropertiesDictionary.NAME.getProperty(), member.getKey()); GraphNode groupData = new UniqueIdData(NodeTypeEnum.Group, groupId); - addMembersRefResult = titanGenericDao.createRelation(groupData, findComponentInstanceRes.left().value(), - GraphEdgeLabels.GROUP_MEMBER, props); + addMembersRefResult = titanGenericDao.createRelation(groupData, findComponentInstanceRes.left().value(), GraphEdgeLabels.GROUP_MEMBER, props); if (addMembersRefResult.isRight()) { TitanOperationStatus status = addMembersRefResult.right().value(); - String description = "Failed to associate group " + groupData.getUniqueId() - + " to component instance " + member.getValue() + " in graph. Status is " + status; - BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, - ErrorSeverity.ERROR); + String description = "Failed to associate group " + groupData.getUniqueId() + " to component instance " + member.getValue() + " in graph. Status is " + status; + BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR); return Either.right(status); } } } - Either<GroupDefinition, TitanOperationStatus> groupFromGraph = this.getGroupFromGraph(groupId, true, false, - true); + Either<GroupDefinition, TitanOperationStatus> groupFromGraph = this.getGroupFromGraph(groupId, true, false, true); return groupFromGraph; } - public Either<GroupDefinition, TitanOperationStatus> dissociateArtifactsFromGroupOnGraph(String groupId, - List<String> artifactsId) { + public Either<GroupDefinition, TitanOperationStatus> dissociateArtifactsFromGroupOnGraph(String groupId, List<String> artifactsId) { if (artifactsId == null || artifactsId.isEmpty()) { return Either.right(TitanOperationStatus.OK); @@ -1777,32 +1803,28 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation for (String artifactId : artifactsId) { UniqueIdData artifactData = new UniqueIdData(NodeTypeEnum.Group, artifactId); - Either<GraphRelation, TitanOperationStatus> deleteRelation = titanGenericDao.deleteRelation(groupData, - artifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF); - log.trace("After dissociate group {} from artifact {}", groupId, artifactId); + Either<GraphRelation, TitanOperationStatus> deleteRelation = titanGenericDao.deleteRelation(groupData, artifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF); + log.trace("After dissociate group {} from artifact {}" ,groupId, artifactId); if (deleteRelation.isRight()) { TitanOperationStatus status = deleteRelation.right().value(); if (status == TitanOperationStatus.NOT_FOUND) { status = TitanOperationStatus.INVALID_ID; } - String description = "Failed to diassociate group " + groupId + " from artifact " + artifactId - + " in graph. Status is " + status; + String description = "Failed to diassociate group " + groupId + " from artifact " + artifactId + " in graph. Status is " + status; BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR); return Either.right(status); } } - Either<GroupDefinition, TitanOperationStatus> groupFromGraph = this.getGroupFromGraph(groupId, true, true, - false); + Either<GroupDefinition, TitanOperationStatus> groupFromGraph = this.getGroupFromGraph(groupId, true, true, false); return groupFromGraph; } - public Either<GroupDefinition, TitanOperationStatus> dissociateMembersFromGroupOnGraph(String groupId, - Map<String, String> members) { + public Either<GroupDefinition, TitanOperationStatus> dissociateMembersFromGroupOnGraph(String groupId, Map<String, String> members) { if (members == null || members.isEmpty()) { return Either.right(TitanOperationStatus.OK); @@ -1812,25 +1834,22 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation for (Entry<String, String> member : members.entrySet()) { UniqueIdData artifactData = new UniqueIdData(NodeTypeEnum.Group, member.getValue()); - Either<GraphRelation, TitanOperationStatus> deleteRelation = titanGenericDao.deleteRelation(groupData, - artifactData, GraphEdgeLabels.GROUP_MEMBER); - log.trace("After dissociate group {} from members", groupId, member.getValue()); + Either<GraphRelation, TitanOperationStatus> deleteRelation = titanGenericDao.deleteRelation(groupData, artifactData, GraphEdgeLabels.GROUP_MEMBER); + log.trace("After dissociate group {} from members {}" ,groupId, member.getValue()); if (deleteRelation.isRight()) { TitanOperationStatus status = deleteRelation.right().value(); if (status == TitanOperationStatus.NOT_FOUND) { status = TitanOperationStatus.INVALID_ID; } - String description = "Failed to diassociate group " + groupId + " from member " + member.getValue() - + " in graph. Status is " + status; + String description = "Failed to diassociate group " + groupId + " from member " + member.getValue() + " in graph. Status is " + status; BeEcompErrorManager.getInstance().logInternalFlowError(ADDING_GROUP, description, ErrorSeverity.ERROR); return Either.right(status); } } - Either<GroupDefinition, TitanOperationStatus> groupFromGraph = this.getGroupFromGraph(groupId, true, true, - false); + Either<GroupDefinition, TitanOperationStatus> groupFromGraph = this.getGroupFromGraph(groupId, true, true, false); return groupFromGraph; @@ -1844,18 +1863,15 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation * @param inTransaction * @return */ - public Either<GroupDefinition, StorageOperationStatus> dissociateArtifactsFromGroup(String groupId, - List<String> artifactsId, boolean inTransaction) { + public Either<GroupDefinition, StorageOperationStatus> dissociateArtifactsFromGroup(String groupId, List<String> artifactsId, boolean inTransaction) { Either<GroupDefinition, StorageOperationStatus> result = null; try { - Either<GroupDefinition, TitanOperationStatus> titanRes = this.dissociateArtifactsFromGroupOnGraph(groupId, - artifactsId); + Either<GroupDefinition, TitanOperationStatus> titanRes = this.dissociateArtifactsFromGroupOnGraph(groupId, artifactsId); if (titanRes.isRight()) { - StorageOperationStatus storageOperationStatus = DaoStatusConverter - .convertTitanStatusToStorageStatus(titanRes.right().value()); + StorageOperationStatus storageOperationStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(titanRes.right().value()); result = Either.right(storageOperationStatus); return result; } @@ -1878,18 +1894,15 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation } - public Either<GroupDefinition, StorageOperationStatus> dissociateMembersFromGroup(String groupId, - Map<String, String> members, boolean inTransaction) { + public Either<GroupDefinition, StorageOperationStatus> dissociateMembersFromGroup(String groupId, Map<String, String> members, boolean inTransaction) { Either<GroupDefinition, StorageOperationStatus> result = null; try { - Either<GroupDefinition, TitanOperationStatus> titanRes = this.dissociateMembersFromGroupOnGraph(groupId, - members); + Either<GroupDefinition, TitanOperationStatus> titanRes = this.dissociateMembersFromGroupOnGraph(groupId, members); if (titanRes.isRight()) { - StorageOperationStatus storageOperationStatus = DaoStatusConverter - .convertTitanStatusToStorageStatus(titanRes.right().value()); + StorageOperationStatus storageOperationStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(titanRes.right().value()); result = Either.right(storageOperationStatus); return result; } @@ -1920,19 +1933,16 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation * @param inTransaction * @return */ - public Either<GroupDefinition, StorageOperationStatus> associateArtifactsToGroup(String groupId, - List<String> artifactsId, boolean inTransaction) { + public Either<GroupDefinition, StorageOperationStatus> associateArtifactsToGroup(String groupId, List<String> artifactsId, boolean inTransaction) { Either<GroupDefinition, StorageOperationStatus> result = null; try { - Either<GroupDefinition, TitanOperationStatus> titanRes = this.associateArtifactsToGroupOnGraph(groupId, - artifactsId); + Either<GroupDefinition, TitanOperationStatus> titanRes = this.associateArtifactsToGroupOnGraph(groupId, artifactsId); if (titanRes.isRight()) { - StorageOperationStatus status = DaoStatusConverter - .convertTitanStatusToStorageStatus(titanRes.right().value()); + StorageOperationStatus status = DaoStatusConverter.convertTitanStatusToStorageStatus(titanRes.right().value()); result = Either.right(status); } @@ -1962,19 +1972,16 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation * @param inTransaction * @return */ - public Either<GroupDefinition, StorageOperationStatus> associateMembersToGroup(String groupId, - Map<String, String> members, boolean inTransaction) { + public Either<GroupDefinition, StorageOperationStatus> associateMembersToGroup(String groupId, Map<String, String> members, boolean inTransaction) { Either<GroupDefinition, StorageOperationStatus> result = null; try { - Either<GroupDefinition, TitanOperationStatus> titanRes = this.associateMembersToGroupOnGraph(groupId, - members); + Either<GroupDefinition, TitanOperationStatus> titanRes = this.associateMembersToGroupOnGraph(groupId, members); if (titanRes.isRight()) { - StorageOperationStatus status = DaoStatusConverter - .convertTitanStatusToStorageStatus(titanRes.right().value()); + StorageOperationStatus status = DaoStatusConverter.convertTitanStatusToStorageStatus(titanRes.right().value()); result = Either.right(status); return result; } @@ -1997,18 +2004,15 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation } - public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupVersion(List<String> groupsId, - boolean inTransaction) { + public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupVersion(List<String> groupsId, boolean inTransaction) { Either<List<GroupDefinition>, StorageOperationStatus> result = null; try { - Either<List<GroupDefinition>, TitanOperationStatus> updateGroupVersionOnGraph = this - .updateGroupVersionOnGraph(groupsId); + Either<List<GroupDefinition>, TitanOperationStatus> updateGroupVersionOnGraph = this.updateGroupVersionOnGraph(groupsId); if (updateGroupVersionOnGraph.isRight()) { - result = Either.right(DaoStatusConverter - .convertTitanStatusToStorageStatus(updateGroupVersionOnGraph.right().value())); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateGroupVersionOnGraph.right().value())); return result; } @@ -2029,42 +2033,53 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation } } - - public Either<GroupDefinition, StorageOperationStatus> updateGroupName(String uniqueId, String newName, - boolean inTransaction) { + /** + * This method updates group name + * @param groupToUpdateFromUniqueId + * @param newName + * @param inTransaction + * @return + */ + public Either<GroupDefinition, StorageOperationStatus> updateGroupName(String groupToUpdateFromUniqueId, + String newName, boolean inTransaction) { Either<GroupDefinition, StorageOperationStatus> result = null; try { - Either<GroupDefinition, TitanOperationStatus> updateGroupNameOnGraph = this.updateGroupNameOnGraph(uniqueId, - newName); + //Update Name + Either<GroupDefinition, TitanOperationStatus> updateGroupNameOnGraph = updateGroupNameOnGraph( + groupToUpdateFromUniqueId, newName); if (updateGroupNameOnGraph.isRight()) { result = Either.right( DaoStatusConverter.convertTitanStatusToStorageStatus(updateGroupNameOnGraph.right().value())); - return result; + } + else{ + result = Either.left(updateGroupNameOnGraph.left().value()); } + return result; - result = Either.left(updateGroupNameOnGraph.left().value()); + } finally { + handleTransactionCommitRollback(inTransaction, result); + } + } + @Override + public Either<GroupDefinition, StorageOperationStatus> updateGroupName(String groupToUpdateFromUniqueId, + String newName, GroupDefinition groupToUpdateTo, boolean inTransaction) { + Either<GroupDefinition, StorageOperationStatus> result = null; + + try { + //Update Name + result = updateGroupName(groupToUpdateFromUniqueId, newName, true); return result; } finally { - if (false == inTransaction) { - if (result == null || result.isRight()) { - log.debug("Going to execute rollback on graph."); - BeEcompErrorManager.getInstance().logBeExecuteRollbackError("Rollback on graph"); - titanGenericDao.rollback(); - } else { - log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); - } - } + handleTransactionCommitRollback(inTransaction, result); } } private Either<GroupDefinition, TitanOperationStatus> updateGroupNameOnGraph(String uniqueId, String newName) { - Either<GroupDefinition, TitanOperationStatus> groupFromGraph = this.getGroupFromGraph(uniqueId, false, false, - false); + Either<GroupDefinition, TitanOperationStatus> groupFromGraph = this.getGroupFromGraph(uniqueId, false, false, false); if (groupFromGraph.isRight()) { TitanOperationStatus status = groupFromGraph.right().value(); @@ -2090,4 +2105,32 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation } } } + + + @Override + public StorageOperationStatus validateAndUpdatePropertyValue(GroupProperty property) { + + StorageOperationStatus result = null; + String innerType = property.getSchema() == null ? null : property.getSchema().getProperty() == null ? null : property.getSchema().getProperty().getType(); + Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); + Either<Object, Boolean> isValid = null; + if (allDataTypes.isRight()) { + TitanOperationStatus status = allDataTypes.right().value(); + log.debug("Failed to fetch data types from cache. Status is {}. ", status); + result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); + } + if(result == null){ + isValid = propertyOperation.validateAndUpdatePropertyValue(property.getType(), property.getValue(), innerType, allDataTypes.left().value()); + if(isValid.isRight()){ + log.debug("Failed to validate property value {}. Status is {}. ", property.getValue(), StorageOperationStatus.INVALID_PROPERTY); + result = StorageOperationStatus.INVALID_PROPERTY; + } + } + if(result == null){ + String validValue = String.valueOf(isValid.left().value()); + property.setValue(validValue); + result = StorageOperationStatus.OK; + } + return result; + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperation.java index 4251e503e6..2fcdf695be 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperation.java @@ -27,8 +27,6 @@ import java.util.Map; import java.util.Set; import java.util.function.Function; -import javax.annotation.Resource; - import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; @@ -48,6 +46,7 @@ import org.openecomp.sdc.be.resources.data.GroupTypeData; import org.openecomp.sdc.be.resources.data.PropertyData; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import fj.data.Either; @@ -58,11 +57,14 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO String CREATE_FLOW_CONTEXT = "CreateGroupType"; String GET_FLOW_CONTEXT = "GetGroupType"; - @Resource private PropertyOperation propertyOperation; + + private TitanGenericDao titanGenericDao; - public GroupTypeOperation() { + public GroupTypeOperation(@Qualifier("titan-generic-dao") TitanGenericDao titanGenericDao, @Qualifier("property-operation")PropertyOperation propertyOperation) { super(); + this.propertyOperation = propertyOperation; + this.titanGenericDao = titanGenericDao; } private static Logger log = LoggerFactory.getLogger(GroupTypeOperation.class.getName()); @@ -83,8 +85,7 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO } @Override - public Either<GroupTypeDefinition, StorageOperationStatus> addGroupType(GroupTypeDefinition groupTypeDefinition, - boolean inTransaction) { + public Either<GroupTypeDefinition, StorageOperationStatus> addGroupType(GroupTypeDefinition groupTypeDefinition, boolean inTransaction) { Either<GroupTypeDefinition, StorageOperationStatus> result = null; @@ -93,10 +94,8 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO Either<GroupTypeData, TitanOperationStatus> eitherStatus = addGroupTypeToGraph(groupTypeDefinition); if (eitherStatus.isRight()) { - BeEcompErrorManager.getInstance().logBeFailedCreateNodeError(CREATE_FLOW_CONTEXT, - groupTypeDefinition.getType(), eitherStatus.right().value().name()); - result = Either - .right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherStatus.right().value())); + BeEcompErrorManager.getInstance().logBeFailedCreateNodeError(CREATE_FLOW_CONTEXT, groupTypeDefinition.getType(), eitherStatus.right().value().name()); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherStatus.right().value())); } else { GroupTypeData groupTypeData = eitherStatus.left().value(); @@ -105,8 +104,7 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO Either<GroupTypeDefinition, StorageOperationStatus> groupTypeRes = this.getGroupType(uniqueId, true); if (groupTypeRes.isRight()) { - BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError(GET_FLOW_CONTEXT, - groupTypeDefinition.getType(), eitherStatus.right().value().name()); + BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError(GET_FLOW_CONTEXT, groupTypeDefinition.getType(), eitherStatus.right().value().name()); } result = groupTypeRes; @@ -125,20 +123,18 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO Either<GroupTypeDefinition, TitanOperationStatus> result = null; - Either<GroupTypeData, TitanOperationStatus> groupTypesRes = titanGenericDao - .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupType), uniqueId, GroupTypeData.class); + Either<GroupTypeData, TitanOperationStatus> groupTypesRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupType), uniqueId, GroupTypeData.class); if (groupTypesRes.isRight()) { TitanOperationStatus status = groupTypesRes.right().value(); - log.debug("Group type {} cannot be found in graph. Status is {}", uniqueId, status); + log.debug("Group type {} cannot be found in graph. status is {}", uniqueId, status); return Either.right(status); } GroupTypeData gtData = groupTypesRes.left().value(); GroupTypeDefinition groupTypeDefinition = new GroupTypeDefinition(gtData.getGroupTypeDataDefinition()); - TitanOperationStatus propertiesStatus = propertyOperation.fillProperties(uniqueId, - properList -> groupTypeDefinition.setProperties(properList)); + TitanOperationStatus propertiesStatus = propertyOperation.fillProperties(uniqueId, properList -> groupTypeDefinition.setProperties(properList)); if (propertiesStatus != TitanOperationStatus.OK) { log.error("Failed to fetch properties of capability type {}", uniqueId); @@ -159,8 +155,7 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO @Override public Either<GroupTypeDefinition, StorageOperationStatus> getGroupType(String uniqueId, boolean inTransaction) { - Function<String, Either<GroupTypeDefinition, TitanOperationStatus>> groupTypeGetter = uId -> getGroupTypeByUid( - uId); + Function<String, Either<GroupTypeDefinition, TitanOperationStatus>> groupTypeGetter = uId -> getGroupTypeByUid(uId); return getElementType(groupTypeGetter, uniqueId, inTransaction); } @@ -171,8 +166,7 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO } @Override - public Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeByType(String type, - boolean inTransaction) { + public Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeByType(String type, boolean inTransaction) { Map<String, Object> mapCriteria = new HashMap<>(); mapCriteria.put(GraphPropertiesDictionary.TYPE.getProperty(), type); mapCriteria.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true); @@ -181,8 +175,7 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO } - public Either<GroupTypeDefinition, StorageOperationStatus> getGroupTypeByCriteria(String type, - Map<String, Object> properties, boolean inTransaction) { + public Either<GroupTypeDefinition, StorageOperationStatus> getGroupTypeByCriteria(String type, Map<String, Object> properties, boolean inTransaction) { Either<GroupTypeDefinition, StorageOperationStatus> result = null; try { if (type == null || type.isEmpty()) { @@ -191,14 +184,11 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO return result; } - Either<List<GroupTypeData>, TitanOperationStatus> groupTypeEither = titanGenericDao - .getByCriteria(NodeTypeEnum.GroupType, properties, GroupTypeData.class); + Either<List<GroupTypeData>, TitanOperationStatus> groupTypeEither = titanGenericDao.getByCriteria(NodeTypeEnum.GroupType, properties, GroupTypeData.class); if (groupTypeEither.isRight()) { - result = Either - .right(DaoStatusConverter.convertTitanStatusToStorageStatus(groupTypeEither.right().value())); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(groupTypeEither.right().value())); } else { - GroupTypeDataDefinition dataDefinition = groupTypeEither.left().value().stream() - .map(e -> e.getGroupTypeDataDefinition()).findFirst().get(); + GroupTypeDataDefinition dataDefinition = groupTypeEither.left().value().stream().map(e -> e.getGroupTypeDataDefinition()).findFirst().get(); result = getGroupType(dataDefinition.getUniqueId(), inTransaction); } @@ -210,14 +200,12 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO } @Override - public Either<GroupTypeDefinition, StorageOperationStatus> getGroupTypeByTypeAndVersion(String type, - String version) { + public Either<GroupTypeDefinition, StorageOperationStatus> getGroupTypeByTypeAndVersion(String type, String version) { return getGroupTypeByTypeAndVersion(type, version, false); } @Override - public Either<GroupTypeDefinition, StorageOperationStatus> getGroupTypeByTypeAndVersion(String type, String version, - boolean inTransaction) { + public Either<GroupTypeDefinition, StorageOperationStatus> getGroupTypeByTypeAndVersion(String type, String version, boolean inTransaction) { Map<String, Object> mapCriteria = new HashMap<>(); mapCriteria.put(GraphPropertiesDictionary.TYPE.getProperty(), type); mapCriteria.put(GraphPropertiesDictionary.VERSION.getProperty(), version); @@ -233,8 +221,7 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO * * 2. Add edge between the former node to its parent(if exists) * - * 3. Add property node and associate it to the node created at #1. (per - * property & if exists) + * 3. Add property node and associate it to the node created at #1. (per property & if exists) * * @param groupTypeDefinition * @return @@ -243,28 +230,25 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO log.debug("Got group type {}", groupTypeDefinition); - String ctUniqueId = UniqueIdBuilder.buildGroupTypeUid(groupTypeDefinition.getType(), - groupTypeDefinition.getVersion()); + String ctUniqueId = UniqueIdBuilder.buildGroupTypeUid(groupTypeDefinition.getType(), groupTypeDefinition.getVersion()); // capabilityTypeDefinition.setUniqueId(ctUniqueId); GroupTypeData groupTypeData = buildGroupTypeData(groupTypeDefinition, ctUniqueId); log.debug("Before adding group type to graph. groupTypeData = {}", groupTypeData); - Either<GroupTypeData, TitanOperationStatus> createGTResult = titanGenericDao.createNode(groupTypeData, - GroupTypeData.class); + Either<GroupTypeData, TitanOperationStatus> createGTResult = titanGenericDao.createNode(groupTypeData, GroupTypeData.class); log.debug("After adding group type to graph. status is = {}", createGTResult); if (createGTResult.isRight()) { TitanOperationStatus operationStatus = createGTResult.right().value(); - log.error("Failed to add group type {} to graph. Status is {}", groupTypeDefinition.getType(), operationStatus); + log.error("Failed to add group type {} to graph. status is {}", groupTypeDefinition.getType(), operationStatus); return Either.right(operationStatus); } GroupTypeData resultCTD = createGTResult.left().value(); List<PropertyDefinition> properties = groupTypeDefinition.getProperties(); - Either<Map<String, PropertyData>, TitanOperationStatus> addPropertiesToCapablityType = propertyOperation - .addPropertiesToElementType(resultCTD.getUniqueId(), NodeTypeEnum.GroupType, properties); + Either<Map<String, PropertyData>, TitanOperationStatus> addPropertiesToCapablityType = propertyOperation.addPropertiesToElementType(resultCTD.getUniqueId(), NodeTypeEnum.GroupType, properties); if (addPropertiesToCapablityType.isRight()) { log.error("Failed add properties {} to capability {}", properties, groupTypeDefinition.getType()); return Either.right(addPropertiesToCapablityType.right().value()); @@ -276,14 +260,9 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO // TODO: Need to find the parent. need to take the latest one since // we may have many versions of the same type /* - * log.debug("Before creating relation between group type {} to its parent {}", ctUniqueId, derivedFrom); UniqueIdData from - * = new UniqueIdData(NodeTypeEnum.CapabilityType, ctUniqueId); - * UniqueIdData to = new UniqueIdData(NodeTypeEnum.CapabilityType, - * derivedFrom); Either<GraphRelation, TitanOperationStatus> - * createRelation = titanGenericDao .createRelation(from, to, - * GraphEdgeLabels.DERIVED_FROM, null); - * log.debug("After create relation between capability type {} to its parent {}. Status is {}", ctUniqueId, derivedFrom, if (createRelation.isRight()) { return - * Either.right(createRelation.right().value()); } + * log.debug("Before creating relation between group type {} to its parent {}", ctUniqueId, derivedFrom); UniqueIdData from = new UniqueIdData(NodeTypeEnum.CapabilityType, ctUniqueId); UniqueIdData to = new + * UniqueIdData(NodeTypeEnum.CapabilityType, derivedFrom); Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao .createRelation(from, to, GraphEdgeLabels.DERIVED_FROM, null); + * log.debug("After create relation between capability type {} to its parent {}. status is {}", ctUniqueId, derivedFrom, createRelation); if (createRelation.isRight()) { return Either.right(createRelation.right().value()); } * */ } @@ -302,8 +281,7 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO protected CapabilityTypeDefinition convertCTDataToCTDefinition(CapabilityTypeData capabilityTypeData) { log.debug("The object returned after create capability is {}", capabilityTypeData); - CapabilityTypeDefinition capabilityTypeDefResult = new CapabilityTypeDefinition( - capabilityTypeData.getCapabilityTypeDataDefinition()); + CapabilityTypeDefinition capabilityTypeDefResult = new CapabilityTypeDefinition(capabilityTypeData.getCapabilityTypeDataDefinition()); return capabilityTypeDefResult; } @@ -323,12 +301,10 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO return groupTypeData; } - public Either<Boolean, StorageOperationStatus> isCapabilityTypeDerivedFrom(String childCandidateType, - String parentCandidateType) { + public Either<Boolean, StorageOperationStatus> isCapabilityTypeDerivedFrom(String childCandidateType, String parentCandidateType) { Map<String, Object> propertiesToMatch = new HashMap<String, Object>(); propertiesToMatch.put(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), childCandidateType); - Either<List<CapabilityTypeData>, TitanOperationStatus> getResponse = titanGenericDao - .getByCriteria(NodeTypeEnum.CapabilityType, propertiesToMatch, CapabilityTypeData.class); + Either<List<CapabilityTypeData>, TitanOperationStatus> getResponse = titanGenericDao.getByCriteria(NodeTypeEnum.CapabilityType, propertiesToMatch, CapabilityTypeData.class); if (getResponse.isRight()) { TitanOperationStatus titanOperationStatus = getResponse.right().value(); log.debug("Couldn't fetch capability type {}, error: {}", childCandidateType, titanOperationStatus); @@ -338,14 +314,12 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO Set<String> travelledTypes = new HashSet<>(); do { travelledTypes.add(childUniqueId); - Either<List<ImmutablePair<CapabilityTypeData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao - .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), childUniqueId, - GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.CapabilityType, CapabilityTypeData.class); + Either<List<ImmutablePair<CapabilityTypeData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), childUniqueId, GraphEdgeLabels.DERIVED_FROM, + NodeTypeEnum.CapabilityType, CapabilityTypeData.class); if (childrenNodes.isRight()) { if (childrenNodes.right().value() != TitanOperationStatus.NOT_FOUND) { TitanOperationStatus titanOperationStatus = getResponse.right().value(); - log.debug("Couldn't fetch derived from node for capability type {}, error: {}", childCandidateType, - titanOperationStatus); + log.debug("Couldn't fetch derived from node for capability type {}, error: {}", childCandidateType, titanOperationStatus); return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(titanOperationStatus)); } else { log.debug("Derived from node is not found for type {} - this is OK for root capability."); @@ -354,8 +328,7 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO } String derivedFromUniqueId = childrenNodes.left().value().get(0).getLeft().getUniqueId(); if (derivedFromUniqueId.equals(parentCandidateType)) { - log.debug("Verified that capability type {} derives from capability type {}", childCandidateType, - parentCandidateType); + log.debug("Verified that capability type {} derives from capability type {}", childCandidateType, parentCandidateType); return Either.left(true); } childUniqueId = derivedFromUniqueId; diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/HeatParametersOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/HeatParametersOperation.java index 5d7b8c5991..ad56779a94 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/HeatParametersOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/HeatParametersOperation.java @@ -128,7 +128,7 @@ public class HeatParametersOperation implements IHeatParametersOperation { for (ImmutablePair<HeatParameterValueData, GraphEdge> immutablePair : values) { GraphEdge edge = immutablePair.getValue(); String propertyName = (String) edge.getProperties().get(GraphPropertiesDictionary.NAME.getProperty()); - log.trace("Heat value " + propertyName + " is associated to node " + parentUniqueId); + log.trace("Heat value {} is associated to node {}", propertyName,parentUniqueId); HeatParameterValueData propertyData = immutablePair.getKey(); heatValues.add(propertyData); @@ -193,17 +193,17 @@ public class HeatParametersOperation implements IHeatParametersOperation { } - log.debug("The heat values deleted from node {} are {}", parentUniqueId, heatValues); + log.debug("The heat values deleted from node {} are {}" , parentUniqueId, heatValues); return StorageOperationStatus.OK; } private Either<HeatParameterData, TitanOperationStatus> deleteHeatParameterFromGraph(String propertyId) { - log.debug("Before deleting heat parameter from graph {}", propertyId); + log.debug("Before deleting heat parameter from graph {}" , propertyId); return titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.HeatParameter), propertyId, HeatParameterData.class); } private Either<HeatParameterValueData, TitanOperationStatus> deleteHeatParameterValueFromGraph(String propertyId) { - log.debug("Before deleting heat parameter from graph {}", propertyId); + log.debug("Before deleting heat parameter from graph {}" , propertyId); return titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.HeatParameterValue), propertyId, HeatParameterValueData.class); } @@ -215,17 +215,6 @@ public class HeatParametersOperation implements IHeatParametersOperation { String propertyName = propertyDefinition.getName(); - // type and value should be validated in business logic: - // ArtifactsBusinessLogic.validateAndConvertHeatParamers(ArtifactDefinition) - - // StorageOperationStatus validateAndUpdateProperty = - // validateAndUpdateProperty(propertyDefinition); - // if (validateAndUpdateProperty != StorageOperationStatus.OK) { - // log.error("Property " + propertyDefinition + " is invalid. - // Status is " + validateAndUpdateProperty); - // return StorageOperationStatus.BAD_REQUEST; - // } - Either<HeatParameterData, TitanOperationStatus> addPropertyToGraph = addPropertyToGraph(propertyName, propertyDefinition, parentId, nodeType); if (addPropertyToGraph.isRight()) { @@ -264,12 +253,12 @@ public class HeatParametersOperation implements IHeatParametersOperation { propertyDefinition.setUniqueId(UniqueIdBuilder.buildHeatParameterUniqueId(parentId, propertyName)); HeatParameterData propertyData = new HeatParameterData(propertyDefinition); - log.debug("Before adding property to graph {}", propertyData); + log.debug("Before adding property to graph {}" , propertyData); Either<HeatParameterData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(propertyData, HeatParameterData.class); - log.debug("After adding property to graph {}", propertyData); + log.debug("After adding property to graph {}" , propertyData); if (createNodeResult.isRight()) { TitanOperationStatus operationStatus = createNodeResult.right().value(); - log.error("Failed to add property {} to graph. Status is {}", propertyName, operationStatus); + log.error("Failed to add property {} to graph. status is {}", propertyName, operationStatus); return Either.right(operationStatus); } @@ -278,10 +267,7 @@ public class HeatParametersOperation implements IHeatParametersOperation { Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(parentNode, propertyData, GraphEdgeLabels.HEAT_PARAMETER, props); if (createRelResult.isRight()) { TitanOperationStatus operationStatus = createRelResult.right().value(); - - if (log.isDebugEnabled()) { - log.error("Failed to associate {} {} to heat parameter {} in graph. Status is {}", nodeType.getName(), parentId, propertyName, operationStatus); - } + log.error("Failed to associate {} {} to heat parameter {} in graph. status is {}", nodeType.getName(), parentId, propertyName, operationStatus); return Either.right(operationStatus); } @@ -291,13 +277,13 @@ public class HeatParametersOperation implements IHeatParametersOperation { public StorageOperationStatus validateAndUpdateProperty(HeatParameterDefinition propertyDefinition) { - log.trace("Going to validate property type and value. {}", propertyDefinition); + log.trace("Going to validate property type and value. {}" , propertyDefinition); String propertyType = propertyDefinition.getType(); HeatParameterType type = getType(propertyType); if (type == null) { - log.info("The type {} of heat is invalid", type); + log.info("The type {} of heat parameter is invalid", type); return StorageOperationStatus.INVALID_TYPE; } @@ -316,7 +302,8 @@ public class HeatParametersOperation implements IHeatParametersOperation { PropertyValueConverter converter = type.getConverter(); if (isEmptyValue(defaultValue)) { - log.debug("Default value was not sent for property {}. Set default value to {}", propertyDefinition.getName(), EMPTY_VALUE); + log.debug("Default value was not sent for property {}. Set default value to {}", propertyDefinition.getName() , EMPTY_VALUE); + propertyDefinition.setDefaultValue(EMPTY_VALUE); } else if (false == isEmptyValue(defaultValue)) { String convertedValue = converter.convert(defaultValue, null, null); @@ -333,6 +320,7 @@ public class HeatParametersOperation implements IHeatParametersOperation { if (isEmptyValue(value)) { log.debug("Value was not sent for property {}. Set value to {}", propertyDefinition.getName(), EMPTY_VALUE); + propertyDefinition.setCurrentValue(EMPTY_VALUE); } else if (!value.equals("")) { String convertedValue = converter.convert(value, null, null); @@ -465,7 +453,7 @@ public class HeatParametersOperation implements IHeatParametersOperation { log.debug("After adding property to graph {}", heatValueData); if (createNodeResult.isRight()) { TitanOperationStatus operationStatus = createNodeResult.right().value(); - log.error("Failed to add heat value {} to graph. Status is {}", heatValueData.getUniqueId(), operationStatus); + log.error("Failed to add heat value {} to graph. status is {}", heatValueData.getUniqueId(), operationStatus); return Either.right(operationStatus); } @@ -474,14 +462,14 @@ public class HeatParametersOperation implements IHeatParametersOperation { Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(heatEnvNode, heatValueData, GraphEdgeLabels.PARAMETER_VALUE, props); if (createRelResult.isRight()) { TitanOperationStatus operationStatus = createRelResult.right().value(); - log.error("Failed to associate heat value {} to heat env artifact {} in graph. Status is {}", heatValueData.getUniqueId(), artifactId, operationStatus); + log.error("Failed to associate heat value {} to heat env artifact {} in graph. status is {}", heatValueData.getUniqueId(), artifactId, operationStatus); return Either.right(operationStatus); } UniqueIdData heatParameterNode = new UniqueIdData(NodeTypeEnum.HeatParameter, heatParameter.getUniqueId()); Either<GraphRelation, TitanOperationStatus> createRel2Result = titanGenericDao.createRelation(heatValueData, heatParameterNode, GraphEdgeLabels.PARAMETER_IMPL, null); if (createRel2Result.isRight()) { TitanOperationStatus operationStatus = createRel2Result.right().value(); - log.error("Failed to associate heat value {} to heat parameter {} in graph. Status is {}", heatValueData.getUniqueId(), heatParameter.getName(), operationStatus); + log.error("Failed to associate heat value {} to heat parameter {} in graph. status is {}", heatValueData.getUniqueId(), heatParameter.getName(), operationStatus); return Either.right(operationStatus); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InputsOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InputsOperation.java index e2d13a9cff..dba4ff9b75 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InputsOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InputsOperation.java @@ -28,12 +28,15 @@ import java.util.Map; import java.util.Map.Entry; import java.util.stream.Collectors; +import javax.json.Json; + import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.tinkerpop.gremlin.process.traversal.Order; import org.apache.tinkerpop.gremlin.structure.Direction; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.json.simple.JSONObject; +import org.json.simple.parser.ParseException; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; import org.openecomp.sdc.be.dao.graph.GraphElementFactory; @@ -45,15 +48,18 @@ import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; + import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.ComponentInstInputsMap; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.ComponentInstanceInput; +import org.openecomp.sdc.be.model.ComponentInstancePropInput; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.GetInputValueInfo; import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.PropertyConstraint; +import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.operations.api.IInputsOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.resources.data.AttributeData; @@ -70,6 +76,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import org.yaml.snakeyaml.Yaml; import com.google.gson.Gson; import com.thinkaurelius.titan.core.TitanEdge; @@ -83,9 +90,13 @@ import fj.data.Either; @Component("input-operation") public class InputsOperation extends AbstractOperation implements IInputsOperation { + private static final String GET_INPUT = "get_input"; + private static String ASSOCIATING_INPUT_TO_PROP = "AssociatingInputToComponentInstanceProperty"; private static Logger log = LoggerFactory.getLogger(InputsOperation.class.getName()); + @Autowired + PropertyOperation propertyOperation; @Autowired private ComponentInstanceOperation componentInstanceOperation; @@ -95,18 +106,103 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati * Delete specific input from component Although inputId is unique, pass also componentId as all other methods, and also check that the inputId is inside that componentId. */ @Override - public Either<String, StorageOperationStatus> deleteInput(String inputId) { + public Either<InputDefinition, StorageOperationStatus> deleteInput(String inputId) { log.debug(String.format("Before deleting input: %s from graph", inputId)); + List<ComponentInstanceInput> inputsValueList = null; + List<ComponentInstanceProperty> propertyList = new ArrayList<>(); + + Either<TitanVertex, TitanOperationStatus> vertexService = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), inputId); + + if (vertexService.isRight()) { + log.debug("failed to fetch vertex of resource input for id = {}", inputId); + TitanOperationStatus status = vertexService.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + + StorageOperationStatus convertTitanStatusToStorageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(status); + return Either.right(convertTitanStatusToStorageStatus); + } + TitanVertex vertex = vertexService.left().value(); + Iterator<Edge> edgeIter = vertex.edges(Direction.IN, GraphEdgeLabels.INPUT.getProperty()); + + if (edgeIter == null) { + log.debug("No edges in graph for criteria"); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.NOT_FOUND)); + } + String inputName = ""; + if (edgeIter != null) { + while (edgeIter.hasNext()) { + Edge edge = edgeIter.next(); + GraphEdge graphEdge = null; + + Map<String, Object> edgeProps = titanGenericDao.getProperties(edge); + GraphEdgeLabels edgeTypeFromGraph = GraphEdgeLabels.getByName(edge.label()); + graphEdge = new GraphEdge(edgeTypeFromGraph, edgeProps); + + inputName = (String) graphEdge.getProperties().get(GraphEdgePropertiesDictionary.NAME.getProperty()); + + } + } + + Either<List<ComponentInstanceInput>, TitanOperationStatus> inputsValueStatus = this.getComponentInstanceInputsByInputId(inputId); if(inputsValueStatus.isLeft()){ - List<ComponentInstanceInput> inputsValueLis = inputsValueStatus.left().value(); - if(!inputsValueLis.isEmpty()){ - for(ComponentInstanceInput inputValue: inputsValueLis){ + inputsValueList = inputsValueStatus.left().value(); + if(!inputsValueList.isEmpty()){ + for(ComponentInstanceInput inputValue: inputsValueList){ Either<InputValueData, TitanOperationStatus> deleteNode = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.InputValue), inputValue.getValueUniqueUid(), InputValueData.class); if (deleteNode.isRight()) { StorageOperationStatus convertTitanStatusToStorageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(deleteNode.right().value()); return Either.right(convertTitanStatusToStorageStatus); - } + } + } + } + // US848813 delete service input that relates to VL / CP property + } else { + Either<List<ComponentInstanceProperty>, TitanOperationStatus> propertyValueStatus = getComponentInstancePropertiesByInputId(inputId); + if(propertyValueStatus.isLeft() && !propertyValueStatus.left().value().isEmpty()){ + //propertyList = propertyValueStatus.left().value(); + for(ComponentInstanceProperty propertyValue: propertyValueStatus.left().value()){ + + String value = propertyValue.getValue(); + Map<String, Object> mappedToscaTemplate = (Map<String, Object>) new Yaml().load(value); + + resetInputName(mappedToscaTemplate, inputName); + + value = gson.toJson(mappedToscaTemplate); + propertyValue.setValue(value); + String compInstId = propertyValue.getComponentInstanceId(); + propertyValue.setRules(null); + + Either<PropertyValueData, TitanOperationStatus> eitherStatus = componentInstanceOperation.updatePropertyOfResourceInstance(propertyValue, compInstId, false); + + if (eitherStatus.isRight()) { + log.error("Failed to add property value {} to resource instance {} in Graph. status is {}", propertyValue, compInstId, eitherStatus.right().value().name()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherStatus.right().value())); + + } else { + PropertyValueData propertyValueData = eitherStatus.left().value(); + + ComponentInstanceProperty propertyValueResult = propertyOperation.buildResourceInstanceProperty(propertyValueData, propertyValue); + + log.debug("The returned ResourceInstanceProperty is {}", propertyValueResult); + + Either<String, TitanOperationStatus> findDefaultValue = propertyOperation.findDefaultValueFromSecondPosition(propertyValue.getPath(), propertyValueData.getUniqueId(), propertyValue.getDefaultValue()); + if (findDefaultValue.isRight()) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(findDefaultValue.right().value())); + + } + String defaultValue = findDefaultValue.left().value(); + propertyValueResult.setDefaultValue(defaultValue); + log.debug("The returned default value in ResourceInstanceProperty is {}", defaultValue); + + propertyValueResult.setComponentInstanceId(compInstId); + propertyList.add(propertyValueResult); + + + } + } } } @@ -115,7 +211,11 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati StorageOperationStatus convertTitanStatusToStorageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(deleteNode.right().value()); return Either.right(convertTitanStatusToStorageStatus); } else { - return Either.left(inputId); + InputDefinition inputDefinition = this.convertInputDataToInputDefinition(deleteNode.left().value()); + inputDefinition.setInputs(inputsValueList); + inputDefinition.setProperties(propertyList); + inputDefinition.setName(inputName); + return Either.left(inputDefinition); } } @@ -131,7 +231,7 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati StorageOperationStatus validateAndUpdateProperty = validateAndUpdateProperty(propertyDefinition, dataTypes); if (validateAndUpdateProperty != StorageOperationStatus.OK) { - log.error("Property " + propertyDefinition + " is invalid. Status is " + validateAndUpdateProperty); + log.error("Property {} is invalid. Status is {}", propertyDefinition, validateAndUpdateProperty); return Either.right(TitanOperationStatus.INVALID_PROPERTY); } @@ -312,6 +412,8 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati if (createNodeResult.isRight()) { TitanOperationStatus operationStatus = createNodeResult.right().value(); log.error("Failed to add input {} to graph. status is {}", propertyName, operationStatus); + if(operationStatus == TitanOperationStatus.TITAN_SCHEMA_VIOLATION ) + return Either.right(TitanOperationStatus.ALREADY_EXIST); return Either.right(operationStatus); } @@ -447,7 +549,7 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati public <ElementDefinition> TitanOperationStatus findAllResourceElementsDefinitionRecursively(String resourceId, List<ElementDefinition> elements, NodeElementFetcher<ElementDefinition> singleNodeFetcher) { - log.trace("Going to fetch elements under resource {}", resourceId); + log.trace("Going to fetch elements under resource {}" , resourceId); TitanOperationStatus resourceAttributesStatus = singleNodeFetcher.findAllNodeElements(resourceId, elements); if (resourceAttributesStatus != TitanOperationStatus.OK) { @@ -514,7 +616,7 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati } - public TitanOperationStatus associatePropertyToInput(String riId, String inputId, ComponentInstanceProperty property, GetInputValueInfo getInput) { + public TitanOperationStatus associatePropertyToInput(String riId, String inputId, ComponentInstanceProperty property, GetInputValueDataDefinition getInput) { TitanOperationStatus status = TitanOperationStatus.OK; Either<TitanGraph, TitanOperationStatus> graphRes = titanGenericDao.getGraph(); if (graphRes.isRight()) { @@ -536,10 +638,14 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati if(getInput!=null){ props.put(GraphEdgePropertiesDictionary.NAME.getProperty(), getInput.getPropName()); if (getInput.isList()) { - String index = getInput.getIndexValue().toString(); - if (getInput.getGetInputIndex() != null) { - index = getInput.getGetInputIndex().getInputName(); - + String index = ""; + if(getInput.getIndexValue()!= null ){ + index = getInput.getIndexValue().toString(); + }else{ + if (getInput.getGetInputIndex() != null) { + index = getInput.getGetInputIndex().getInputName(); + + } } props.put(GraphEdgePropertiesDictionary.GET_INPUT_INDEX.getProperty(), index); } @@ -627,7 +733,7 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati } - groupDefinition.setInputsValue(propsList); + groupDefinition.setInputs(propsList); } } @@ -704,7 +810,7 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati Either<List<ComponentInstanceInput>, TitanOperationStatus> getAllRes = getAllInputsOfResourceInstanceOnlyInputDefId(resourceInstanceId); if (getAllRes.isRight()) { TitanOperationStatus status = getAllRes.right().value(); - log.trace("After fetching all properties of resource instance {}. Status is {}", resourceInstanceId, status); + log.trace("After fetching all properties of resource instance {}. Status is {}" ,resourceInstanceId, status); return new ImmutablePair<TitanOperationStatus, String>(status, null); } @@ -713,7 +819,7 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati for (ComponentInstanceInput instanceProperty : list) { String propertyUniqueId = instanceProperty.getUniqueId(); String valueUniqueUid = instanceProperty.getValueUniqueUid(); - log.trace("Go over property {} under resource instance {}. valueUniqueId = {}", propertyUniqueId, resourceInstanceId, valueUniqueUid); + log.trace("Go over property {} under resource instance {}. valueUniqueId = {}" ,propertyUniqueId, resourceInstanceId, valueUniqueUid); if (propertyId.equals(propertyUniqueId) && valueUniqueUid != null) { log.debug("The property {} already created under resource instance {}", propertyId, resourceInstanceId); return new ImmutablePair<TitanOperationStatus, String>(TitanOperationStatus.ALREADY_EXIST, valueUniqueUid); @@ -1031,19 +1137,36 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati PropertyValueData propertyValueData = propertyValueDataPair.left; String propertyValueUid = propertyValueData.getUniqueId(); String value = propertyValueData.getValue(); + + String componentInstanceId = (String) propertyValueDataPair.right.getProperties().get(GraphEdgePropertiesDictionary.OWNER_ID.getProperty()); Either<ImmutablePair<PropertyData, GraphEdge>, TitanOperationStatus> propertyDefRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PropertyValue), propertyValueUid, GraphEdgeLabels.PROPERTY_IMPL, NodeTypeEnum.Property, PropertyData.class); if (propertyDefRes.isRight()) { TitanOperationStatus status = propertyDefRes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } return Either.right(status); } ImmutablePair<PropertyData, GraphEdge> propertyDefPair = propertyDefRes.left().value(); PropertyData propertyData = propertyDefPair.left; String propertyUniqueId = (String) propertyData.getPropertyDataDefinition().getUniqueId(); + + Either<TitanVertex, TitanOperationStatus> originVertexEither = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), propertyUniqueId); + if (originVertexEither.isRight()) { + log.debug("Failed to fetch vertex of property for id {} error {}", propertyUniqueId, originVertexEither.right().value()); + return Either.right(originVertexEither.right().value()); + } + TitanVertex originVertex = originVertexEither.left().value(); + Iterator<Edge> edgeIter = originVertex.edges(Direction.IN, GraphEdgeLabels.PROPERTY.getProperty()); + if (edgeIter == null) { + return Either.right(TitanOperationStatus.NOT_FOUND); + } + + String propertyName = ""; + + while (edgeIter.hasNext()) { + TitanEdge edge = (TitanEdge) edgeIter.next(); + propertyName = (String) edge.property(GraphEdgePropertiesDictionary.NAME.getProperty()).value(); + } ComponentInstanceProperty resourceInstanceProperty = new ComponentInstanceProperty(); // set property original unique id @@ -1059,7 +1182,9 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati resourceInstanceProperty.setRules(propertyValueData.getRules()); resourceInstanceProperty.setType(propertyData.getPropertyDataDefinition().getType()); resourceInstanceProperty.setSchema(propertyData.getPropertyDataDefinition().getSchema()); - resourceInstanceProperty.setName((String) propertyValueDataPair.right.getProperties().get(GraphPropertiesDictionary.NAME.getProperty())); + resourceInstanceProperty.setName(propertyName); + resourceInstanceProperty.setComponentInstanceId(componentInstanceId); + result.add(resourceInstanceProperty); } @@ -1091,10 +1216,22 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati if (newInputsMap != null && !newInputsMap.isEmpty()) { for (Entry<String, List<InputDefinition>> entry : newInputsMap.entrySet()) { String compInstId = entry.getKey(); + Either<TitanVertex, TitanOperationStatus> ciVertexEither = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), compInstId); + if (ciVertexEither.isRight()) { + log.debug("Failed to fetch vertex of resource instance for id {} error {}", compInstId, ciVertexEither.right().value()); + return Either.right( DaoStatusConverter.convertTitanStatusToStorageStatus(ciVertexEither.right().value())); + } + TitanVertex ciVertex = ciVertexEither.left().value(); + + + //String originType = (String) titanGenericDao.getProperty(originVertex, GraphPropertiesDictionary.LABEL.getProperty()); + String compInstname = (String) titanGenericDao.getProperty(ciVertex, GraphPropertiesDictionary.NORMALIZED_NAME.getProperty()); + List<InputDefinition> inputs = entry.getValue(); if (inputs != null && !inputs.isEmpty()) { for (InputDefinition input : inputs) { + Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(compInstId, GraphPropertiesDictionary.INPUT_COUNTER, true); if (counterRes.isRight()) { @@ -1109,9 +1246,13 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(oldInputEither.right().value())); } - JSONObject jobject = new JSONObject(); - jobject.put("get_input", input.getName()); + InputDefinition oldInput = oldInputEither.left().value(); + String serviceInputName = compInstname + "_" + input.getName(); + input.setName(serviceInputName); + + JSONObject jobject = new JSONObject(); + jobject.put(GET_INPUT, input.getName()); ComponentInstanceInput inputValue = new ComponentInstanceInput(oldInput, jobject.toJSONString(), null); Integer index = counterRes.left().value(); @@ -1125,13 +1266,6 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati } ComponentInstanceInput inputValueData = eitherStatus.left().value(); - // ComponentInstanceInput propertyValueResult = - // buildResourceInstanceInput(propertyValueData, - // inputValue); - // log.debug("The returned ResourceInstanceProperty is " - // + propertyValueResult); - - String inputName = input.getName(); input.setSchema(oldInputEither.left().value().getSchema()); input.setDefaultValue(oldInput.getDefaultValue()); input.setConstraints(oldInput.getConstraints()); @@ -1147,13 +1281,13 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati return Either.right(validateAndUpdateProperty); } - Either<InputsData, TitanOperationStatus> addPropertyToGraph = addInputToGraph(inputName, input, resourceId, nodeType); + Either<InputsData, TitanOperationStatus> addPropertyToGraph = addInputToGraph(serviceInputName, input, resourceId, nodeType); if (addPropertyToGraph.isRight()) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(addPropertyToGraph.right().value())); } InputDefinition createdInputyDefinition = convertInputDataToInputDefinition(addPropertyToGraph.left().value()); - createdInputyDefinition.setName(inputName); + createdInputyDefinition.setName(serviceInputName); createdInputyDefinition.setParentUniqueId(resourceId); Map<String, Object> props = new HashMap<String, Object>(); @@ -1178,7 +1312,275 @@ public class InputsOperation extends AbstractOperation implements IInputsOperati } } + Map<String, List<ComponentInstancePropInput>> newInputsPropsMap = componentInsInputs.getComponentInstanceProperties(); + if (newInputsPropsMap != null && !newInputsPropsMap.isEmpty()) { + Either<List<InputDefinition>, StorageOperationStatus> result = createInputsFromProperty(resourceId, nodeType, dataTypes, resList, newInputsPropsMap); + + if (result.isRight()) { + log.debug("Failed to create inputs of resource for id {} error {}", resourceId, result.right().value()); + return result; + } + resList = result.left().value(); + + } return Either.left(resList); } + private Either<List<InputDefinition>, StorageOperationStatus> createInputsFromProperty(String resourceId, NodeTypeEnum nodeType, Map<String, DataTypeDefinition> dataTypes, List<InputDefinition> resList, Map<String, List<ComponentInstancePropInput>> newInputsPropsMap) { + for (Entry<String, List<ComponentInstancePropInput>> entry : newInputsPropsMap.entrySet()) { + String compInstId = entry.getKey(); + List<ComponentInstancePropInput> properties = entry.getValue(); + + Either<TitanVertex, TitanOperationStatus> ciVertexEither = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), compInstId); + if (ciVertexEither.isRight()) { + log.debug("Failed to fetch vertex of resource instance for id {} error {}", compInstId, ciVertexEither.right().value()); + return Either.right( DaoStatusConverter.convertTitanStatusToStorageStatus(ciVertexEither.right().value())); + } + TitanVertex ciVertex = ciVertexEither.left().value(); + + + //String originType = (String) titanGenericDao.getProperty(originVertex, GraphPropertiesDictionary.LABEL.getProperty()); + String compInstname = (String) titanGenericDao.getProperty(ciVertex, GraphPropertiesDictionary.NORMALIZED_NAME.getProperty()); + String inputName = compInstname; + + if (properties != null && !properties.isEmpty()) { + for (ComponentInstancePropInput propInput : properties) { + Either<InputDefinition, StorageOperationStatus> createInputRes = createInputForComponentInstance(resourceId, nodeType, dataTypes, compInstId, inputName, propInput); + + if (createInputRes.isRight()) { + log.debug("Failed to create input of resource instance for id {} error {}", compInstId, createInputRes.right().value()); + return Either.right(createInputRes.right().value()); + } + + resList.add(createInputRes.left().value()); + + } + } + + } + return Either.left(resList); + } + + private Either<InputDefinition, StorageOperationStatus> createInputForComponentInstance(String resourceId, NodeTypeEnum nodeType, Map<String, DataTypeDefinition> dataTypes, String compInstId, String inputName, ComponentInstancePropInput propInput) { + String propertiesName = propInput.getPropertiesName() ; + PropertyDefinition selectedProp = propInput.getInput(); + String[] parsedPropNames = propInput.getParsedPropNames(); + if(parsedPropNames != null){ + for(String str: parsedPropNames){ + inputName += "_" + str; + } + } else { + inputName += "_" + propInput.getName(); + } + + InputDefinition input = null; + ComponentInstanceProperty prop = propInput; + + if(propertiesName != null && !propertiesName.isEmpty() && selectedProp != null){ + input = new InputDefinition(selectedProp); + }else{ + input = new InputDefinition(prop); + input.setName(inputName + "_" + prop.getName()); + + } + input.setName(inputName); + + JSONObject jobject = new JSONObject(); + + + if(prop.getValueUniqueUid() == null || prop.getValueUniqueUid().isEmpty()){ + if(propertiesName != null && !propertiesName.isEmpty() && selectedProp != null){ + + jobject = createJSONValueForProperty(parsedPropNames.length -1, parsedPropNames, jobject, inputName); + prop.setValue(jobject.toJSONString()); + + }else{ + + jobject.put(GET_INPUT, input.getName()); + prop.setValue(jobject.toJSONString()); + + + } + Either<Integer, StorageOperationStatus> increaseCounterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(compInstId, GraphPropertiesDictionary.PROPERTY_COUNTER, true); + if (increaseCounterRes.isRight()) { + log.debug("Failed to increase resource property counter {} to resource instance {}", prop, compInstId); + + return Either.right( increaseCounterRes.right().value()); + } + Integer index = increaseCounterRes.left().value(); + Either<ComponentInstanceProperty, StorageOperationStatus> result = componentInstanceOperation.addPropertyValueToResourceInstance(prop, compInstId, false, index, true); + if (result.isRight()) { + log.debug("Failed to add property value {} to resource instance {}", prop, compInstId); + return Either.right( result.right().value()); + } + prop = result.left().value(); + + }else{ + + String value = prop.getValue(); + if(value != null){ + Object objValue = new Yaml().load(value); + if( objValue instanceof Map || objValue instanceof List ){ + if(propertiesName == null ||propertiesName.isEmpty()){ + jobject.put(GET_INPUT, input.getName()); + prop.setValue(jobject.toJSONString()); + prop.setRules(null); + + }else{ + Map<String, Object> mappedToscaTemplate = (Map<String, Object>) objValue; + createInputValue(mappedToscaTemplate, 1, parsedPropNames, inputName); + Gson gson = new Gson(); + String json = gson.toJson(mappedToscaTemplate); + prop.setValue(json); + prop.setRules(null); + } + + }else{ + jobject.put(GET_INPUT, input.getName()); + prop.setValue(jobject.toJSONString()); + prop.setRules(null); + } + }else{ + jobject.put(GET_INPUT, input.getName()); + prop.setValue(jobject.toJSONString()); + prop.setRules(null); + } + + Either<PropertyValueData, TitanOperationStatus> eitherStatus = componentInstanceOperation.updatePropertyOfResourceInstance(prop, compInstId, false); + + if (eitherStatus.isRight()) { + log.error("Failed to add property value {} to resource instance {} in Graph. status is {}", prop, compInstId, eitherStatus.right().value().name()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherStatus.right().value())); + + } else { + PropertyValueData propertyValueData = eitherStatus.left().value(); + + prop = propertyOperation.buildResourceInstanceProperty(propertyValueData, prop); + + log.debug("The returned ResourceInstanceProperty is {}", prop); + + Either<String, TitanOperationStatus> findDefaultValue = propertyOperation.findDefaultValueFromSecondPosition(prop.getPath(), propertyValueData.getUniqueId(), prop.getDefaultValue()); + if (findDefaultValue.isRight()) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(findDefaultValue.right().value())); + + } + String defaultValue = findDefaultValue.left().value(); + prop.setDefaultValue(defaultValue); + log.debug("The returned default value in ResourceInstanceProperty is {}", defaultValue); + + prop.setComponentInstanceId(compInstId); + + + + } + + + } + + StorageOperationStatus validateAndUpdateProperty = validateAndUpdateProperty(input, dataTypes); + if (validateAndUpdateProperty != StorageOperationStatus.OK) { + log.error("Property {} is invalid. Status is {}", input, validateAndUpdateProperty); + return Either.right(validateAndUpdateProperty); + } + + Either<InputsData, TitanOperationStatus> addPropertyToGraph = addInputToGraph(input.getName(), input, resourceId, nodeType); + + if (addPropertyToGraph.isRight()) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(addPropertyToGraph.right().value())); + } + InputDefinition createdInputyDefinition = convertInputDataToInputDefinition(addPropertyToGraph.left().value()); + createdInputyDefinition.setName(input.getName()); + createdInputyDefinition.setParentUniqueId(resourceId); + + TitanOperationStatus status = associatePropertyToInput(compInstId, createdInputyDefinition.getUniqueId(), prop, null); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to associate input {} tp property value{} ", createdInputyDefinition.getName(), prop.getValueUniqueUid()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + + return Either.left(createdInputyDefinition); + + } + + private JSONObject createJSONValueForProperty (int i, String [] parsedPropNames, JSONObject ooj, String inputName){ + + while(i >= 1){ + if( i == parsedPropNames.length -1){ + JSONObject jobProp = new JSONObject(); + jobProp.put(GET_INPUT, inputName); + ooj.put(parsedPropNames[i], jobProp); + i--; + return createJSONValueForProperty (i, parsedPropNames, ooj, inputName); + }else{ + JSONObject res = new JSONObject(); + res.put(parsedPropNames[i], ooj); + i --; + res = createJSONValueForProperty (i, parsedPropNames, res, inputName); + return res; + } + } + + return ooj; + } + + public void resetInputName(Map<String, Object> lhm1, String inputName){ + for (Map.Entry<String, Object> entry : lhm1.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + if (value instanceof String && ((String) value).equalsIgnoreCase(inputName) && key.equals(GET_INPUT)) { + value = ""; + lhm1.remove(key); + } else if (value instanceof Map) { + Map<String, Object> subMap = (Map<String, Object>)value; + resetInputName(subMap, inputName); + } else { + continue; + } + + } + } + + private Map<String, Object> createInputValue(Map<String, Object> lhm1, int index, String[] inputNames, String inputName){ + while(index < inputNames.length){ + if(lhm1.containsKey(inputNames[index])){ + Object value = lhm1.get(inputNames[index]); + if (value instanceof Map){ + if(index == inputNames.length -1){ + ((Map) value).put(GET_INPUT, inputName); + return ((Map) value); + + }else{ + index++; + return createInputValue((Map)value, index, inputNames, inputName); + } + }else{ + Map<String, Object> jobProp = new HashMap<>(); + if(index == inputNames.length -1){ + jobProp.put(GET_INPUT, inputName); + lhm1.put(inputNames[index], jobProp); + return lhm1; + }else{ + lhm1.put(inputNames[index], jobProp); + index++; + return createInputValue(jobProp, index, inputNames, inputName); + } + } + }else{ + Map<String, Object> jobProp = new HashMap<>(); + lhm1.put(inputNames[index], jobProp); + if(index == inputNames.length -1){ + jobProp.put(GET_INPUT, inputName); + return jobProp; + }else{ + index++; + return createInputValue(jobProp, index, inputNames, inputName); + } + } + } + return lhm1; + } + + + + } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InterfaceLifecycleOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InterfaceLifecycleOperation.java index 0d29c18a95..a7c883b14e 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InterfaceLifecycleOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InterfaceLifecycleOperation.java @@ -27,12 +27,7 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Set; -import com.thinkaurelius.titan.core.TitanTransaction; -import com.thinkaurelius.titan.core.TitanVertex; - -import org.apache.cassandra.transport.Event.StatusChange; import org.apache.commons.lang3.tuple.ImmutablePair; -import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation; @@ -56,6 +51,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; +import com.thinkaurelius.titan.core.TitanVertex; + import fj.data.Either; @Component("interface-operation") @@ -74,45 +71,40 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation private TitanGenericDao titanGenericDao; @Override - public Either<InterfaceDefinition, StorageOperationStatus> addInterfaceToResource(InterfaceDefinition interf, - String resourceId, String interfaceName) { + public Either<InterfaceDefinition, StorageOperationStatus> addInterfaceToResource(InterfaceDefinition interf, String resourceId, String interfaceName) { return addInterfaceToResource(interf, resourceId, interfaceName, false); } @Override - public Either<InterfaceDefinition, StorageOperationStatus> addInterfaceToResource(InterfaceDefinition interf, - String resourceId, String interfaceName, boolean inTransaction) { + public Either<InterfaceDefinition, StorageOperationStatus> addInterfaceToResource(InterfaceDefinition interf, String resourceId, String interfaceName, boolean inTransaction) { return createInterfaceOnResource(interf, resourceId, interfaceName, true, inTransaction); } - private Either<OperationData, TitanOperationStatus> addOperationToGraph(InterfaceDefinition interf, String opName, - Operation op, InterfaceData interfaceData) { + private Either<OperationData, TitanOperationStatus> addOperationToGraph(InterfaceDefinition interf, String opName, Operation op, InterfaceData interfaceData) { op.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId((String) interfaceData.getUniqueId(), opName)); OperationData operationData = new OperationData(op); log.debug("Before adding operation to graph {}", operationData); - Either<OperationData, TitanOperationStatus> createOpNodeResult = titanGenericDao.createNode(operationData, - OperationData.class); + Either<OperationData, TitanOperationStatus> createOpNodeResult = titanGenericDao.createNode(operationData, OperationData.class); log.debug("After adding operation to graph {}", operationData); if (createOpNodeResult.isRight()) { TitanOperationStatus opStatus = createOpNodeResult.right().value(); - log.error("Failed to add operation {} to graph. Status is {}", opName, opStatus); + log.error("Failed to add operation {} to graph. status is {}", opName, opStatus); return Either.right(opStatus); } Map<String, Object> props = new HashMap<String, Object>(); props.put(GraphPropertiesDictionary.NAME.getProperty(), opName); - Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(interfaceData, - operationData, GraphEdgeLabels.INTERFACE_OPERATION, props); + Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(interfaceData, operationData, GraphEdgeLabels.INTERFACE_OPERATION, props); if (createRelResult.isRight()) { TitanOperationStatus operationStatus = createOpNodeResult.right().value(); - log.error("Failed to associate operation {} to property {} in graph. Status is {}", interfaceData.getUniqueId(), opName, operationStatus); + log.error("Failed to associate operation {} to property {} in graph. status is {}", interfaceData.getUniqueId(), opName, operationStatus); return Either.right(operationStatus); } @@ -121,11 +113,9 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation } - private Either<TitanVertex, TitanOperationStatus> addOperationToGraph(InterfaceDefinition interf, String opName, - Operation op, TitanVertex interfaceVertex) { + private Either<TitanVertex, TitanOperationStatus> addOperationToGraph(InterfaceDefinition interf, String opName, Operation op, TitanVertex interfaceVertex) { - String interfaceId = (String) titanGenericDao.getProperty(interfaceVertex, - GraphPropertiesDictionary.UNIQUE_ID.getProperty()); + String interfaceId = (String) titanGenericDao.getProperty(interfaceVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty()); op.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(interfaceId, opName)); OperationData operationData = new OperationData(op); @@ -141,12 +131,10 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation Map<String, Object> props = new HashMap<String, Object>(); props.put(GraphPropertiesDictionary.NAME.getProperty(), opName); TitanVertex operationVertex = createOpNodeResult.left().value(); - TitanOperationStatus createRelResult = titanGenericDao.createEdge(interfaceVertex, operationVertex, - GraphEdgeLabels.INTERFACE_OPERATION, props); + TitanOperationStatus createRelResult = titanGenericDao.createEdge(interfaceVertex, operationVertex, GraphEdgeLabels.INTERFACE_OPERATION, props); if (!createRelResult.equals(TitanOperationStatus.OK)) { - log.error("Failed to associate operation {} to property {} in graph. status is {}", interfaceId, opName, - createRelResult); + log.error("Failed to associate operation {} to property {} in graph. status is {}", interfaceId, opName, createRelResult); return Either.right(createRelResult); } @@ -173,8 +161,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation } - private Either<InterfaceData, TitanOperationStatus> addInterfaceToGraph(InterfaceDefinition interfaceInfo, - String interfaceName, String resourceId) { + private Either<InterfaceData, TitanOperationStatus> addInterfaceToGraph(InterfaceDefinition interfaceInfo, String interfaceName, String resourceId) { InterfaceData interfaceData = new InterfaceData(interfaceInfo); @@ -185,8 +172,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation interfaceInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, interfaceNameSplitted)); - Either<InterfaceData, TitanOperationStatus> existInterface = titanGenericDao - .getNode(interfaceData.getUniqueIdKey(), interfaceData.getUniqueId(), InterfaceData.class); + Either<InterfaceData, TitanOperationStatus> existInterface = titanGenericDao.getNode(interfaceData.getUniqueIdKey(), interfaceData.getUniqueId(), InterfaceData.class); if (existInterface.isRight()) { @@ -197,8 +183,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation } } - private Either<TitanVertex, TitanOperationStatus> addInterfaceToGraph(InterfaceDefinition interfaceInfo, - String interfaceName, String resourceId, TitanVertex metadataVertex) { + private Either<TitanVertex, TitanOperationStatus> addInterfaceToGraph(InterfaceDefinition interfaceInfo, String interfaceName, String resourceId, TitanVertex metadataVertex) { InterfaceData interfaceData = new InterfaceData(interfaceInfo); @@ -206,8 +191,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation interfaceInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, interfaceNameSplitted)); - Either<TitanVertex, TitanOperationStatus> existInterface = titanGenericDao - .getVertexByProperty(interfaceData.getUniqueIdKey(), interfaceData.getUniqueId()); + Either<TitanVertex, TitanOperationStatus> existInterface = titanGenericDao.getVertexByProperty(interfaceData.getUniqueIdKey(), interfaceData.getUniqueId()); if (existInterface.isRight()) { @@ -218,26 +202,23 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation } } - private Either<InterfaceData, TitanOperationStatus> createInterfaceNodeAndRelation(String interfaceName, - String resourceId, InterfaceData interfaceData, ResourceMetadataData resourceData) { + private Either<InterfaceData, TitanOperationStatus> createInterfaceNodeAndRelation(String interfaceName, String resourceId, InterfaceData interfaceData, ResourceMetadataData resourceData) { log.debug("Before adding interface to graph {}", interfaceData); - Either<InterfaceData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(interfaceData, - InterfaceData.class); + Either<InterfaceData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(interfaceData, InterfaceData.class); log.debug("After adding property to graph {}", interfaceData); if (createNodeResult.isRight()) { TitanOperationStatus operationStatus = createNodeResult.right().value(); - log.error("Failed to add interface {} to graph. Status is {}", interfaceName, operationStatus); + log.error("Failed to add interface {} to graph. status is {}", interfaceName, operationStatus); return Either.right(operationStatus); } Map<String, Object> props = new HashMap<String, Object>(); props.put(GraphPropertiesDictionary.NAME.getProperty(), interfaceName); - Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(resourceData, - interfaceData, GraphEdgeLabels.INTERFACE, props); + Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(resourceData, interfaceData, GraphEdgeLabels.INTERFACE, props); if (createRelResult.isRight()) { TitanOperationStatus operationStatus = createNodeResult.right().value(); - log.error("Failed to associate resource {} to property {} in graph. Status is {}", resourceId, interfaceName, operationStatus); + log.error("Failed to associate resource {} to property {} in graph. status is {}", resourceId, interfaceName, operationStatus); return Either.right(operationStatus); } @@ -245,8 +226,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation return Either.left(createNodeResult.left().value()); } - private Either<TitanVertex, TitanOperationStatus> createInterfaceNodeAndRelation(String interfaceName, - String resourceId, InterfaceData interfaceData, TitanVertex metadataVertex) { + private Either<TitanVertex, TitanOperationStatus> createInterfaceNodeAndRelation(String interfaceName, String resourceId, InterfaceData interfaceData, TitanVertex metadataVertex) { log.debug("Before adding interface to graph {}", interfaceData); Either<TitanVertex, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(interfaceData); @@ -259,35 +239,30 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation Map<String, Object> props = new HashMap<String, Object>(); props.put(GraphPropertiesDictionary.NAME.getProperty(), interfaceName); TitanVertex interfaceVertex = createNodeResult.left().value(); - TitanOperationStatus createRelResult = titanGenericDao.createEdge(metadataVertex, interfaceVertex, - GraphEdgeLabels.INTERFACE, props); + TitanOperationStatus createRelResult = titanGenericDao.createEdge(metadataVertex, interfaceVertex, GraphEdgeLabels.INTERFACE, props); if (!createRelResult.equals(TitanOperationStatus.OK)) { - log.error("Failed to associate resource {} to property {} in graph. status is {}", resourceId, - interfaceName, createRelResult); + log.error("Failed to associate resource {} to property {} in graph. status is {}", resourceId, interfaceName, createRelResult); } return Either.left(interfaceVertex); } - private Either<OperationData, TitanOperationStatus> createOperationNodeAndRelation(String operationName, - OperationData operationData, InterfaceData interfaceData) { + private Either<OperationData, TitanOperationStatus> createOperationNodeAndRelation(String operationName, OperationData operationData, InterfaceData interfaceData) { log.debug("Before adding operation to graph {}", operationData); - Either<OperationData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(operationData, - OperationData.class); + Either<OperationData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(operationData, OperationData.class); log.debug("After adding operation to graph {}", interfaceData); if (createNodeResult.isRight()) { TitanOperationStatus operationStatus = createNodeResult.right().value(); - log.error("Failed to add interfoperationce {} to graph. Status is {}", operationName, operationStatus); + log.error("Failed to add interfoperationce {} to graph. status is {}", operationName, operationStatus); return Either.right(operationStatus); } Map<String, Object> props = new HashMap<String, Object>(); props.put(GraphPropertiesDictionary.NAME.getProperty(), operationName); - Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(interfaceData, - operationData, GraphEdgeLabels.INTERFACE_OPERATION, props); + Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(interfaceData, operationData, GraphEdgeLabels.INTERFACE_OPERATION, props); if (createRelResult.isRight()) { TitanOperationStatus operationStatus = createNodeResult.right().value(); - log.error("Failed to associate operation {} to interface {} in graph. Status is {}", operationName, interfaceData.getUniqueId(), operationStatus); + log.error("Failed to associate operation {} to interface {} in graph. status is {}", operationName, interfaceData.getUniqueId(), operationStatus); return Either.right(operationStatus); } @@ -307,7 +282,8 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation // * InterfaceData propertyData = getResult.left().value(); return // * Either.left(convertPropertyDataToPropertyDefinition(propertyData)); } // * else { TitanOperationStatus titanStatus = getResult.right().value(); - // * log.debug("Node with id {} was not found in the graph. Status: {}", propertyId, titanStatus); + // * log.debug("Node with id " + propertyId + + // * " was not found in the graph. status: " + titanStatus); // * StorageOperationStatus storageOperationStatus = // * DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus); // * return Either.right(storageOperationStatus); } @@ -323,14 +299,12 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation // } @Override - public Either<Map<String, InterfaceDefinition>, StorageOperationStatus> getAllInterfacesOfResource( - String resourceIdn, boolean recursively) { + public Either<Map<String, InterfaceDefinition>, StorageOperationStatus> getAllInterfacesOfResource(String resourceIdn, boolean recursively) { return getAllInterfacesOfResource(resourceIdn, recursively, false); } @Override - public Either<Map<String, InterfaceDefinition>, StorageOperationStatus> getAllInterfacesOfResource( - String resourceId, boolean recursively, boolean inTransaction) { + public Either<Map<String, InterfaceDefinition>, StorageOperationStatus> getAllInterfacesOfResource(String resourceId, boolean recursively, boolean inTransaction) { Either<Map<String, InterfaceDefinition>, StorageOperationStatus> result = null; Map<String, InterfaceDefinition> interfaces = new HashMap<String, InterfaceDefinition>(); @@ -348,7 +322,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation findInterfacesRes = findAllInterfacesNotRecursively(resourceId, interfaces); } if (!findInterfacesRes.equals(TitanOperationStatus.OK)) { - log.error("Failed to get all interfaces of resource {}. Status is {}", resourceId, findInterfacesRes); + log.error("Failed to get all interfaces of resource {}. status is {}", resourceId, findInterfacesRes); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(findInterfacesRes)); return result; } @@ -367,12 +341,10 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation } } - private TitanOperationStatus findAllInterfacesNotRecursively(String resourceId, - Map<String, InterfaceDefinition> interfaces) { + private TitanOperationStatus findAllInterfacesNotRecursively(String resourceId, Map<String, InterfaceDefinition> interfaces) { - Either<List<ImmutablePair<InterfaceData, GraphEdge>>, TitanOperationStatus> interfaceNodes = titanGenericDao - .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, - GraphEdgeLabels.INTERFACE, NodeTypeEnum.Interface, InterfaceData.class); + Either<List<ImmutablePair<InterfaceData, GraphEdge>>, TitanOperationStatus> interfaceNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.INTERFACE, + NodeTypeEnum.Interface, InterfaceData.class); if (interfaceNodes.isRight()) { TitanOperationStatus status = interfaceNodes.right().value(); @@ -384,15 +356,13 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation if (interfaceList != null) { for (ImmutablePair<InterfaceData, GraphEdge> interfacePair : interfaceList) { String interfaceUniqueId = (String) interfacePair.getKey().getUniqueId(); - Either<String, TitanOperationStatus> interfaceNameRes = getPropertyValueFromEdge( - interfacePair.getValue(), GraphPropertiesDictionary.NAME); + Either<String, TitanOperationStatus> interfaceNameRes = getPropertyValueFromEdge(interfacePair.getValue(), GraphPropertiesDictionary.NAME); if (interfaceNameRes.isRight()) { log.error("The requirement name is missing on the edge of requirement {}", interfaceUniqueId); return interfaceNameRes.right().value(); } String interfaceName = interfaceNameRes.left().value(); - Either<InterfaceDefinition, TitanOperationStatus> interfaceDefRes = getNonRecursiveInterface( - interfacePair.getKey()); + Either<InterfaceDefinition, TitanOperationStatus> interfaceDefRes = getNonRecursiveInterface(interfacePair.getKey()); if (interfaceDefRes.isRight()) { TitanOperationStatus status = interfaceDefRes.right().value(); log.error("Failed to get interface actions of interface {}", interfaceUniqueId); @@ -401,7 +371,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation InterfaceDefinition interfaceDefinition = interfaceDefRes.left().value(); if (true == interfaces.containsKey(interfaceName)) { - log.debug("The interface {} was already defined in derived resource. add not overriden operations", interfaceName); + log.debug("The interface {} was already defined in dervied resource. add not overriden operations", interfaceName); InterfaceDefinition existInterface = interfaces.get(interfaceName); addMissingOperationsToInterface(interfaceDefinition, existInterface); } else { @@ -414,17 +384,15 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation return TitanOperationStatus.OK; } - public TitanOperationStatus findAllInterfacesRecursively(String resourceId, - Map<String, InterfaceDefinition> interfaces) { + public TitanOperationStatus findAllInterfacesRecursively(String resourceId, Map<String, InterfaceDefinition> interfaces) { TitanOperationStatus findAllInterfacesNotRecursively = findAllInterfacesNotRecursively(resourceId, interfaces); if (!findAllInterfacesNotRecursively.equals(TitanOperationStatus.OK)) { - log.error("failed to get interfaces for resource {}. Status is {}", resourceId, findAllInterfacesNotRecursively); + log.error("failed to get interfaces for resource {}. status is {}", resourceId, findAllInterfacesNotRecursively); } - Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> parentNodes = titanGenericDao - .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, - GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource, ResourceMetadataData.class); + Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> parentNodes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource, + ResourceMetadataData.class); if (parentNodes.isRight()) { TitanOperationStatus parentNodesStatus = parentNodes.right().value(); @@ -432,7 +400,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation log.debug("Finish to lookup for parnet interfaces"); return TitanOperationStatus.OK; } else { - log.error("Failed to find parent interfaces of resource {}. Status is {}", resourceId, parentNodesStatus); + log.error("Failed to find parent interfaces of resource {}. status is {}", resourceId, parentNodesStatus); return parentNodesStatus; } } @@ -448,8 +416,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation return TitanOperationStatus.OK; } - private Either<String, TitanOperationStatus> getPropertyValueFromEdge(GraphEdge edge, - GraphPropertiesDictionary property) { + private Either<String, TitanOperationStatus> getPropertyValueFromEdge(GraphEdge edge, GraphPropertiesDictionary property) { Map<String, Object> edgeProps = edge.getProperties(); String interfaceName = null; if (edgeProps != null) { @@ -469,9 +436,8 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation InterfaceDefinition interfaceDefinition = new InterfaceDefinition(interfaceData.getInterfaceDataDefinition()); String interfaceId = interfaceData.getUniqueId(); - Either<List<ImmutablePair<OperationData, GraphEdge>>, TitanOperationStatus> operationsRes = titanGenericDao - .getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), interfaceId, - GraphEdgeLabels.INTERFACE_OPERATION, NodeTypeEnum.InterfaceOperation, OperationData.class); + Either<List<ImmutablePair<OperationData, GraphEdge>>, TitanOperationStatus> operationsRes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), interfaceId, GraphEdgeLabels.INTERFACE_OPERATION, + NodeTypeEnum.InterfaceOperation, OperationData.class); if (operationsRes.isRight()) { TitanOperationStatus status = operationsRes.right().value(); @@ -486,8 +452,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation if (operationList != null && !operationList.isEmpty()) { for (ImmutablePair<OperationData, GraphEdge> operationPair : operationList) { Operation operation = new Operation(operationPair.getKey().getOperationDataDefinition()); - Either<String, TitanOperationStatus> operationNameRes = getPropertyValueFromEdge( - operationPair.getValue(), GraphPropertiesDictionary.NAME); + Either<String, TitanOperationStatus> operationNameRes = getPropertyValueFromEdge(operationPair.getValue(), GraphPropertiesDictionary.NAME); if (operationNameRes.isRight()) { log.error("The operation name is missing on the edge of operation {}", operationPair.getKey().getUniqueId()); return Either.right(operationNameRes.right().value()); @@ -504,11 +469,9 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation private StorageOperationStatus findOperationImplementation(Operation operation) { String operationId = operation.getUniqueId(); - Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsRes = artifactOperation - .getArtifacts(operationId, NodeTypeEnum.InterfaceOperation, true); + Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsRes = artifactOperation.getArtifacts(operationId, NodeTypeEnum.InterfaceOperation, true); if (artifactsRes.isRight() || artifactsRes.left().value() == null) { - log.error("failed to get artifact from graph for operation id {}. status is {}", operationId, - artifactsRes.right().value()); + log.error("failed to get artifact from graph for operation id {}. status is {}", operationId, artifactsRes.right().value()); return artifactsRes.right().value(); } else { Map<String, ArtifactDefinition> artifacts = artifactsRes.left().value(); @@ -521,10 +484,9 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation return StorageOperationStatus.OK; } - private StorageOperationStatus addMissingOperationsToInterface(InterfaceDefinition interfaceDefinition, - InterfaceDefinition existInterface) { - Map<String, Operation> existOperations = existInterface.getOperations(); - Map<String, Operation> operations = interfaceDefinition.getOperations(); + private StorageOperationStatus addMissingOperationsToInterface(InterfaceDefinition interfaceDefinition, InterfaceDefinition existInterface) { + Map<String, Operation> existOperations = existInterface.getOperationsMap(); + Map<String, Operation> operations = interfaceDefinition.getOperationsMap(); if (operations != null && !operations.isEmpty()) { Set<Entry<String, Operation>> operationsSet = operations.entrySet(); for (Entry<String, Operation> operation : operationsSet) { @@ -537,29 +499,22 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation } @Override - public Either<Operation, StorageOperationStatus> updateInterfaceOperation(String resourceId, String interfaceName, - String operationName, Operation interf) { + public Either<Operation, StorageOperationStatus> updateInterfaceOperation(String resourceId, String interfaceName, String operationName, Operation interf) { return updateInterfaceOperation(resourceId, interfaceName, operationName, interf, false); } @Override - public Either<Operation, StorageOperationStatus> updateInterfaceOperation(String resourceId, String interfaceName, - String operationName, Operation operation, boolean inTransaction) { - Either<Operation, StorageOperationStatus> status = updateOperationOnGraph(operation, resourceId, interfaceName, - operationName); + public Either<Operation, StorageOperationStatus> updateInterfaceOperation(String resourceId, String interfaceName, String operationName, Operation operation, boolean inTransaction) { + Either<Operation, StorageOperationStatus> status = updateOperationOnGraph(operation, resourceId, interfaceName, operationName); /* - * if (status.isRight()) { if (false == inTransaction) { - * titanGenericDao.rollback(); } log.error("Failed to update operation " - * + operationName + " of interfaceName " + interfaceName + - * " of resource" + resourceId); return Either.right(DaoStatusConverter - * .convertTitanStatusToStorageStatus(status.right().value())); } else { - * if (false == inTransaction) { titanGenericDao.commit(); } - * OperationData operationData = status.left().value(); + * if (status.isRight()) { if (false == inTransaction) { titanGenericDao.rollback(); } + * log.error("Failed to update operation {} of interfaceName {} of resource {}", operationName, interfaceName, resourceId); + * return + * Either.right(DaoStatusConverter .convertTitanStatusToStorageStatus(status.right().value())); } else { if (false == inTransaction) { titanGenericDao.commit(); } OperationData operationData = status.left().value(); * - * Operation operationDefResult = - * convertOperationDataToOperation(operationData); + * Operation operationDefResult = convertOperationDataToOperation(operationData); * * * log.debug("The returned OperationDefintion is {}", operationDefResult); return Either.left(operationDefResult); } @@ -567,26 +522,16 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation return status; } - private Either<Operation, StorageOperationStatus> updateOperationOnGraph(Operation operation, String resourceId, - String interfaceName, String operationName) { + private Either<Operation, StorageOperationStatus> updateOperationOnGraph(Operation operation, String resourceId, String interfaceName, String operationName) { - Either<List<ImmutablePair<InterfaceData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao - .getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), resourceId, - GraphEdgeLabels.INTERFACE, NodeTypeEnum.Interface, InterfaceData.class); + Either<List<ImmutablePair<InterfaceData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), resourceId, GraphEdgeLabels.INTERFACE, NodeTypeEnum.Interface, + InterfaceData.class); if (childrenNodes.isRight()) { /* - * InterfaceDefinition intDef = new InterfaceDefinition(); - * intDef.setType(interfaceName); Map<String, Operation> opMap = new - * HashMap<String, Operation>(); opMap.put(operationName, - * operation); intDef.setOperations(opMap); - * Either<InterfaceDefinition, StorageOperationStatus> statusRes = - * this .createInterfaceOnResource(intDef, resourceId, - * interfaceName, true); if (statusRes.isRight()) return - * Either.right(statusRes.right().value()); else { - * InterfaceDefinition newDef = statusRes.left().value(); Operation - * res = newDef.getOperations().get(operationName); return - * Either.left(res); } + * InterfaceDefinition intDef = new InterfaceDefinition(); intDef.setType(interfaceName); Map<String, Operation> opMap = new HashMap<String, Operation>(); opMap.put(operationName, operation); intDef.setOperations(opMap); + * Either<InterfaceDefinition, StorageOperationStatus> statusRes = this .createInterfaceOnResource(intDef, resourceId, interfaceName, true); if (statusRes.isRight()) return Either.right(statusRes.right().value()); else { + * InterfaceDefinition newDef = statusRes.left().value(); Operation res = newDef.getOperations().get(operationName); return Either.left(res); } */ return updateOperationFromParentNode(operation, resourceId, interfaceName, operationName); @@ -597,8 +542,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation } - private Either<Operation, StorageOperationStatus> updateExistingOperation(String resourceId, Operation operation, - String interfaceName, String operationName, + private Either<Operation, StorageOperationStatus> updateExistingOperation(String resourceId, Operation operation, String interfaceName, String operationName, Either<List<ImmutablePair<InterfaceData, GraphEdge>>, TitanOperationStatus> childrenNodes) { Operation newOperation = null; StorageOperationStatus storageOperationStatus = StorageOperationStatus.GENERAL_ERROR; @@ -610,14 +554,11 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation InterfaceData interfaceData = interfaceDataNode.getKey(); if (interfaceEdgeProp.get(GraphPropertiesDictionary.NAME.getProperty()).equals(interfaceName)) { - Either<List<ImmutablePair<OperationData, GraphEdge>>, TitanOperationStatus> operationRes = titanGenericDao - .getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), - (String) interfaceDataNode.getLeft().getUniqueId(), GraphEdgeLabels.INTERFACE_OPERATION, - NodeTypeEnum.InterfaceOperation, OperationData.class); + Either<List<ImmutablePair<OperationData, GraphEdge>>, TitanOperationStatus> operationRes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) interfaceDataNode.getLeft().getUniqueId(), + GraphEdgeLabels.INTERFACE_OPERATION, NodeTypeEnum.InterfaceOperation, OperationData.class); if (operationRes.isRight()) { - log.error("Failed to find operation {} on interface {}", operationName, interfaceName); - return Either - .right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationRes.right().value())); + log.error("Failed to find operation {} on interface {}", operationName, interfaceName); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationRes.right().value())); } else { List<ImmutablePair<OperationData, GraphEdge>> operations = operationRes.left().value(); for (ImmutablePair<OperationData, GraphEdge> operationPairEdge : operations) { @@ -625,25 +566,18 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation OperationData opData = operationPairEdge.getLeft(); Map<String, Object> opEdgeProp = opEdge.getProperties(); if (opEdgeProp.get(GraphPropertiesDictionary.NAME.getProperty()).equals(operationName)) { - ArtifactDefinition artifact = operation.getImplementation(); - Either<ImmutablePair<ArtifactData, GraphEdge>, TitanOperationStatus> artifactRes = titanGenericDao - .getChild(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), - (String) opData.getUniqueId(), GraphEdgeLabels.ARTIFACT_REF, - NodeTypeEnum.ArtifactRef, ArtifactData.class); + ArtifactDefinition artifact = operation.getImplementationArtifact(); + Either<ImmutablePair<ArtifactData, GraphEdge>, TitanOperationStatus> artifactRes = titanGenericDao.getChild(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) opData.getUniqueId(), GraphEdgeLabels.ARTIFACT_REF, + NodeTypeEnum.ArtifactRef, ArtifactData.class); Either<ArtifactDefinition, StorageOperationStatus> artStatus; if (artifactRes.isRight()) { - artStatus = artifactOperation.addArifactToComponent(artifact, - (String) operationPairEdge.getLeft().getUniqueId(), - NodeTypeEnum.InterfaceOperation, true, true); + artStatus = artifactOperation.addArifactToComponent(artifact, (String) operationPairEdge.getLeft().getUniqueId(), NodeTypeEnum.InterfaceOperation, true, true); } else { - artStatus = artifactOperation.updateArifactOnResource(artifact, - (String) operationPairEdge.getLeft().getUniqueId(), - (String) artifactRes.left().value().getLeft().getUniqueId(), - NodeTypeEnum.InterfaceOperation, true); + artStatus = artifactOperation.updateArifactOnResource(artifact, (String) operationPairEdge.getLeft().getUniqueId(), (String) artifactRes.left().value().getLeft().getUniqueId(), NodeTypeEnum.InterfaceOperation, true); } if (artStatus.isRight()) { titanGenericDao.rollback(); - log.error("Failed to add artifact {}", operationName, interfaceName); + log.error("Failed to add artifact {} to interface {}", operationName, interfaceName); return Either.right(artStatus.right().value()); } else { newOperation = this.convertOperationDataToOperation(opData); @@ -655,23 +589,18 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation } if (newOperation == null) { - Either<InterfaceData, TitanOperationStatus> parentInterfaceStatus = findInterfaceOnParentNode( - resourceId, interfaceName); + Either<InterfaceData, TitanOperationStatus> parentInterfaceStatus = findInterfaceOnParentNode(resourceId, interfaceName); if (parentInterfaceStatus.isRight()) { log.debug("Interface {} not exist", interfaceName); - return Either.right(DaoStatusConverter - .convertTitanStatusToStorageStatus(parentInterfaceStatus.right().value())); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentInterfaceStatus.right().value())); } InterfaceData parentInterfaceData = parentInterfaceStatus.left().value(); - Either<List<ImmutablePair<OperationData, GraphEdge>>, TitanOperationStatus> opRes = titanGenericDao - .getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), - (String) parentInterfaceData.getUniqueId(), GraphEdgeLabels.INTERFACE_OPERATION, - NodeTypeEnum.InterfaceOperation, OperationData.class); + Either<List<ImmutablePair<OperationData, GraphEdge>>, TitanOperationStatus> opRes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) parentInterfaceData.getUniqueId(), + GraphEdgeLabels.INTERFACE_OPERATION, NodeTypeEnum.InterfaceOperation, OperationData.class); if (opRes.isRight()) { - log.error("Failed to find operation {} on interface", operationName, interfaceName); - return Either.right( - DaoStatusConverter.convertTitanStatusToStorageStatus(operationRes.right().value())); + log.error("Failed to find operation {} on interface {}", operationName, interfaceName); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationRes.right().value())); } else { List<ImmutablePair<OperationData, GraphEdge>> parentOperations = opRes.left().value(); @@ -679,10 +608,8 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation GraphEdge opEdge = operationPairEdge.getRight(); OperationData opData = operationPairEdge.getLeft(); Map<String, Object> opEdgeProp = opEdge.getProperties(); - if (opEdgeProp.get(GraphPropertiesDictionary.NAME.getProperty()) - .equals(operationName)) { - return copyAndCreateNewOperation(operation, interfaceName, operationName, null, - interfaceData, operationRes, opData); + if (opEdgeProp.get(GraphPropertiesDictionary.NAME.getProperty()).equals(operationName)) { + return copyAndCreateNewOperation(operation, interfaceName, operationName, null, interfaceData, operationRes, opData); } } } @@ -703,26 +630,20 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation return Either.left(newOperation); } - private Either<Operation, StorageOperationStatus> copyAndCreateNewOperation(Operation operation, - String interfaceName, String operationName, Operation newOperation, InterfaceData interfaceData, - Either<List<ImmutablePair<OperationData, GraphEdge>>, TitanOperationStatus> operationRes, - OperationData opData) { + private Either<Operation, StorageOperationStatus> copyAndCreateNewOperation(Operation operation, String interfaceName, String operationName, Operation newOperation, InterfaceData interfaceData, + Either<List<ImmutablePair<OperationData, GraphEdge>>, TitanOperationStatus> operationRes, OperationData opData) { OperationDataDefinition opDataInfo = opData.getOperationDataDefinition(); OperationDataDefinition newOperationInfo = new OperationDataDefinition(opDataInfo); - newOperationInfo.setUniqueId( - UniqueIdBuilder.buildPropertyUniqueId(interfaceData.getUniqueId(), operationName.toLowerCase())); + newOperationInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(interfaceData.getUniqueId(), operationName.toLowerCase())); OperationData newopData = new OperationData(newOperationInfo); - Either<OperationData, TitanOperationStatus> operationStatus = createOperationNodeAndRelation(operationName, - newopData, interfaceData); + Either<OperationData, TitanOperationStatus> operationStatus = createOperationNodeAndRelation(operationName, newopData, interfaceData); if (operationStatus.isRight()) { - log.error("Failed to create operation {} on interface {}", operationName, interfaceName); + log.error("Failed to create operation {} on interface {}", operationName, interfaceName); return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationRes.right().value())); } - ArtifactDefinition artifact = operation.getImplementation(); + ArtifactDefinition artifact = operation.getImplementationArtifact(); if (artifact != null) { - Either<ArtifactDefinition, StorageOperationStatus> artStatus = artifactOperation.addArifactToComponent( - artifact, (String) operationStatus.left().value().getUniqueId(), NodeTypeEnum.InterfaceOperation, - true, true); + Either<ArtifactDefinition, StorageOperationStatus> artStatus = artifactOperation.addArifactToComponent(artifact, (String) operationStatus.left().value().getUniqueId(), NodeTypeEnum.InterfaceOperation, true, true); if (artStatus.isRight()) { titanGenericDao.rollback(); log.error("Failed to add artifact {} to interface {}", operationName, interfaceName); @@ -735,17 +656,14 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation return Either.left(newOperation); } - private Either<Operation, StorageOperationStatus> updateOperationFromParentNode(Operation operation, - String resourceId, String interfaceName, String operationName) { + private Either<Operation, StorageOperationStatus> updateOperationFromParentNode(Operation operation, String resourceId, String interfaceName, String operationName) { // Operation newOperation = null; ResourceMetadataData resourceData = new ResourceMetadataData(); resourceData.getMetadataDataDefinition().setUniqueId(resourceId); - Either<InterfaceData, TitanOperationStatus> parentInterfaceStatus = findInterfaceOnParentNode(resourceId, - interfaceName); + Either<InterfaceData, TitanOperationStatus> parentInterfaceStatus = findInterfaceOnParentNode(resourceId, interfaceName); if (parentInterfaceStatus.isRight()) { log.debug("Interface {} not exist", interfaceName); - return Either - .right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentInterfaceStatus.right().value())); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentInterfaceStatus.right().value())); } InterfaceData interfaceData = parentInterfaceStatus.left().value(); @@ -756,28 +674,24 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation newInterfaceInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, interfaceNameSplitted)); InterfaceData updatedInterfaceData = new InterfaceData(newInterfaceInfo); - Either<InterfaceData, TitanOperationStatus> createStatus = createInterfaceNodeAndRelation(interfaceName, - resourceId, updatedInterfaceData, resourceData); + Either<InterfaceData, TitanOperationStatus> createStatus = createInterfaceNodeAndRelation(interfaceName, resourceId, updatedInterfaceData, resourceData); if (createStatus.isRight()) { - log.debug("failed to create interface node {} on resource {}", interfaceName, resourceId); + log.debug("failed to create interface node {} on resource {}", interfaceName, resourceId); return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createStatus.right().value())); } InterfaceData newInterfaceNode = createStatus.left().value(); - Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(newInterfaceNode, - interfaceData, GraphEdgeLabels.DERIVED_FROM, null); + Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(newInterfaceNode, interfaceData, GraphEdgeLabels.DERIVED_FROM, null); if (createRelResult.isRight()) { TitanOperationStatus operationStatus = createRelResult.right().value(); - log.error("Failed to associate interface {} to interface {} in graph. Status is {}", interfaceData.getUniqueId(), newInterfaceNode.getUniqueId(), operationStatus); + log.error("Failed to associate interface {} to interface {} in graph. status is {}", interfaceData.getUniqueId(), newInterfaceNode.getUniqueId(), operationStatus); return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationStatus)); } - Either<List<ImmutablePair<OperationData, GraphEdge>>, TitanOperationStatus> operationRes = titanGenericDao - .getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), - (String) interfaceData.getUniqueId(), GraphEdgeLabels.INTERFACE_OPERATION, - NodeTypeEnum.InterfaceOperation, OperationData.class); + Either<List<ImmutablePair<OperationData, GraphEdge>>, TitanOperationStatus> operationRes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) interfaceData.getUniqueId(), + GraphEdgeLabels.INTERFACE_OPERATION, NodeTypeEnum.InterfaceOperation, OperationData.class); if (operationRes.isRight()) { - log.error("Failed to find operation {} on interface {}", operationName, interfaceName); + log.error("Failed to find operation {} on interface {}", operationName, interfaceName); return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationRes.right().value())); } else { @@ -802,25 +716,20 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation // return Either.left(newOperation); } - private Either<InterfaceData, TitanOperationStatus> findInterfaceOnParentNode(String resourceId, - String interfaceName) { + private Either<InterfaceData, TitanOperationStatus> findInterfaceOnParentNode(String resourceId, String interfaceName) { - Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> parentRes = titanGenericDao - .getChild(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), resourceId, GraphEdgeLabels.DERIVED_FROM, - NodeTypeEnum.Resource, ResourceMetadataData.class); + Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> parentRes = titanGenericDao.getChild(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), resourceId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource, + ResourceMetadataData.class); if (parentRes.isRight()) { - log.debug("interface {} not found", interfaceName); + log.debug("interface {} not found ", interfaceName); return Either.right(parentRes.right().value()); } ImmutablePair<ResourceMetadataData, GraphEdge> parenNode = parentRes.left().value(); - Either<List<ImmutablePair<InterfaceData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao - .getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), - parenNode.getKey().getMetadataDataDefinition().getUniqueId(), GraphEdgeLabels.INTERFACE, - NodeTypeEnum.Interface, InterfaceData.class); + Either<List<ImmutablePair<InterfaceData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), parenNode.getKey().getMetadataDataDefinition().getUniqueId(), + GraphEdgeLabels.INTERFACE, NodeTypeEnum.Interface, InterfaceData.class); if (childrenNodes.isRight()) { - return findInterfaceOnParentNode(parenNode.getKey().getMetadataDataDefinition().getUniqueId(), - interfaceName); + return findInterfaceOnParentNode(parenNode.getKey().getMetadataDataDefinition().getUniqueId(), interfaceName); } else { for (ImmutablePair<InterfaceData, GraphEdge> interfaceDataNode : childrenNodes.left().value()) { @@ -833,15 +742,13 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation } } - return findInterfaceOnParentNode(parenNode.getKey().getMetadataDataDefinition().getUniqueId(), - interfaceName); + return findInterfaceOnParentNode(parenNode.getKey().getMetadataDataDefinition().getUniqueId(), interfaceName); } } @Override - public Either<InterfaceDefinition, StorageOperationStatus> createInterfaceOnResource(InterfaceDefinition interf, - String resourceId, String interfaceName, boolean failIfExist, boolean inTransaction) { + public Either<InterfaceDefinition, StorageOperationStatus> createInterfaceOnResource(InterfaceDefinition interf, String resourceId, String interfaceName, boolean failIfExist, boolean inTransaction) { Either<InterfaceData, TitanOperationStatus> status = addInterfaceToGraph(interf, interfaceName, resourceId); @@ -857,15 +764,14 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation InterfaceData interfaceData = status.left().value(); InterfaceDefinition interfaceDefResult = convertInterfaceDataToInterfaceDefinition(interfaceData); - Map<String, Operation> operations = interf.getOperations(); + Map<String, Operation> operations = interf.getOperationsMap(); if (operations != null && !operations.isEmpty()) { Set<String> opNames = operations.keySet(); Map<String, Operation> newOperations = new HashMap<String, Operation>(); for (String operationName : opNames) { Operation op = operations.get(operationName); - Either<OperationData, TitanOperationStatus> opStatus = addOperationToGraph(interf, operationName, - op, interfaceData); + Either<OperationData, TitanOperationStatus> opStatus = addOperationToGraph(interf, operationName, op, interfaceData); if (status.isRight()) { titanGenericDao.rollback(); log.error("Failed to add operation {} to interface {}", operationName, interfaceName); @@ -876,11 +782,9 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation OperationData opData = opStatus.left().value(); Operation newOperation = this.convertOperationDataToOperation(opData); - ArtifactDefinition art = op.getImplementation(); + ArtifactDefinition art = op.getImplementationArtifact(); if (art != null) { - Either<ArtifactDefinition, StorageOperationStatus> artRes = artifactOperation - .addArifactToComponent(art, (String) opData.getUniqueId(), - NodeTypeEnum.InterfaceOperation, failIfExist, true); + Either<ArtifactDefinition, StorageOperationStatus> artRes = artifactOperation.addArifactToComponent(art, (String) opData.getUniqueId(), NodeTypeEnum.InterfaceOperation, failIfExist, true); if (artRes.isRight()) { titanGenericDao.rollback(); log.error("Failed to add artifact {} to interface {}", operationName, interfaceName); @@ -891,7 +795,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation } } } - interfaceDefResult.setOperations(newOperations); + interfaceDefResult.setOperationsMap(newOperations); } log.debug("The returned InterfaceDefintion is {}", interfaceDefResult); return Either.left(interfaceDefResult); @@ -900,11 +804,9 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation } @Override - public StorageOperationStatus createInterfaceOnResource(InterfaceDefinition interf, String resourceId, - String interfaceName, boolean failIfExist, boolean inTransaction, TitanVertex metadataVertex) { + public StorageOperationStatus createInterfaceOnResource(InterfaceDefinition interf, String resourceId, String interfaceName, boolean failIfExist, boolean inTransaction, TitanVertex metadataVertex) { - Either<TitanVertex, TitanOperationStatus> interfaceResult = addInterfaceToGraph(interf, interfaceName, - resourceId, metadataVertex); + Either<TitanVertex, TitanOperationStatus> interfaceResult = addInterfaceToGraph(interf, interfaceName, resourceId, metadataVertex); if (interfaceResult.isRight()) { if (false == inTransaction) { @@ -921,14 +823,13 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation // InterfaceDefinition interfaceDefResult = // convertInterfaceDataToInterfaceDefinition(interfaceData); - Map<String, Operation> operations = interf.getOperations(); + Map<String, Operation> operations = interf.getOperationsMap(); if (operations != null && !operations.isEmpty()) { Set<String> opNames = operations.keySet(); for (String operationName : opNames) { Operation op = operations.get(operationName); - Either<TitanVertex, TitanOperationStatus> operationResult = addOperationToGraph(interf, - operationName, op, interfaceVertex); + Either<TitanVertex, TitanOperationStatus> operationResult = addOperationToGraph(interf, operationName, op, interfaceVertex); if (operationResult.isRight()) { if (false == inTransaction) { titanGenericDao.rollback(); @@ -941,12 +842,10 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation } TitanVertex operationVertex = operationResult.left().value(); - ArtifactDefinition art = op.getImplementation(); + ArtifactDefinition art = op.getImplementationArtifact(); if (art != null) { - String opId = (String) titanGenericDao.getProperty(operationVertex, - GraphPropertiesDictionary.UNIQUE_ID.getProperty()); - StorageOperationStatus artRes = artifactOperation.addArifactToComponent(art, opId, - NodeTypeEnum.InterfaceOperation, failIfExist, operationVertex); + String opId = (String) titanGenericDao.getProperty(operationVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty()); + StorageOperationStatus artRes = artifactOperation.addArifactToComponent(art, opId, NodeTypeEnum.InterfaceOperation, failIfExist, operationVertex); if (!artRes.equals(StorageOperationStatus.OK)) { if (false == inTransaction) { titanGenericDao.rollback(); @@ -964,14 +863,12 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation } @Override - public Either<Operation, StorageOperationStatus> deleteInterfaceOperation(String resourceId, String interfaceName, - String operationId) { + public Either<Operation, StorageOperationStatus> deleteInterfaceOperation(String resourceId, String interfaceName, String operationId) { return deleteInterfaceOperation(resourceId, interfaceName, operationId, false); } @Override - public Either<Operation, StorageOperationStatus> deleteInterfaceOperation(String resourceId, String interfaceName, - String operationId, boolean inTransaction) { + public Either<Operation, StorageOperationStatus> deleteInterfaceOperation(String resourceId, String interfaceName, String operationId, boolean inTransaction) { Either<Operation, TitanOperationStatus> status = removeOperationOnGraph(resourceId, interfaceName, operationId); if (status.isRight()) { @@ -993,17 +890,15 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation } @Override - public Either<InterfaceDefinition, StorageOperationStatus> deleteInterfaceOfResourceOnGraph(String resourceId, - InterfaceDefinition interfaceDef, boolean inTransaction) { + public Either<InterfaceDefinition, StorageOperationStatus> deleteInterfaceOfResourceOnGraph(String resourceId, InterfaceDefinition interfaceDef, boolean inTransaction) { - Map<String, Operation> operations = interfaceDef.getOperations(); + Map<String, Operation> operations = interfaceDef.getOperationsMap(); String interfaceNameSplitted = getShortInterfaceName(interfaceDef); if (operations != null) { for (Entry<String, Operation> entry : operations.entrySet()) { Operation op = entry.getValue(); - Either<Operation, StorageOperationStatus> removeOperationFromResource = deleteInterfaceOperation( - resourceId, interfaceNameSplitted, op.getUniqueId(), true); + Either<Operation, StorageOperationStatus> removeOperationFromResource = deleteInterfaceOperation(resourceId, interfaceNameSplitted, op.getUniqueId(), true); if (removeOperationFromResource.isRight()) { if (false == inTransaction) { titanGenericDao.rollback(); @@ -1017,13 +912,11 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation } - private Either<Operation, TitanOperationStatus> removeOperationOnGraph(String resourceId, String interfaceName, - String operationId) { + private Either<Operation, TitanOperationStatus> removeOperationOnGraph(String resourceId, String interfaceName, String operationId) { log.debug("Before deleting operation from graph {}", operationId); - Either<List<ImmutablePair<InterfaceData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao - .getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), resourceId, - GraphEdgeLabels.INTERFACE, NodeTypeEnum.Interface, InterfaceData.class); + Either<List<ImmutablePair<InterfaceData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), resourceId, GraphEdgeLabels.INTERFACE, NodeTypeEnum.Interface, + InterfaceData.class); if (childrenNodes.isRight()) { log.debug("Not found interface {}", interfaceName); @@ -1038,12 +931,10 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation String interfaceSplitedName = splitType(interfaceName); if (interfaceEdgeProp.get(GraphPropertiesDictionary.NAME.getProperty()).equals(interfaceSplitedName)) { - Either<List<ImmutablePair<OperationData, GraphEdge>>, TitanOperationStatus> operationRes = titanGenericDao - .getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), - (String) interfaceDataNode.getLeft().getUniqueId(), GraphEdgeLabels.INTERFACE_OPERATION, - NodeTypeEnum.InterfaceOperation, OperationData.class); + Either<List<ImmutablePair<OperationData, GraphEdge>>, TitanOperationStatus> operationRes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) interfaceDataNode.getLeft().getUniqueId(), + GraphEdgeLabels.INTERFACE_OPERATION, NodeTypeEnum.InterfaceOperation, OperationData.class); if (operationRes.isRight()) { - log.error("Failed to find operation {}", operationId, interfaceName); + log.error("Failed to find operation {} on interface {}", operationId, interfaceName); return Either.right(operationRes.right().value()); } List<ImmutablePair<OperationData, GraphEdge>> operations = operationRes.left().value(); @@ -1053,24 +944,18 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation opData = operationPairEdge.getLeft(); if (opData.getUniqueId().equals(operationId)) { - Either<ImmutablePair<ArtifactData, GraphEdge>, TitanOperationStatus> artifactRes = titanGenericDao - .getChild(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), - (String) operationPairEdge.getLeft().getUniqueId(), - GraphEdgeLabels.ARTIFACT_REF, NodeTypeEnum.ArtifactRef, ArtifactData.class); + Either<ImmutablePair<ArtifactData, GraphEdge>, TitanOperationStatus> artifactRes = titanGenericDao.getChild(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) operationPairEdge.getLeft().getUniqueId(), + GraphEdgeLabels.ARTIFACT_REF, NodeTypeEnum.ArtifactRef, ArtifactData.class); Either<ArtifactDefinition, StorageOperationStatus> arStatus = null; if (artifactRes.isLeft()) { ArtifactData arData = artifactRes.left().value().getKey(); - arStatus = artifactOperation.removeArifactFromResource( - (String) operationPairEdge.getLeft().getUniqueId(), (String) arData.getUniqueId(), - NodeTypeEnum.InterfaceOperation, true, true); + arStatus = artifactOperation.removeArifactFromResource((String) operationPairEdge.getLeft().getUniqueId(), (String) arData.getUniqueId(), NodeTypeEnum.InterfaceOperation, true, true); if (arStatus.isRight()) { log.debug("failed to delete artifact {}", arData.getUniqueId()); return Either.right(TitanOperationStatus.INVALID_ID); } } - Either<OperationData, TitanOperationStatus> deleteOpStatus = titanGenericDao.deleteNode( - UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.InterfaceOperation), opData.getUniqueId(), - OperationData.class); + Either<OperationData, TitanOperationStatus> deleteOpStatus = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.InterfaceOperation), opData.getUniqueId(), OperationData.class); if (deleteOpStatus.isRight()) { log.debug("failed to delete operation {}", opData.getUniqueId()); return Either.right(TitanOperationStatus.INVALID_ID); @@ -1081,9 +966,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation operation.setImplementation(arStatus.left().value()); } if (operations.size() <= 1) { - Either<InterfaceData, TitanOperationStatus> deleteInterfaceStatus = titanGenericDao - .deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Interface), - interfaceDataNode.left.getUniqueId(), InterfaceData.class); + Either<InterfaceData, TitanOperationStatus> deleteInterfaceStatus = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Interface), interfaceDataNode.left.getUniqueId(), InterfaceData.class); if (deleteInterfaceStatus.isRight()) { log.debug("failed to delete interface {}", interfaceDataNode.left.getUniqueId()); return Either.right(TitanOperationStatus.INVALID_ID); @@ -1100,8 +983,6 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation log.debug("Not found operation {}", interfaceName); return Either.right(TitanOperationStatus.INVALID_ID); - // } - } private String splitType(String interfaceName) { @@ -1131,16 +1012,14 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation } @Override - public Either<InterfaceDefinition, StorageOperationStatus> createInterfaceType(InterfaceDefinition interf, - boolean inTransaction) { + public Either<InterfaceDefinition, StorageOperationStatus> createInterfaceType(InterfaceDefinition interf, boolean inTransaction) { Either<InterfaceDefinition, StorageOperationStatus> result = null; try { InterfaceData interfaceData = new InterfaceData(interf); interf.setUniqueId(interf.getType().toLowerCase()); - Either<InterfaceData, TitanOperationStatus> existInterface = titanGenericDao - .getNode(interfaceData.getUniqueIdKey(), interfaceData.getUniqueId(), InterfaceData.class); + Either<InterfaceData, TitanOperationStatus> existInterface = titanGenericDao.getNode(interfaceData.getUniqueIdKey(), interfaceData.getUniqueId(), InterfaceData.class); if (existInterface.isLeft()) { // already exist @@ -1150,32 +1029,29 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation } log.debug("Before adding interface type to graph {}", interfaceData); - Either<InterfaceData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(interfaceData, - InterfaceData.class); + Either<InterfaceData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(interfaceData, InterfaceData.class); log.debug("After adding property type to graph {}", interfaceData); if (createNodeResult.isRight()) { TitanOperationStatus operationStatus = createNodeResult.right().value(); - log.error("Failed to add interface {} to graph. Status is {}", interf.getType(), operationStatus); + log.error("Failed to add interface {} to graph. status is {}", interf.getType(), operationStatus); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationStatus)); return result; } InterfaceDefinition interfaceDefResult = convertInterfaceDataToInterfaceDefinition(interfaceData); - Map<String, Operation> operations = interf.getOperations(); + Map<String, Operation> operations = interf.getOperationsMap(); if (operations != null && !operations.isEmpty()) { Map<String, Operation> newOperations = new HashMap<String, Operation>(); for (Map.Entry<String, Operation> operation : operations.entrySet()) { - Either<OperationData, TitanOperationStatus> opStatus = addOperationToGraph(interf, - operation.getKey(), operation.getValue(), interfaceData); + Either<OperationData, TitanOperationStatus> opStatus = addOperationToGraph(interf, operation.getKey(), operation.getValue(), interfaceData); if (opStatus.isRight()) { titanGenericDao.rollback(); log.error("Failed to add operation {} to interface {}", operation.getKey(), interf.getType()); - result = Either - .right(DaoStatusConverter.convertTitanStatusToStorageStatus(opStatus.right().value())); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(opStatus.right().value())); return result; } else { OperationData opData = opStatus.left().value(); @@ -1183,7 +1059,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation newOperations.put(operation.getKey(), newOperation); } } - interfaceDefResult.setOperations(newOperations); + interfaceDefResult.setOperationsMap(newOperations); } result = Either.left(interfaceDefResult); return result; @@ -1203,26 +1079,22 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation @Override public Either<InterfaceDefinition, StorageOperationStatus> getInterface(String interfaceId) { - Either<InterfaceData, TitanOperationStatus> getResult = titanGenericDao - .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Interface), interfaceId, InterfaceData.class); + Either<InterfaceData, TitanOperationStatus> getResult = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Interface), interfaceId, InterfaceData.class); if (getResult.isLeft()) { InterfaceData interfaceData = getResult.left().value(); return Either.left(convertInterfaceDataToInterfaceDefinition(interfaceData)); } else { TitanOperationStatus titanStatus = getResult.right().value(); - log.debug("Node with id {} was not found in the graph. Status: {}", interfaceId, titanStatus); - StorageOperationStatus storageOperationStatus = DaoStatusConverter - .convertTitanStatusToStorageStatus(titanStatus); + log.debug("Node with id {} was not found in the graph. status: {}", interfaceId, titanStatus); + StorageOperationStatus storageOperationStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus); return Either.right(storageOperationStatus); } } @Override - public StorageOperationStatus associateInterfaceToNode(GraphNode node, InterfaceDefinition interfaceDefinition, - TitanVertex metadataVertex) { + public StorageOperationStatus associateInterfaceToNode(GraphNode node, InterfaceDefinition interfaceDefinition, TitanVertex metadataVertex) { - Either<TitanVertex, TitanOperationStatus> interfaceData = titanGenericDao.getVertexByProperty( - UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Interface), interfaceDefinition.getUniqueId()); + Either<TitanVertex, TitanOperationStatus> interfaceData = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Interface), interfaceDefinition.getUniqueId()); if (interfaceData.isRight()) { return DaoStatusConverter.convertTitanStatusToStorageStatus(interfaceData.right().value()); } @@ -1232,8 +1104,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation String interfaceName = getShortInterfaceName(interfaceDefinition); properties.put(GraphPropertiesDictionary.NAME.getProperty(), interfaceName.toLowerCase()); - TitanOperationStatus createRelation = titanGenericDao.createEdge(metadataVertex, interfaceData.left().value(), - GraphEdgeLabels.INTERFACE, properties); + TitanOperationStatus createRelation = titanGenericDao.createEdge(metadataVertex, interfaceData.left().value(), GraphEdgeLabels.INTERFACE, properties); if (!createRelation.equals(TitanOperationStatus.OK)) { return DaoStatusConverter.convertTitanStatusToStorageStatus(createRelation); } @@ -1260,19 +1131,15 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation } @Override - public Either<Operation, StorageOperationStatus> getSpecificOperation(String resourceId, String interfaceType, - String operationName) { - log.trace("Getting operation, resourceId {}, interfaceType {}, operationName {}", resourceId, interfaceType, - operationName); - Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = getAllInterfacesOfResource( - resourceId, false); - if (allInterfacesOfResource.isRight() || allInterfacesOfResource.left().value() == null - || allInterfacesOfResource.left().value().get(interfaceType) == null) { + public Either<Operation, StorageOperationStatus> getSpecificOperation(String resourceId, String interfaceType, String operationName) { + log.trace("Getting operation, resourceId {}, interfaceType {}, operationName {}", resourceId, interfaceType, operationName); + Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = getAllInterfacesOfResource(resourceId, false); + if (allInterfacesOfResource.isRight() || allInterfacesOfResource.left().value() == null || allInterfacesOfResource.left().value().get(interfaceType) == null) { log.debug("Couldn't find interface definition of type {} for resource id {}", interfaceType, resourceId); return Either.right(allInterfacesOfResource.right().value()); } InterfaceDefinition interfaceDefinition = allInterfacesOfResource.left().value().get(interfaceType); - Map<String, Operation> operations = interfaceDefinition.getOperations(); + Map<String, Operation> operations = interfaceDefinition.getOperationsMap(); if (operations == null || operations.get(operationName) == null) { log.debug("Couldn't find operation for operation name {}, interface type {}", operationName, interfaceType); return Either.right(StorageOperationStatus.GENERAL_ERROR); @@ -1281,24 +1148,19 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation } @Override - public Either<InterfaceDefinition, StorageOperationStatus> dissociateInterfaceFromNode(GraphNode node, - InterfaceDefinition interfaceDefinition) { + public Either<InterfaceDefinition, StorageOperationStatus> dissociateInterfaceFromNode(GraphNode node, InterfaceDefinition interfaceDefinition) { - Either<InterfaceData, TitanOperationStatus> interfaceData = titanGenericDao.getNode( - UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Interface), interfaceDefinition.getUniqueId(), - InterfaceData.class); + Either<InterfaceData, TitanOperationStatus> interfaceData = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Interface), interfaceDefinition.getUniqueId(), InterfaceData.class); if (interfaceData.isRight()) { log.debug("Couldn't find interface {}", interfaceDefinition); return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(interfaceData.right().value())); } InterfaceData value = interfaceData.left().value(); - Either<GraphRelation, TitanOperationStatus> deleteRelation = titanGenericDao.deleteRelation(node, value, - GraphEdgeLabels.INTERFACE); + Either<GraphRelation, TitanOperationStatus> deleteRelation = titanGenericDao.deleteRelation(node, value, GraphEdgeLabels.INTERFACE); if (deleteRelation.isRight()) { TitanOperationStatus status = deleteRelation.right().value(); - log.debug("Couldn't dissociate interface between node {} to node {}. Status is {}", node.getUniqueId(), - value.getUniqueId(), status); + log.debug("Couldn't dissociate interface between node {} to node {}. Status is {}", node.getUniqueId(), value.getUniqueId(), status); return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/LifecycleOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/LifecycleOperation.java index 863975893c..2537891bbd 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/LifecycleOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/LifecycleOperation.java @@ -116,15 +116,12 @@ public class LifecycleOperation implements ILifecycleOperation { } @Override - public Either<User, StorageOperationStatus> getComponentOwner(String resourceId, NodeTypeEnum nodeType, - boolean inTransaction) { + public Either<User, StorageOperationStatus> getComponentOwner(String resourceId, NodeTypeEnum nodeType, boolean inTransaction) { Either<User, StorageOperationStatus> result = Either.right(StorageOperationStatus.GENERAL_ERROR); try { - Either<ImmutablePair<UserData, GraphEdge>, TitanOperationStatus> parentNode = titanGenericDao.getParentNode( - UniqueIdBuilder.getKeyByNodeType(nodeType), resourceId, GraphEdgeLabels.STATE, NodeTypeEnum.User, - UserData.class); + Either<ImmutablePair<UserData, GraphEdge>, TitanOperationStatus> parentNode = titanGenericDao.getParentNode(UniqueIdBuilder.getKeyByNodeType(nodeType), resourceId, GraphEdgeLabels.STATE, NodeTypeEnum.User, UserData.class); if (parentNode.isRight()) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentNode.right().value())); @@ -144,8 +141,7 @@ public class LifecycleOperation implements ILifecycleOperation { } @Override - public Either<? extends Component, StorageOperationStatus> checkoutComponent(NodeTypeEnum nodeType, - Component component, User modifier, User currentOwner, boolean inTransaction) { + public Either<? extends Component, StorageOperationStatus> checkoutComponent(NodeTypeEnum nodeType, Component component, User modifier, User currentOwner, boolean inTransaction) { Either<? extends Component, StorageOperationStatus> result = null; try { @@ -153,17 +149,14 @@ public class LifecycleOperation implements ILifecycleOperation { if (!component.getLifecycleState().equals(LifecycleStateEnum.CERTIFIED)) { component.setHighestVersion(false); ComponentOperation componentOperation = getComponentOperation(nodeType); - Either<? extends Component, StorageOperationStatus> updateComponent = componentOperation - .updateComponent(component, inTransaction, titanGenericDao, component.getClass(), nodeType); + Either<? extends Component, StorageOperationStatus> updateComponent = componentOperation.updateComponent(component, inTransaction, titanGenericDao, component.getClass(), nodeType); if (updateComponent.isRight()) { StorageOperationStatus error = updateComponent.right().value(); - log.debug("Couldn't set lifecycle for component {} to state {}, error: {}", component.getUniqueId(), - LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, error); + log.debug("Couldn't set lifecycle for component {} to state {}, error: {}", component.getUniqueId(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, error); return Either.right(error); } - StorageOperationStatus changeStateToLastState = changeStateRelation(nodeType, component.getUniqueId(), - currentOwner, GraphEdgeLabels.STATE, GraphEdgeLabels.LAST_STATE); + StorageOperationStatus changeStateToLastState = changeStateRelation(nodeType, component.getUniqueId(), currentOwner, GraphEdgeLabels.STATE, GraphEdgeLabels.LAST_STATE); if (!changeStateToLastState.equals(StorageOperationStatus.OK)) { result = Either.right(changeStateToLastState); return result; @@ -173,8 +166,7 @@ public class LifecycleOperation implements ILifecycleOperation { // clone the component result = cloneComponentForCheckout(component, nodeType, modifier); if (result.isRight()) { - log.debug("Couldn't set lifecycle for component {} to state {}, error: {}", component.getUniqueId(), - LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, result.right().value()); + log.debug("Couldn't set lifecycle for component {} to state {}, error: {}", component.getUniqueId(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, result.right().value()); return result; } @@ -193,8 +185,7 @@ public class LifecycleOperation implements ILifecycleOperation { return result; } - private Either<? extends Component, StorageOperationStatus> cloneComponentForCertified(Component component, - User modifier, Integer majorVersion) { + private Either<? extends Component, StorageOperationStatus> cloneComponentForCertified(Component component, User modifier, Integer majorVersion) { // set new version String certifiedVersion = (majorVersion + 1) + VERSION_DELIMETER + "0"; @@ -205,15 +196,13 @@ public class LifecycleOperation implements ILifecycleOperation { component.setHighestVersion(true); ComponentOperation componentOperation = getComponentOperation(component.getComponentType().getNodeType()); - Either<? extends Component, StorageOperationStatus> cloneComponentResult = componentOperation - .cloneComponent(component, certifiedVersion, LifecycleStateEnum.CERTIFIED, true); + Either<? extends Component, StorageOperationStatus> cloneComponentResult = componentOperation.cloneComponent(component, certifiedVersion, LifecycleStateEnum.CERTIFIED, true); return cloneComponentResult; } @Override - public Either<? extends Component, StorageOperationStatus> undoCheckout(NodeTypeEnum nodeType, Component component, - User modifier, User currentOwner, boolean inTransaction) { + public Either<? extends Component, StorageOperationStatus> undoCheckout(NodeTypeEnum nodeType, Component component, User modifier, User currentOwner, boolean inTransaction) { Either<? extends Component, StorageOperationStatus> result = null; ComponentOperation componentOperation = getComponentOperation(nodeType); @@ -226,8 +215,7 @@ public class LifecycleOperation implements ILifecycleOperation { String previousVersion = versionParts[0] + VERSION_DELIMETER + minorVersion; if (!previousVersion.equals("0.0")) { - Either<? extends Component, StorageOperationStatus> updateOldResourceResult = updateOldComponentBeforeUndoCheckout( - componentOperation, prevComponent, component, previousVersion, nodeType, true); + Either<? extends Component, StorageOperationStatus> updateOldResourceResult = updateOldComponentBeforeUndoCheckout(componentOperation, prevComponent, component, previousVersion, nodeType, true); if (updateOldResourceResult.isRight()) { result = updateOldResourceResult; return result; @@ -236,8 +224,7 @@ public class LifecycleOperation implements ILifecycleOperation { } // delete the component - Either<? extends Component, StorageOperationStatus> deleteResourceResult = componentOperation - .deleteComponent(component.getUniqueId(), true); + Either<? extends Component, StorageOperationStatus> deleteResourceResult = componentOperation.deleteComponent(component.getUniqueId(), true); if (deleteResourceResult.isRight()) { result = deleteResourceResult; return result; @@ -262,23 +249,19 @@ public class LifecycleOperation implements ILifecycleOperation { } @Override - public Either<? extends Component, StorageOperationStatus> checkinComponent(NodeTypeEnum nodeType, - Component component, User modifier, User owner, boolean inTransaction) { + public Either<? extends Component, StorageOperationStatus> checkinComponent(NodeTypeEnum nodeType, Component component, User modifier, User owner, boolean inTransaction) { Either<? extends Component, StorageOperationStatus> result = null; try { - StorageOperationStatus updateCheckinInGraph = updateCheckinInGraph(nodeType, component.getUniqueId(), - component.getLifecycleState(), modifier, owner); + StorageOperationStatus updateCheckinInGraph = updateCheckinInGraph(nodeType, component.getUniqueId(), component.getLifecycleState(), modifier, owner); if (!updateCheckinInGraph.equals(StorageOperationStatus.OK)) { - log.error("failed to update state of resource {}. status={}", component.getUniqueId(), - updateCheckinInGraph); + log.error("failed to update state of resource {}. status={}", component.getUniqueId(), updateCheckinInGraph); return Either.right(updateCheckinInGraph); } LifecycleStateEnum state = LifecycleStateEnum.NOT_CERTIFIED_CHECKIN; ComponentParametersView componentParametersView = buildFilterForFetchComponentAfterChangeState(); result = updateComponentMD(component, modifier, state, nodeType, componentParametersView); if (result.isRight()) { - log.debug("Couldn't set lifecycle for component {} to state {}, error: {}", component.getUniqueId(), - state, result.right().value()); + log.debug("Couldn't set lifecycle for component {} to state {}, error: {}", component.getUniqueId(), state, result.right().value()); } return result; @@ -306,8 +289,7 @@ public class LifecycleOperation implements ILifecycleOperation { return componentParametersView; } - private StorageOperationStatus updateCheckinInGraph(NodeTypeEnum componentType, String componentId, - LifecycleStateEnum state, User modifier, User owner) { + private StorageOperationStatus updateCheckinInGraph(NodeTypeEnum componentType, String componentId, LifecycleStateEnum state, User modifier, User owner) { // check if we cancel rfc if (state.equals(LifecycleStateEnum.READY_FOR_CERTIFICATION)) { @@ -316,8 +298,7 @@ public class LifecycleOperation implements ILifecycleOperation { Map<String, Object> props = new HashMap<String, Object>(); props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); UniqueIdData resourceData = new UniqueIdData(componentType, componentId); - Either<GraphRelation, TitanOperationStatus> deleteResult = titanGenericDao - .deleteIncomingRelationByCriteria(resourceData, GraphEdgeLabels.LAST_STATE, props); + Either<GraphRelation, TitanOperationStatus> deleteResult = titanGenericDao.deleteIncomingRelationByCriteria(resourceData, GraphEdgeLabels.LAST_STATE, props); if (deleteResult.isRight()) { log.debug("failed to update last state relation"); return StorageOperationStatus.INCONSISTENCY; @@ -325,8 +306,7 @@ public class LifecycleOperation implements ILifecycleOperation { } // remove CHECKOUT relation - StorageOperationStatus removeUserToResourceRelation = removeUserToResourceRelation(componentType, - owner.getUserId(), componentId, GraphEdgeLabels.STATE); + StorageOperationStatus removeUserToResourceRelation = removeUserToResourceRelation(componentType, owner.getUserId(), componentId, GraphEdgeLabels.STATE); if (!removeUserToResourceRelation.equals(StorageOperationStatus.OK)) { return removeUserToResourceRelation; } @@ -334,8 +314,7 @@ public class LifecycleOperation implements ILifecycleOperation { // create CHECKIN relation Map<String, Object> props = new HashMap<String, Object>(); props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - StorageOperationStatus createUserToResourceRelation = createUserToResourceRelation(componentType, - modifier.getUserId(), componentId, GraphEdgeLabels.STATE, props); + StorageOperationStatus createUserToResourceRelation = createUserToResourceRelation(componentType, modifier.getUserId(), componentId, GraphEdgeLabels.STATE, props); if (!createUserToResourceRelation.equals(StorageOperationStatus.OK)) { return createUserToResourceRelation; } @@ -344,15 +323,12 @@ public class LifecycleOperation implements ILifecycleOperation { } @Override - public Either<? extends Component, StorageOperationStatus> requestCertificationComponent(NodeTypeEnum nodeType, - Component component, User modifier, User owner, boolean inTransaction) { + public Either<? extends Component, StorageOperationStatus> requestCertificationComponent(NodeTypeEnum nodeType, Component component, User modifier, User owner, boolean inTransaction) { Either<? extends Component, StorageOperationStatus> result = null; try { - StorageOperationStatus updateRfcOnGraph = updateRfcOnGraph(nodeType, component.getUniqueId(), - component.getLifecycleState(), modifier, owner); + StorageOperationStatus updateRfcOnGraph = updateRfcOnGraph(nodeType, component.getUniqueId(), component.getLifecycleState(), modifier, owner); if (!updateRfcOnGraph.equals(StorageOperationStatus.OK)) { - log.error("failed to update state of resource {}. status={}", component.getUniqueId(), - updateRfcOnGraph); + log.error("failed to update state of resource {}. status={}", component.getUniqueId(), updateRfcOnGraph); return Either.right(updateRfcOnGraph); } @@ -362,8 +338,7 @@ public class LifecycleOperation implements ILifecycleOperation { result = updateComponentMD(component, modifier, state, nodeType, componentParametersView); if (result.isRight()) { - log.debug("Couldn't set lifecycle for component {} to state {}, error: {}", component.getUniqueId(), - state, result.right().value()); + log.debug("Couldn't set lifecycle for component {} to state {}, error: {}", component.getUniqueId(), state, result.right().value()); return result; } return result; @@ -381,15 +356,13 @@ public class LifecycleOperation implements ILifecycleOperation { } } - private StorageOperationStatus updateRfcOnGraph(NodeTypeEnum componentType, String componentId, - LifecycleStateEnum state, User modifier, User owner) { + private StorageOperationStatus updateRfcOnGraph(NodeTypeEnum componentType, String componentId, LifecycleStateEnum state, User modifier, User owner) { if (state.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) { // if this is atomic checkin + RFC: create checkin relation // remove CHECKOUT relation - StorageOperationStatus relationStatus = removeUserToResourceRelation(componentType, owner.getUserId(), - componentId, GraphEdgeLabels.STATE); + StorageOperationStatus relationStatus = removeUserToResourceRelation(componentType, owner.getUserId(), componentId, GraphEdgeLabels.STATE); if (!relationStatus.equals(StorageOperationStatus.OK)) { return relationStatus; } @@ -397,14 +370,12 @@ public class LifecycleOperation implements ILifecycleOperation { // create CHECKIN relation Map<String, Object> props = new HashMap<String, Object>(); props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - relationStatus = createUserToResourceRelation(componentType, modifier.getUserId(), componentId, - GraphEdgeLabels.LAST_STATE, props); + relationStatus = createUserToResourceRelation(componentType, modifier.getUserId(), componentId, GraphEdgeLabels.LAST_STATE, props); if (!relationStatus.equals(StorageOperationStatus.OK)) { return relationStatus; } } else { - StorageOperationStatus changeStatus = changeRelationLabel(componentType, componentId, owner, - GraphEdgeLabels.STATE, GraphEdgeLabels.LAST_STATE); + StorageOperationStatus changeStatus = changeRelationLabel(componentType, componentId, owner, GraphEdgeLabels.STATE, GraphEdgeLabels.LAST_STATE); if (!changeStatus.equals(StorageOperationStatus.OK)) { return changeStatus; } @@ -413,21 +384,18 @@ public class LifecycleOperation implements ILifecycleOperation { // create RFC relation Map<String, Object> props = new HashMap<String, Object>(); props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION); - StorageOperationStatus changeRelationLabel = createUserToResourceRelation(componentType, modifier.getUserId(), - componentId, GraphEdgeLabels.STATE, props); + StorageOperationStatus changeRelationLabel = createUserToResourceRelation(componentType, modifier.getUserId(), componentId, GraphEdgeLabels.STATE, props); if (!changeRelationLabel.equals(StorageOperationStatus.OK)) { return changeRelationLabel; } return StorageOperationStatus.OK; } - private StorageOperationStatus changeRelationLabel(NodeTypeEnum componentType, String componentId, User owner, - GraphEdgeLabels prevLabel, GraphEdgeLabels toLabel) { + private StorageOperationStatus changeRelationLabel(NodeTypeEnum componentType, String componentId, User owner, GraphEdgeLabels prevLabel, GraphEdgeLabels toLabel) { UniqueIdData resourceV = new UniqueIdData(componentType, componentId); UserData userV = new UserData(); userV.setUserId(owner.getUserId()); - Either<GraphRelation, TitanOperationStatus> replaceRelationLabelResult = titanGenericDao - .replaceRelationLabel(userV, resourceV, prevLabel, toLabel); + Either<GraphRelation, TitanOperationStatus> replaceRelationLabelResult = titanGenericDao.replaceRelationLabel(userV, resourceV, prevLabel, toLabel); if (replaceRelationLabelResult.isRight()) { log.error("failed to replace label from last state to state"); return DaoStatusConverter.convertTitanStatusToStorageStatus(replaceRelationLabelResult.right().value()); @@ -436,12 +404,10 @@ public class LifecycleOperation implements ILifecycleOperation { } @Override - public Either<? extends Component, StorageOperationStatus> startComponentCertification(NodeTypeEnum nodeType, - Component component, User modifier, User owner, boolean inTransaction) { + public Either<? extends Component, StorageOperationStatus> startComponentCertification(NodeTypeEnum nodeType, Component component, User modifier, User owner, boolean inTransaction) { Either<? extends Component, StorageOperationStatus> result = null; try { - StorageOperationStatus updateOnGraph = updateStartCertificationOnGraph(nodeType, component.getUniqueId(), - modifier, owner); + StorageOperationStatus updateOnGraph = updateStartCertificationOnGraph(nodeType, component.getUniqueId(), modifier, owner); if (!updateOnGraph.equals(StorageOperationStatus.OK)) { log.error("failed to update state of resource {}. status={}", component.getUniqueId(), updateOnGraph); return Either.right(updateOnGraph); @@ -452,8 +418,7 @@ public class LifecycleOperation implements ILifecycleOperation { result = updateComponentMD(component, modifier, state, nodeType, componentParametersView); if (result.isRight()) { - log.debug("Couldn't set lifecycle for component {} to state {}, error: {}", component.getUniqueId(), - state, result.right().value()); + log.debug("Couldn't set lifecycle for component {} to state {}, error: {}", component.getUniqueId(), state, result.right().value()); } return result; @@ -470,10 +435,8 @@ public class LifecycleOperation implements ILifecycleOperation { } } - private StorageOperationStatus updateStartCertificationOnGraph(NodeTypeEnum componentType, String componentId, - User modifier, User owner) { - StorageOperationStatus changeRelationLabel = changeRelationLabel(componentType, componentId, owner, - GraphEdgeLabels.STATE, GraphEdgeLabels.LAST_STATE); + private StorageOperationStatus updateStartCertificationOnGraph(NodeTypeEnum componentType, String componentId, User modifier, User owner) { + StorageOperationStatus changeRelationLabel = changeRelationLabel(componentType, componentId, owner, GraphEdgeLabels.STATE, GraphEdgeLabels.LAST_STATE); if (!changeRelationLabel.equals(StorageOperationStatus.OK)) { return changeRelationLabel; } @@ -481,8 +444,7 @@ public class LifecycleOperation implements ILifecycleOperation { Map<String, Object> props = new HashMap<String, Object>(); props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - StorageOperationStatus createUserToResourceRelation = createUserToResourceRelation(componentType, - modifier.getUserId(), componentId, GraphEdgeLabels.STATE, props); + StorageOperationStatus createUserToResourceRelation = createUserToResourceRelation(componentType, modifier.getUserId(), componentId, GraphEdgeLabels.STATE, props); if (!createUserToResourceRelation.equals(StorageOperationStatus.OK)) { return createUserToResourceRelation; } @@ -490,8 +452,7 @@ public class LifecycleOperation implements ILifecycleOperation { } @Override - public Either<? extends Component, StorageOperationStatus> certifyComponent(NodeTypeEnum nodeType, - Component component, User modifier, User currentOwner, boolean inTransaction) { + public Either<? extends Component, StorageOperationStatus> certifyComponent(NodeTypeEnum nodeType, Component component, User modifier, User currentOwner, boolean inTransaction) { Either<? extends Component, StorageOperationStatus> result = null; try { @@ -509,8 +470,7 @@ public class LifecycleOperation implements ILifecycleOperation { } // clone the resource - Either<? extends Component, StorageOperationStatus> createResourceResult = Either - .right(StorageOperationStatus.GENERAL_ERROR); + Either<? extends Component, StorageOperationStatus> createResourceResult = Either.right(StorageOperationStatus.GENERAL_ERROR); switch (nodeType) { case Service: case Resource: @@ -531,8 +491,7 @@ public class LifecycleOperation implements ILifecycleOperation { Component certifiedResource = createResourceResult.left().value(); // add rfc relation to preserve follower information - StorageOperationStatus addRfcRelation = addRfcRelationToCertfiedComponent(nodeType, resourceIdBeforeCertify, - certifiedResource.getUniqueId()); + StorageOperationStatus addRfcRelation = addRfcRelationToCertfiedComponent(nodeType, resourceIdBeforeCertify, certifiedResource.getUniqueId()); if (!addRfcRelation.equals(StorageOperationStatus.OK)) { result = Either.right(addRfcRelation); return result; @@ -556,15 +515,13 @@ public class LifecycleOperation implements ILifecycleOperation { } @Override - public Either<Boolean, StorageOperationStatus> deleteOldComponentVersions(NodeTypeEnum nodeType, - String componentName, String uuid, boolean inTransaction) { + public Either<Boolean, StorageOperationStatus> deleteOldComponentVersions(NodeTypeEnum nodeType, String componentName, String uuid, boolean inTransaction) { Either<Boolean, StorageOperationStatus> result = null; ComponentOperation componentOperation = getComponentOperation(nodeType); try { - Either<List<Component>, StorageOperationStatus> oldVersionsToDelete = getComponentTempVersions(nodeType, - uuid); + Either<List<Component>, StorageOperationStatus> oldVersionsToDelete = getComponentTempVersions(nodeType, uuid); if (oldVersionsToDelete.isRight()) { result = Either.right(oldVersionsToDelete.right().value()); @@ -573,8 +530,7 @@ public class LifecycleOperation implements ILifecycleOperation { for (Component resourceToDelete : oldVersionsToDelete.left().value()) { - Either<Component, StorageOperationStatus> updateResource = componentOperation - .markComponentToDelete(resourceToDelete, inTransaction); + Either<Component, StorageOperationStatus> updateResource = componentOperation.markComponentToDelete(resourceToDelete, inTransaction); if (updateResource.isRight()) { result = Either.right(updateResource.right().value()); return result; @@ -596,26 +552,22 @@ public class LifecycleOperation implements ILifecycleOperation { } } - private StorageOperationStatus addRfcRelationToCertfiedComponent(NodeTypeEnum componentType, - String resourceIdBeforeCertify, String uniqueId) { + private StorageOperationStatus addRfcRelationToCertfiedComponent(NodeTypeEnum componentType, String resourceIdBeforeCertify, String uniqueId) { // get user of certification request UniqueIdData componentV = new UniqueIdData(componentType, resourceIdBeforeCertify); Map<String, Object> props = new HashMap<String, Object>(); props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION); - Either<GraphRelation, TitanOperationStatus> rfcRelationResponse = titanGenericDao - .getIncomingRelationByCriteria(componentV, GraphEdgeLabels.LAST_STATE, props); + Either<GraphRelation, TitanOperationStatus> rfcRelationResponse = titanGenericDao.getIncomingRelationByCriteria(componentV, GraphEdgeLabels.LAST_STATE, props); if (rfcRelationResponse.isRight()) { TitanOperationStatus status = rfcRelationResponse.right().value(); log.error("failed to find rfc relation for component {}. status=", resourceIdBeforeCertify, status); return DaoStatusConverter.convertTitanStatusToStorageStatus(status); } GraphRelation rfcRelation = rfcRelationResponse.left().value(); - rfcRelation.setTo( - new RelationEndPoint(componentType, GraphPropertiesDictionary.UNIQUE_ID.getProperty(), uniqueId)); + rfcRelation.setTo(new RelationEndPoint(componentType, GraphPropertiesDictionary.UNIQUE_ID.getProperty(), uniqueId)); - Either<GraphRelation, TitanOperationStatus> createRelationResponse = titanGenericDao - .createRelation(rfcRelation); + Either<GraphRelation, TitanOperationStatus> createRelationResponse = titanGenericDao.createRelation(rfcRelation); if (createRelationResponse.isRight()) { TitanOperationStatus status = createRelationResponse.right().value(); log.error("failed to create rfc relation for component {}. status=", uniqueId, status); @@ -635,9 +587,7 @@ public class LifecycleOperation implements ILifecycleOperation { additionalQueryParams = new HashMap<String, Object>(); additionalQueryParams.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), resourceType.name()); } - Either<? extends Component, StorageOperationStatus> getLastCertifiedResponse = componentOperation - .getComponentByNameAndVersion(component.getName(), majorVersion + VERSION_DELIMETER + "0", - additionalQueryParams, true); + Either<? extends Component, StorageOperationStatus> getLastCertifiedResponse = componentOperation.getComponentByNameAndVersion(component.getName(), majorVersion + VERSION_DELIMETER + "0", additionalQueryParams, true); if (getLastCertifiedResponse.isRight()) { log.error("failed to update last certified resource. status={}", getLastCertifiedResponse.right().value()); @@ -646,8 +596,7 @@ public class LifecycleOperation implements ILifecycleOperation { Component lastCertified = getLastCertifiedResponse.left().value(); lastCertified.setHighestVersion(false); - Either<Component, StorageOperationStatus> updateResource = componentOperation.updateComponent(lastCertified, - true); + Either<Component, StorageOperationStatus> updateResource = componentOperation.updateComponent(lastCertified, true); if (updateResource.isRight()) { log.error("failed to update last certified resource. status={}", updateResource.right().value()); return updateResource.right().value(); @@ -655,8 +604,7 @@ public class LifecycleOperation implements ILifecycleOperation { return StorageOperationStatus.OK; } - private Either<Component, StorageOperationStatus> cloneComponentForCheckout(Component component, - NodeTypeEnum nodeType, User modifier) { + private Either<Component, StorageOperationStatus> cloneComponentForCheckout(Component component, NodeTypeEnum nodeType, User modifier) { ComponentOperation componentOperation = getComponentOperation(nodeType); String prevId = component.getUniqueId(); @@ -686,8 +634,7 @@ public class LifecycleOperation implements ILifecycleOperation { additionalQueryParams.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), resourceType.name()); } String name = component.getComponentMetadataDefinition().getMetadataDataDefinition().getName(); - Either<Component, StorageOperationStatus> alreadyExistResult = componentOperation - .getComponentByNameAndVersion(name, version, additionalQueryParams, true); + Either<Component, StorageOperationStatus> alreadyExistResult = componentOperation.getComponentByNameAndVersion(name, version, additionalQueryParams, true); if (alreadyExistResult.isLeft()) { log.debug("Component with name {} and version {} already exist", name, version); return Either.right(StorageOperationStatus.ENTITY_ALREADY_EXISTS); @@ -696,14 +643,11 @@ public class LifecycleOperation implements ILifecycleOperation { StorageOperationStatus storageOperationStatus = alreadyExistResult.right().value(); if (storageOperationStatus != StorageOperationStatus.NOT_FOUND) { - log.debug( - "Unexpected error when checking if component with name {} and version {} already exist, error: {}", - name, version, storageOperationStatus); + log.debug("Unexpected error when checking if component with name {} and version {} already exist, error: {}", name, version, storageOperationStatus); return Either.right(storageOperationStatus); } - Either<Component, StorageOperationStatus> cloneComponentResponse = componentOperation.cloneComponent(component, - version, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, true); + Either<Component, StorageOperationStatus> cloneComponentResponse = componentOperation.cloneComponent(component, version, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, true); return cloneComponentResponse; } @@ -720,8 +664,7 @@ public class LifecycleOperation implements ILifecycleOperation { return Either.left(newVersion); } - private StorageOperationStatus setRelationForCancelCertification(LifecycleStateEnum nextState, - NodeTypeEnum componentType, String componentId) { + private StorageOperationStatus setRelationForCancelCertification(LifecycleStateEnum nextState, NodeTypeEnum componentType, String componentId) { StorageOperationStatus result = StorageOperationStatus.GENERAL_ERROR; Map<String, Object> props = new HashMap<String, Object>(); @@ -730,8 +673,7 @@ public class LifecycleOperation implements ILifecycleOperation { // delete relation CERTIFICATION_IN_PROGRESS props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - Either<GraphRelation, TitanOperationStatus> deleteResult = titanGenericDao - .deleteIncomingRelationByCriteria(componentData, GraphEdgeLabels.STATE, props); + Either<GraphRelation, TitanOperationStatus> deleteResult = titanGenericDao.deleteIncomingRelationByCriteria(componentData, GraphEdgeLabels.STATE, props); if (deleteResult.isRight()) { log.debug("failed to update last state relation"); result = StorageOperationStatus.INCONSISTENCY; @@ -741,8 +683,7 @@ public class LifecycleOperation implements ILifecycleOperation { // delete relation READY_FOR_CERTIFICATION (LAST_STATE) props.put(GraphPropertiesDictionary.STATE.getProperty(), nextState); - deleteResult = titanGenericDao.deleteIncomingRelationByCriteria(componentData, GraphEdgeLabels.LAST_STATE, - props); + deleteResult = titanGenericDao.deleteIncomingRelationByCriteria(componentData, GraphEdgeLabels.LAST_STATE, props); if (deleteResult.isRight()) { log.debug("failed to update last state relation"); result = StorageOperationStatus.INCONSISTENCY; @@ -753,8 +694,7 @@ public class LifecycleOperation implements ILifecycleOperation { // create relation READY_FOR_CERTIFICATION (STATE) UserData user = new UserData(); user.setUserId((String) origRelation.getFrom().getIdValue()); - Either<GraphRelation, TitanOperationStatus> createRelationResult = titanGenericDao.createRelation(user, - componentData, GraphEdgeLabels.STATE, origRelation.toGraphMap()); + Either<GraphRelation, TitanOperationStatus> createRelationResult = titanGenericDao.createRelation(user, componentData, GraphEdgeLabels.STATE, origRelation.toGraphMap()); if (createRelationResult.isRight()) { log.error("failed to update last state relation. status={}", createRelationResult.right().value()); @@ -764,8 +704,7 @@ public class LifecycleOperation implements ILifecycleOperation { return StorageOperationStatus.OK; } - private StorageOperationStatus setRelationForFailCertification(LifecycleStateEnum nextState, - NodeTypeEnum componentType, String componentId) { + private StorageOperationStatus setRelationForFailCertification(LifecycleStateEnum nextState, NodeTypeEnum componentType, String componentId) { StorageOperationStatus result = null; Map<String, Object> props = new HashMap<String, Object>(); @@ -774,8 +713,7 @@ public class LifecycleOperation implements ILifecycleOperation { // delete relation CERTIFICATION_IN_PROGRESS props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - Either<GraphRelation, TitanOperationStatus> deleteResult = titanGenericDao - .deleteIncomingRelationByCriteria(componentData, GraphEdgeLabels.STATE, props); + Either<GraphRelation, TitanOperationStatus> deleteResult = titanGenericDao.deleteIncomingRelationByCriteria(componentData, GraphEdgeLabels.STATE, props); if (deleteResult.isRight()) { log.debug("failed to update last state relation"); result = StorageOperationStatus.INCONSISTENCY; @@ -785,8 +723,7 @@ public class LifecycleOperation implements ILifecycleOperation { // delete relation READY_FOR_CERTIFICATION props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.READY_FOR_CERTIFICATION); - deleteResult = titanGenericDao.deleteIncomingRelationByCriteria(componentData, GraphEdgeLabels.LAST_STATE, - props); + deleteResult = titanGenericDao.deleteIncomingRelationByCriteria(componentData, GraphEdgeLabels.LAST_STATE, props); if (deleteResult.isRight()) { log.debug("failed to update last state relation"); result = StorageOperationStatus.INCONSISTENCY; @@ -795,8 +732,7 @@ public class LifecycleOperation implements ILifecycleOperation { // delete relation NOT_CERTIFIED_CHECKIN (in order to change to STATE) props.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - deleteResult = titanGenericDao.deleteIncomingRelationByCriteria(componentData, GraphEdgeLabels.LAST_STATE, - props); + deleteResult = titanGenericDao.deleteIncomingRelationByCriteria(componentData, GraphEdgeLabels.LAST_STATE, props); if (deleteResult.isRight()) { log.debug("failed to update last state relation"); result = StorageOperationStatus.INCONSISTENCY; @@ -807,14 +743,31 @@ public class LifecycleOperation implements ILifecycleOperation { GraphRelation origRelation = deleteResult.left().value(); UserData user = new UserData(); user.setUserId((String) origRelation.getFrom().getIdValue()); - Either<GraphRelation, TitanOperationStatus> createRelationResult = titanGenericDao.createRelation(user, - componentData, GraphEdgeLabels.STATE, origRelation.toGraphMap()); + Either<GraphRelation, TitanOperationStatus> createRelationResult = titanGenericDao.createRelation(user, componentData, GraphEdgeLabels.STATE, origRelation.toGraphMap()); if (createRelationResult.isRight()) { log.debug("failed to update last state relation"); result = StorageOperationStatus.INCONSISTENCY; return result; } + + // delete relation LAST_MODIFIER (in order to change tester to designer) + deleteResult = titanGenericDao.deleteIncomingRelationByCriteria(componentData, GraphEdgeLabels.LAST_MODIFIER, null); + if (deleteResult.isRight()) { + log.debug("failed to update last modifier relation"); + result = StorageOperationStatus.INCONSISTENCY; + return result; + } + + // create new LAST_MODIFIER relation + origRelation = deleteResult.left().value(); + createRelationResult = titanGenericDao.createRelation(user, componentData, GraphEdgeLabels.LAST_MODIFIER, origRelation.toGraphMap()); + if (createRelationResult.isRight()) { + log.debug("failed to update last state relation"); + result = StorageOperationStatus.INCONSISTENCY; + return result; + } + return StorageOperationStatus.OK; } @@ -826,9 +779,7 @@ public class LifecycleOperation implements ILifecycleOperation { * @param nextState * @return */ - private Either<Component, StorageOperationStatus> updateComponentMD(Component component, User modifier, - LifecycleStateEnum nextState, NodeTypeEnum nodeType, - ComponentParametersView returnedComponentParametersViewFilter) { + private Either<Component, StorageOperationStatus> updateComponentMD(Component component, User modifier, LifecycleStateEnum nextState, NodeTypeEnum nodeType, ComponentParametersView returnedComponentParametersViewFilter) { if (returnedComponentParametersViewFilter == null) { returnedComponentParametersViewFilter = new ComponentParametersView(); @@ -849,34 +800,28 @@ public class LifecycleOperation implements ILifecycleOperation { } log.debug("updateComponentMD::getAndUpdateMetadata start"); // get service MD - Either<ComponentMetadataData, TitanOperationStatus> componentDataResult = titanGenericDao.getNode( - UniqueIdBuilder.getKeyByNodeType(nodeType), component.getUniqueId(), ComponentMetadataData.class); + Either<ComponentMetadataData, TitanOperationStatus> componentDataResult = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), component.getUniqueId(), ComponentMetadataData.class); if (componentDataResult.isRight()) { log.debug("failed to get service data from graph"); - return Either - .right(DaoStatusConverter.convertTitanStatusToStorageStatus(componentDataResult.right().value())); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(componentDataResult.right().value())); } // set state on resource ComponentMetadataData componentData = componentDataResult.left().value(); componentData.getMetadataDataDefinition().setState(nextState.name()); component.setLifecycleState(nextState); - Either<ComponentMetadataData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(componentData, - ComponentMetadataData.class); + Either<ComponentMetadataData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(componentData, ComponentMetadataData.class); log.debug("updateComponentMD::getAndUpdateMetadata end"); if (updateNode.isRight()) { - log.error("Failed to update component " + component.getUniqueId() + ". status is " - + updateNode.right().value()); + log.error("Failed to update component {}. status is {}", component.getUniqueId(), updateNode.right().value()); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value())); return result; } log.debug("updateComponentMD::getAndUpdateMetadata start"); - Either<Object, StorageOperationStatus> serviceAfterChange = componentOperation - .getComponent(component.getUniqueId(), returnedComponentParametersViewFilter, true); + Either<Object, StorageOperationStatus> serviceAfterChange = componentOperation.getComponent(component.getUniqueId(), returnedComponentParametersViewFilter, true); log.debug("updateComponentMD::getAndUpdateMetadata end"); if (serviceAfterChange.isRight()) { - log.error("Failed to get component " + component.getUniqueId() + " after change. status is " - + updateNode.right().value()); + log.error("Failed to get component {} after change. status is {}", component.getUniqueId(), updateNode.right().value()); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value())); return result; } @@ -891,8 +836,7 @@ public class LifecycleOperation implements ILifecycleOperation { * @param nextState * @return */ - private Either<Resource, StorageOperationStatus> updateResourceMD(Resource resource, User modifier, - LifecycleStateEnum nextState) { + private Either<Resource, StorageOperationStatus> updateResourceMD(Resource resource, User modifier, LifecycleStateEnum nextState) { Either<Resource, StorageOperationStatus> result; resource.setLastUpdateDate(null); @@ -904,33 +848,27 @@ public class LifecycleOperation implements ILifecycleOperation { return result; } // get resource MD - Either<ResourceMetadataData, TitanOperationStatus> resourceDataResult = titanGenericDao.getNode( - UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resource.getUniqueId(), - ResourceMetadataData.class); + Either<ResourceMetadataData, TitanOperationStatus> resourceDataResult = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resource.getUniqueId(), ResourceMetadataData.class); if (resourceDataResult.isRight()) { log.debug("failed to get resource data from graph"); - return Either - .right(DaoStatusConverter.convertTitanStatusToStorageStatus(resourceDataResult.right().value())); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(resourceDataResult.right().value())); } // set state on resource ResourceMetadataData resourceData = resourceDataResult.left().value(); resourceData.getMetadataDataDefinition().setState(nextState.name()); resource.setLifecycleState(nextState); - Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(resourceData, - ResourceMetadataData.class); + Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(resourceData, ResourceMetadataData.class); if (updateNode.isRight()) { - log.error("Failed to update resource " + resource.getUniqueId() + ". status is " - + updateNode.right().value()); + log.error("Failed to update resource {}. status is {}", resource.getUniqueId(), updateNode.right().value()); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value())); return result; } return Either.left(resource); } - private Either<List<Component>, StorageOperationStatus> getComponentTempVersions(NodeTypeEnum nodeType, - String uuid) { + private Either<List<Component>, StorageOperationStatus> getComponentTempVersions(NodeTypeEnum nodeType, String uuid) { Either<List<Component>, StorageOperationStatus> result = Either.right(StorageOperationStatus.GENERAL_ERROR); List<Component> componentList = new ArrayList<Component>(); @@ -941,8 +879,7 @@ public class LifecycleOperation implements ILifecycleOperation { createOldVersionsCriteria(nodeType, uuid, hasProps, hasNotProps); - Either<List<ComponentMetadataData>, TitanOperationStatus> getByCriteria = titanGenericDao - .getByCriteria(nodeType, hasProps, hasNotProps, ComponentMetadataData.class); + Either<List<ComponentMetadataData>, TitanOperationStatus> getByCriteria = titanGenericDao.getByCriteria(nodeType, hasProps, hasNotProps, ComponentMetadataData.class); if (getByCriteria.isRight()) { log.error("failed to get old versions for component, type:{}, id: {}", nodeType, uuid); @@ -952,8 +889,7 @@ public class LifecycleOperation implements ILifecycleOperation { List<ComponentMetadataData> oldVersionComponents = getByCriteria.left().value(); for (ComponentMetadataData component : oldVersionComponents) { - Either<Component, StorageOperationStatus> resourceRes = componentOperation - .getComponent(component.getMetadataDataDefinition().getUniqueId(), true); + Either<Component, StorageOperationStatus> resourceRes = componentOperation.getComponent(component.getMetadataDataDefinition().getUniqueId(), true); if (resourceRes.isRight()) { result = Either.right(resourceRes.right().value()); return result; @@ -965,17 +901,31 @@ public class LifecycleOperation implements ILifecycleOperation { return result; } - private void createOldVersionsCriteria(NodeTypeEnum nodeType, String uuid, Map<String, Object> hasProps, - Map<String, Object> hasNotProps) { + /* + * private Either<List<Service>, StorageOperationStatus> getServiceTempVersions(NodeTypeEnum nodeType, String uuid) { + * + * Either<List<Service>, StorageOperationStatus> result = Either.right(StorageOperationStatus.GENERAL_ERROR); List<Service> resourceList = new ArrayList<Service>(); + * + * Map<String, Object> hasProps = new HashMap<String, Object>(); Map<String, Object> hasNotProps = new HashMap<String, Object>(); + * + * createOldVersionsCriteria(nodeType, uuid, hasProps, hasNotProps); + * + * Either<List<ServiceMetadataData>, TitanOperationStatus> getByCriteria = titanGenericDao.getByCriteria(NodeTypeEnum.Service, hasProps, hasNotProps, ServiceMetadataData.class); + * + * if (getByCriteria.isRight()) { log.error("failed to get old versions for {}", uuid); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus( getByCriteria.right().value())); return result; } + * + * List<ServiceMetadataData> oldVersionResources = getByCriteria.left().value(); for (ServiceMetadataData resource : oldVersionResources) { Either<Service, StorageOperationStatus> resourceRes = serviceOperation.getService((String) + * resource.getUniqueId(), true); if (resourceRes.isRight()) { result = Either.right(resourceRes.right().value()); return result; } else { resourceList.add(resourceRes.left().value()); } } result = Either.left(resourceList); return result; } + */ + private void createOldVersionsCriteria(NodeTypeEnum nodeType, String uuid, Map<String, Object> hasProps, Map<String, Object> hasNotProps) { hasProps.put(GraphPropertiesDictionary.UUID.getProperty(), uuid); hasProps.put(GraphPropertiesDictionary.LABEL.getProperty(), nodeType.name().toLowerCase()); hasNotProps.put(GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name()); } - private Either<? extends Component, StorageOperationStatus> updateOldComponentBeforeUndoCheckout( - ComponentOperation componentOperation, Component prevComponent, Component currentComponent, - String previousVersion, NodeTypeEnum nodeType, boolean inTransaction) { + private Either<? extends Component, StorageOperationStatus> updateOldComponentBeforeUndoCheckout(ComponentOperation componentOperation, Component prevComponent, Component currentComponent, String previousVersion, NodeTypeEnum nodeType, + boolean inTransaction) { log.debug("update previous version of component"); Map<String, Object> additionalQueryParams = new HashMap<String, Object>(); @@ -985,31 +935,25 @@ public class LifecycleOperation implements ILifecycleOperation { additionalQueryParams.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), resourceType.name()); } - ComponentMetadataDataDefinition metadataDataDefinition = currentComponent.getComponentMetadataDefinition() - .getMetadataDataDefinition(); - Either<? extends Component, StorageOperationStatus> getOlderCompResult = componentOperation - .getComponentByNameAndVersion(metadataDataDefinition.getName(), previousVersion, additionalQueryParams, - true); + ComponentMetadataDataDefinition metadataDataDefinition = currentComponent.getComponentMetadataDefinition().getMetadataDataDefinition(); + Either<? extends Component, StorageOperationStatus> getOlderCompResult = componentOperation.getComponentByNameAndVersion(metadataDataDefinition.getName(), previousVersion, additionalQueryParams, true); // if previous version exist - set it as current version if (getOlderCompResult.isRight()) { if (StorageOperationStatus.NOT_FOUND.equals(getOlderCompResult.right().value())) { - log.debug("No components by name and version : {} {}", metadataDataDefinition.getName(), previousVersion); + log.debug("No components by name and version: {} - {}", metadataDataDefinition.getName(), previousVersion); log.debug("Name may have changed, since the version isn't certified try to fetch by UUID {}", metadataDataDefinition.getUUID()); additionalQueryParams.clear(); - additionalQueryParams.put(GraphPropertiesDictionary.UUID.getProperty(), - metadataDataDefinition.getUUID()); + additionalQueryParams.put(GraphPropertiesDictionary.UUID.getProperty(), metadataDataDefinition.getUUID()); additionalQueryParams.put(GraphPropertiesDictionary.VERSION.getProperty(), previousVersion); - Either<List<ComponentMetadataData>, TitanOperationStatus> byUUID = titanGenericDao - .getByCriteria(nodeType, additionalQueryParams, ComponentMetadataData.class); + Either<List<ComponentMetadataData>, TitanOperationStatus> byUUID = titanGenericDao.getByCriteria(nodeType, additionalQueryParams, ComponentMetadataData.class); if (byUUID.isRight()) { log.debug("Failed to fetch by UUID {}", metadataDataDefinition.getUUID()); return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(byUUID.right().value())); } String prevVersionId = (String) byUUID.left().value().get(0).getUniqueId(); - Either<? extends Component, StorageOperationStatus> component = componentOperation - .getComponent(prevVersionId, inTransaction); + Either<? extends Component, StorageOperationStatus> component = componentOperation.getComponent(prevVersionId, inTransaction); if (component.isRight()) { log.debug("Failed to fetch previous component by ID {}", prevVersionId); return Either.right(component.right().value()); @@ -1029,8 +973,7 @@ public class LifecycleOperation implements ILifecycleOperation { } prevComponent.setHighestVersion(true); - Either<Component, StorageOperationStatus> updateCompResult = componentOperation.updateComponent(prevComponent, - inTransaction); + Either<Component, StorageOperationStatus> updateCompResult = componentOperation.updateComponent(prevComponent, inTransaction); if (updateCompResult.isRight()) { log.debug("failed to update prev version of component"); return updateCompResult; @@ -1038,8 +981,7 @@ public class LifecycleOperation implements ILifecycleOperation { User user = new User(); user.setUserId(prevComponent.getLastUpdaterUserId()); - StorageOperationStatus changeStateRelation = changeStateRelation(nodeType, prevComponent.getUniqueId(), user, - GraphEdgeLabels.LAST_STATE, GraphEdgeLabels.STATE); + StorageOperationStatus changeStateRelation = changeStateRelation(nodeType, prevComponent.getUniqueId(), user, GraphEdgeLabels.LAST_STATE, GraphEdgeLabels.STATE); if (!changeStateRelation.equals(StorageOperationStatus.OK)) { return Either.right(changeStateRelation); } @@ -1047,13 +989,11 @@ public class LifecycleOperation implements ILifecycleOperation { return Either.left(prevComponent); } - private StorageOperationStatus changeStateRelation(NodeTypeEnum nodeType, String componentId, User currentOwner, - GraphEdgeLabels from, GraphEdgeLabels to) { + private StorageOperationStatus changeStateRelation(NodeTypeEnum nodeType, String componentId, User currentOwner, GraphEdgeLabels from, GraphEdgeLabels to) { UniqueIdData componentData = new UniqueIdData(nodeType, componentId); UserData userData = new UserData(); userData.setUserId(currentOwner.getUserId()); - Either<GraphRelation, TitanOperationStatus> replaceRelationLabelResult = titanGenericDao - .replaceRelationLabel(userData, componentData, from, to); + Either<GraphRelation, TitanOperationStatus> replaceRelationLabelResult = titanGenericDao.replaceRelationLabel(userData, componentData, from, to); if (replaceRelationLabelResult.isRight()) { TitanOperationStatus titanStatus = replaceRelationLabelResult.right().value(); log.error("failed to replace label from {} to {}. status = {}", from, to, titanStatus); @@ -1066,15 +1006,13 @@ public class LifecycleOperation implements ILifecycleOperation { return StorageOperationStatus.OK; } - private StorageOperationStatus removeUserToResourceRelation(NodeTypeEnum componentType, String idFrom, String idTo, - GraphEdgeLabels label) { + private StorageOperationStatus removeUserToResourceRelation(NodeTypeEnum componentType, String idFrom, String idTo, GraphEdgeLabels label) { UniqueIdData componentV = new UniqueIdData(componentType, idTo); UserData userV = new UserData(); userV.setUserId(idFrom); // delete relation - Either<GraphRelation, TitanOperationStatus> deleteRelationResult = titanGenericDao.deleteRelation(userV, - componentV, label); + Either<GraphRelation, TitanOperationStatus> deleteRelationResult = titanGenericDao.deleteRelation(userV, componentV, label); if (deleteRelationResult.isRight()) { log.error("failed to delete relation. status={}", deleteRelationResult.right().value()); return DaoStatusConverter.convertTitanStatusToStorageStatus(deleteRelationResult.right().value()); @@ -1082,15 +1020,13 @@ public class LifecycleOperation implements ILifecycleOperation { return StorageOperationStatus.OK; } - private StorageOperationStatus createUserToResourceRelation(NodeTypeEnum componentType, String idFrom, String idTo, - GraphEdgeLabels label, Map<String, Object> props) { + private StorageOperationStatus createUserToResourceRelation(NodeTypeEnum componentType, String idFrom, String idTo, GraphEdgeLabels label, Map<String, Object> props) { UniqueIdData componentV = new UniqueIdData(componentType, idTo); UserData userV = new UserData(); userV.setUserId(idFrom); // create relation - Either<GraphRelation, TitanOperationStatus> createRelationResult = titanGenericDao.createRelation(userV, - componentV, label, props); + Either<GraphRelation, TitanOperationStatus> createRelationResult = titanGenericDao.createRelation(userV, componentV, label, props); if (createRelationResult.isRight()) { log.error("failed to create relation. status={}", createRelationResult.right().value()); return DaoStatusConverter.convertTitanStatusToStorageStatus(createRelationResult.right().value()); @@ -1099,8 +1035,7 @@ public class LifecycleOperation implements ILifecycleOperation { } @Override - public Either<? extends Component, StorageOperationStatus> cancelOrFailCertification(NodeTypeEnum nodeType, - Component component, User modifier, User owner, LifecycleStateEnum nextState, boolean inTransaction) { + public Either<? extends Component, StorageOperationStatus> cancelOrFailCertification(NodeTypeEnum nodeType, Component component, User modifier, User owner, LifecycleStateEnum nextState, boolean inTransaction) { Either<? extends Component, StorageOperationStatus> result = Either.right(StorageOperationStatus.GENERAL_ERROR); try { @@ -1108,8 +1043,7 @@ public class LifecycleOperation implements ILifecycleOperation { ComponentParametersView componentParametersView = buildFilterForFetchComponentAfterChangeState(); result = updateComponentMD(component, modifier, nextState, nodeType, componentParametersView); if (result.isRight()) { - log.debug("Couldn't set lifecycle for component {} to state {}, error: {}", component.getUniqueId(), - nextState, result.right().value()); + log.debug("Couldn't set lifecycle for component {} to state {}, error: {}", component.getUniqueId(), nextState, result.right().value()); return result; } StorageOperationStatus status = StorageOperationStatus.OK; diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/OnboardingClient.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/OnboardingClient.java index a7f8275064..033d5c268b 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/OnboardingClient.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/OnboardingClient.java @@ -91,7 +91,6 @@ public class OnboardingClient { } - // Mock returning a file from the file system until we have API from onboarding public Either<Map<String, byte[]>, StorageOperationStatus> getMockCsar(String csarUuid) { File dir = new File("/var/tmp/mockCsar"); FileFilter fileFilter = new WildcardFileFilter("*.csar"); @@ -169,7 +168,7 @@ public class OnboardingClient { /** * Build the url for download CSAR * - * E.g., http://1.2.3.4:8181/onboarding-api/v1.0/vendor-software-products/packages/ + * E.g., http://0.0.0.0:8181/onboarding-api/v1.0/vendor-software-products/packages/ * * @return */ diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperation.java index d085c242e8..796fc8dd34 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperation.java @@ -64,8 +64,7 @@ public class PolicyTypeOperation extends AbstractOperation implements IPolicyTyp return getLatestPolicyTypeByType(policyTypeName, false); } - private Either<PolicyTypeDefinition, StorageOperationStatus> getLatestPolicyTypeByType(String type, - boolean inTransaction) { + private Either<PolicyTypeDefinition, StorageOperationStatus> getLatestPolicyTypeByType(String type, boolean inTransaction) { Map<String, Object> mapCriteria = new HashMap<>(); mapCriteria.put(GraphPropertiesDictionary.TYPE.getProperty(), type); mapCriteria.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true); @@ -79,8 +78,7 @@ public class PolicyTypeOperation extends AbstractOperation implements IPolicyTyp } @Override - public Either<PolicyTypeDefinition, StorageOperationStatus> addPolicyType(PolicyTypeDefinition policyTypeDef, - boolean inTransaction) { + public Either<PolicyTypeDefinition, StorageOperationStatus> addPolicyType(PolicyTypeDefinition policyTypeDef, boolean inTransaction) { Either<PolicyTypeDefinition, StorageOperationStatus> result = null; @@ -89,10 +87,8 @@ public class PolicyTypeOperation extends AbstractOperation implements IPolicyTyp Either<PolicyTypeData, TitanOperationStatus> eitherStatus = addPolicyTypeToGraph(policyTypeDef); if (eitherStatus.isRight()) { - BeEcompErrorManager.getInstance().logBeFailedCreateNodeError(CREATE_FLOW_CONTEXT, - policyTypeDef.getType(), eitherStatus.right().value().name()); - result = Either - .right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherStatus.right().value())); + BeEcompErrorManager.getInstance().logBeFailedCreateNodeError(CREATE_FLOW_CONTEXT, policyTypeDef.getType(), eitherStatus.right().value().name()); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherStatus.right().value())); } else { PolicyTypeData policyTypeData = eitherStatus.left().value(); @@ -101,8 +97,7 @@ public class PolicyTypeOperation extends AbstractOperation implements IPolicyTyp Either<PolicyTypeDefinition, StorageOperationStatus> policyTypeRes = this.getPolicyType(uniqueId, true); if (policyTypeRes.isRight()) { - BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError(GET_FLOW_CONTEXT, - policyTypeDef.getType(), eitherStatus.right().value().name()); + BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError(GET_FLOW_CONTEXT, policyTypeDef.getType(), eitherStatus.right().value().name()); } result = policyTypeRes; @@ -126,20 +121,18 @@ public class PolicyTypeOperation extends AbstractOperation implements IPolicyTyp log.debug("Before adding policy type to graph. policyTypeData = {}", policyTypeData); - Either<PolicyTypeData, TitanOperationStatus> eitherPolicyTypeData = titanGenericDao.createNode(policyTypeData, - PolicyTypeData.class); + Either<PolicyTypeData, TitanOperationStatus> eitherPolicyTypeData = titanGenericDao.createNode(policyTypeData, PolicyTypeData.class); log.debug("After adding policy type to graph. status is = {}", eitherPolicyTypeData); if (eitherPolicyTypeData.isRight()) { TitanOperationStatus operationStatus = eitherPolicyTypeData.right().value(); - log.error("Failed to add policy type {} to graph. Status is {}", policyTypeDef.getType(), operationStatus); + log.error("Failed to add policy type {} to graph. status is {}", policyTypeDef.getType(), operationStatus); return Either.right(operationStatus); } PolicyTypeData resultCTD = eitherPolicyTypeData.left().value(); List<PropertyDefinition> properties = policyTypeDef.getProperties(); - Either<Map<String, PropertyData>, TitanOperationStatus> addPropertiesToPolicyType = propertyOperation - .addPropertiesToElementType(resultCTD.getUniqueId(), NodeTypeEnum.PolicyType, properties); + Either<Map<String, PropertyData>, TitanOperationStatus> addPropertiesToPolicyType = propertyOperation.addPropertiesToElementType(resultCTD.getUniqueId(), NodeTypeEnum.PolicyType, properties); if (addPropertiesToPolicyType.isRight()) { log.error("Failed add properties {} to policy {}", properties, policyTypeDef.getType()); return Either.right(addPropertiesToPolicyType.right().value()); @@ -148,8 +141,7 @@ public class PolicyTypeOperation extends AbstractOperation implements IPolicyTyp return Either.left(eitherPolicyTypeData.left().value()); } - public Either<PolicyTypeDefinition, StorageOperationStatus> getPolicyTypeByCriteria(String type, - Map<String, Object> properties, boolean inTransaction) { + public Either<PolicyTypeDefinition, StorageOperationStatus> getPolicyTypeByCriteria(String type, Map<String, Object> properties, boolean inTransaction) { Either<PolicyTypeDefinition, StorageOperationStatus> result = null; try { if (type == null || type.isEmpty()) { @@ -158,14 +150,11 @@ public class PolicyTypeOperation extends AbstractOperation implements IPolicyTyp return result; } - Either<List<PolicyTypeData>, TitanOperationStatus> eitherPolicyData = titanGenericDao - .getByCriteria(NodeTypeEnum.PolicyType, properties, PolicyTypeData.class); + Either<List<PolicyTypeData>, TitanOperationStatus> eitherPolicyData = titanGenericDao.getByCriteria(NodeTypeEnum.PolicyType, properties, PolicyTypeData.class); if (eitherPolicyData.isRight()) { - result = Either - .right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherPolicyData.right().value())); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherPolicyData.right().value())); } else { - PolicyTypeDataDefinition dataDefinition = eitherPolicyData.left().value().stream() - .map(e -> e.getPolicyTypeDataDefinition()).findFirst().get(); + PolicyTypeDataDefinition dataDefinition = eitherPolicyData.left().value().stream().map(e -> e.getPolicyTypeDataDefinition()).findFirst().get(); result = getPolicyType(dataDefinition.getUniqueId(), inTransaction); } @@ -178,8 +167,7 @@ public class PolicyTypeOperation extends AbstractOperation implements IPolicyTyp @Override public Either<PolicyTypeDefinition, StorageOperationStatus> getPolicyType(String uniqueId, boolean inTransaction) { - Function<String, Either<PolicyTypeDefinition, TitanOperationStatus>> policyTypeGetter = uId -> getPolicyTypeByUid( - uId); + Function<String, Either<PolicyTypeDefinition, TitanOperationStatus>> policyTypeGetter = uId -> getPolicyTypeByUid(uId); return getElementType(policyTypeGetter, uniqueId, inTransaction); } @@ -187,21 +175,18 @@ public class PolicyTypeOperation extends AbstractOperation implements IPolicyTyp private Either<PolicyTypeDefinition, TitanOperationStatus> getPolicyTypeByUid(String uniqueId) { Either<PolicyTypeDefinition, TitanOperationStatus> result = null; - Either<PolicyTypeData, TitanOperationStatus> eitherPolicyTypeData = titanGenericDao - .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PolicyType), uniqueId, PolicyTypeData.class); + Either<PolicyTypeData, TitanOperationStatus> eitherPolicyTypeData = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PolicyType), uniqueId, PolicyTypeData.class); if (eitherPolicyTypeData.isRight()) { TitanOperationStatus status = eitherPolicyTypeData.right().value(); - log.debug("Policy type {} cannot be found in graph. Status is {}", uniqueId, status); + log.debug("Policy type {} cannot be found in graph. status is {}", uniqueId, status); return Either.right(status); } PolicyTypeData policyTypeData = eitherPolicyTypeData.left().value(); - PolicyTypeDefinition policyTypeDefinition = new PolicyTypeDefinition( - policyTypeData.getPolicyTypeDataDefinition()); + PolicyTypeDefinition policyTypeDefinition = new PolicyTypeDefinition(policyTypeData.getPolicyTypeDataDefinition()); - TitanOperationStatus propertiesStatus = propertyOperation.fillProperties(uniqueId, - propList -> policyTypeDefinition.setProperties(propList)); + TitanOperationStatus propertiesStatus = propertyOperation.fillProperties(uniqueId, propList -> policyTypeDefinition.setProperties(propList)); if (propertiesStatus != TitanOperationStatus.OK) { log.error("Failed to fetch properties of policy type {}", uniqueId); return Either.right(propertiesStatus); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ProductOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ProductOperation.java index 2a8192421b..3d4fba36df 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ProductOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ProductOperation.java @@ -94,10 +94,8 @@ public class ProductOperation extends ComponentOperation implements IProductOper @SuppressWarnings("unchecked") @Override - protected <T> Either<T, StorageOperationStatus> getComponentByNameAndVersion(String name, String version, - Map<String, Object> additionalParams, boolean inTransaction) { - return (Either<T, StorageOperationStatus>) getByNamesAndVersion(GraphPropertiesDictionary.NAME.getProperty(), - name, version, additionalParams, inTransaction); + protected <T> Either<T, StorageOperationStatus> getComponentByNameAndVersion(String name, String version, Map<String, Object> additionalParams, boolean inTransaction) { + return (Either<T, StorageOperationStatus>) getByNamesAndVersion(GraphPropertiesDictionary.NAME.getProperty(), name, version, additionalParams, inTransaction); } @Override @@ -106,14 +104,12 @@ public class ProductOperation extends ComponentOperation implements IProductOper } @Override - public <T> Either<List<T>, StorageOperationStatus> getFilteredComponents(Map<FilterKeyEnum, String> filters, - boolean inTransaction) { + public <T> Either<List<T>, StorageOperationStatus> getFilteredComponents(Map<FilterKeyEnum, String> filters, boolean inTransaction) { return getFilteredComponents(filters, inTransaction, NodeTypeEnum.Product); } private Product convertProductDataToProduct(ProductMetadataData productData) { - ProductMetadataDefinition productMetadataDefinition = new ProductMetadataDefinition( - (ProductMetadataDataDefinition) productData.getMetadataDataDefinition()); + ProductMetadataDefinition productMetadataDefinition = new ProductMetadataDefinition((ProductMetadataDataDefinition) productData.getMetadataDataDefinition()); Product product = new Product(productMetadataDefinition); @@ -123,28 +119,24 @@ public class ProductOperation extends ComponentOperation implements IProductOper @SuppressWarnings("unchecked") @Override public <T> Either<T, StorageOperationStatus> updateComponent(T component, boolean inTransaction) { - return (Either<T, StorageOperationStatus>) updateComponent((Component) component, inTransaction, - titanGenericDao, Product.class, NodeTypeEnum.Product); + return (Either<T, StorageOperationStatus>) updateComponent((Component) component, inTransaction, titanGenericDao, Product.class, NodeTypeEnum.Product); } @SuppressWarnings("unchecked") @Override public Either<Component, StorageOperationStatus> deleteComponent(String id, boolean inTransaction) { - return (Either<Component, StorageOperationStatus>) (Either<?, StorageOperationStatus>) deleteProduct(id, - inTransaction); + return (Either<Component, StorageOperationStatus>) (Either<?, StorageOperationStatus>) deleteProduct(id, inTransaction); } @Override - public Either<List<ArtifactDefinition>, StorageOperationStatus> getAdditionalArtifacts(String resourceId, - boolean recursively, boolean inTransaction) { + public Either<List<ArtifactDefinition>, StorageOperationStatus> getAdditionalArtifacts(String resourceId, boolean recursively, boolean inTransaction) { // TODO Auto-generated method stub return null; } @SuppressWarnings("unchecked") @Override - public <T extends org.openecomp.sdc.be.model.Component> Either<T, StorageOperationStatus> getComponent(String id, - Class<T> clazz) { + public <T extends org.openecomp.sdc.be.model.Component> Either<T, StorageOperationStatus> getComponent(String id, Class<T> clazz) { return (Either<T, StorageOperationStatus>) getProduct(id, false); } @@ -160,16 +152,14 @@ public class ProductOperation extends ComponentOperation implements IProductOper Either<TitanGraph, TitanOperationStatus> graphResult = titanGenericDao.getGraph(); if (graphResult.isRight()) { - result = Either - .right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value())); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value())); return result; } - Either<ProductMetadataData, TitanOperationStatus> productNode = titanGenericDao.getNode( - UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Product), productId, ProductMetadataData.class); + Either<ProductMetadataData, TitanOperationStatus> productNode = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Product), productId, ProductMetadataData.class); if (productNode.isRight()) { TitanOperationStatus status = productNode.right().value(); - log.error("Failed to find product {}. Status is {}", productId, status); + log.error("Failed to find product {}. status is {}", productId, status); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); return result; } @@ -177,29 +167,27 @@ public class ProductOperation extends ComponentOperation implements IProductOper Either<Product, StorageOperationStatus> productRes = getProduct(productId, true); if (productRes.isRight()) { StorageOperationStatus status = productRes.right().value(); - log.error("Failed to find product {}", productId, status); + log.error("Failed to find product {}.status is {}", productId, status); result = Either.right(status); return result; } Product product = productRes.left().value(); - Either<List<ComponentInstance>, StorageOperationStatus> deleteAllInstancesRes = componentInstanceOperation - .deleteAllComponentInstances(productId, NodeTypeEnum.Product, true); - log.debug("After deleting instances under product {}. Result is {}", productId, deleteAllInstancesRes); + Either<List<ComponentInstance>, StorageOperationStatus> deleteAllInstancesRes = componentInstanceOperation.deleteAllComponentInstances(productId, NodeTypeEnum.Product, true); + log.debug("After deleting instances under product {}.Result is {}", productId, deleteAllInstancesRes); if (deleteAllInstancesRes.isRight()) { StorageOperationStatus status = deleteAllInstancesRes.right().value(); if (status != StorageOperationStatus.NOT_FOUND) { - log.error("Failed to delete instances under product {}. Status is {}", productId, status); + log.error("Failed to delete instances under product {}.status is {}", productId, status); result = Either.right(status); return result; } } - Either<ProductMetadataData, TitanOperationStatus> deleteProductNodeRes = titanGenericDao - .deleteNode(productNode.left().value(), ProductMetadataData.class); + Either<ProductMetadataData, TitanOperationStatus> deleteProductNodeRes = titanGenericDao.deleteNode(productNode.left().value(), ProductMetadataData.class); if (deleteProductNodeRes.isRight()) { TitanOperationStatus status = deleteProductNodeRes.right().value(); - log.error("Failed to delete product node {}. Status is {}", productId, status); + log.error("Failed to delete product node {}. status is {}", productId, status); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); return result; } @@ -230,47 +218,20 @@ public class ProductOperation extends ComponentOperation implements IProductOper /* * Map<String, Object> propertiesToMatch = new HashMap<>(); * - * propertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty - * (), LifecycleStateEnum.CERTIFIED.name()); - * Either<List<ProductMetadataData>, TitanOperationStatus> - * lastVersionNodes = getLastVersion(NodeTypeEnum.Product, - * propertiesToMatch, ProductMetadataData.class); if - * (lastVersionNodes.isRight() && lastVersionNodes.right().value() - * != TitanOperationStatus.NOT_FOUND) { return - * Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus - * (lastVersionNodes.right().value())); } List<ProductMetadataData> - * notCertifiedHighest = (lastVersionNodes.isLeft() ? - * lastVersionNodes.left().value() : new - * ArrayList<ProductMetadataData>()); + * propertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty (), LifecycleStateEnum.CERTIFIED.name()); Either<List<ProductMetadataData>, TitanOperationStatus> lastVersionNodes = getLastVersion(NodeTypeEnum.Product, + * propertiesToMatch, ProductMetadataData.class); if (lastVersionNodes.isRight() && lastVersionNodes.right().value() != TitanOperationStatus.NOT_FOUND) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus + * (lastVersionNodes.right().value())); } List<ProductMetadataData> notCertifiedHighest = (lastVersionNodes.isLeft() ? lastVersionNodes.left().value() : new ArrayList<ProductMetadataData>()); * - * propertiesToMatch.put(GraphPropertiesDictionary. - * IS_HIGHEST_VERSION.getProperty(), true); - * Either<List<ProductMetadataData>, TitanOperationStatus> - * componentsNodes = - * titanGenericDao.getByCriteria(NodeTypeEnum.Product, - * propertiesToMatch, ProductMetadataData.class); if - * (componentsNodes.isRight() && componentsNodes.right().value() != - * TitanOperationStatus.NOT_FOUND) { return - * Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus - * (componentsNodes.right().value())); } List<ProductMetadataData> - * certifiedHighest = (componentsNodes.isLeft() ? - * componentsNodes.left().value() : new - * ArrayList<ProductMetadataData>()); Set<String> names = new - * HashSet<String>(); for (ProductMetadataData data : - * notCertifiedHighest) { String name = - * data.getMetadataDataDefinition().getName(); names.add(name); } + * propertiesToMatch.put(GraphPropertiesDictionary. IS_HIGHEST_VERSION.getProperty(), true); Either<List<ProductMetadataData>, TitanOperationStatus> componentsNodes = titanGenericDao.getByCriteria(NodeTypeEnum.Product, propertiesToMatch, + * ProductMetadataData.class); if (componentsNodes.isRight() && componentsNodes.right().value() != TitanOperationStatus.NOT_FOUND) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus + * (componentsNodes.right().value())); } List<ProductMetadataData> certifiedHighest = (componentsNodes.isLeft() ? componentsNodes.left().value() : new ArrayList<ProductMetadataData>()); Set<String> names = new HashSet<String>(); for + * (ProductMetadataData data : notCertifiedHighest) { String name = data.getMetadataDataDefinition().getName(); names.add(name); } * - * for (ProductMetadataData data : certifiedHighest) { String - * productName = data.getMetadataDataDefinition().getName(); if - * (!names.contains(productName)) { notCertifiedHighest.add(data); } - * } + * for (ProductMetadataData data : certifiedHighest) { String productName = data.getMetadataDataDefinition().getName(); if (!names.contains(productName)) { notCertifiedHighest.add(data); } } */ - Either<List<ProductMetadataData>, TitanOperationStatus> listOfHighestComponents = this - .getListOfHighestComponents(NodeTypeEnum.Product, ProductMetadataData.class); - if (listOfHighestComponents.isRight() - && listOfHighestComponents.right().value() != TitanOperationStatus.NOT_FOUND) { - return Either.right( - DaoStatusConverter.convertTitanStatusToStorageStatus(listOfHighestComponents.right().value())); + Either<List<ProductMetadataData>, TitanOperationStatus> listOfHighestComponents = this.getListOfHighestComponents(NodeTypeEnum.Product, ProductMetadataData.class); + if (listOfHighestComponents.isRight() && listOfHighestComponents.right().value() != TitanOperationStatus.NOT_FOUND) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(listOfHighestComponents.right().value())); } List<ProductMetadataData> notCertifiedHighest = listOfHighestComponents.left().value(); @@ -282,42 +243,30 @@ public class ProductOperation extends ComponentOperation implements IProductOper // fetch from cache long startFetchAllFromCache = System.currentTimeMillis(); - Map<String, Long> components = notCertifiedHighest.stream() - .collect(Collectors.toMap(p -> p.getMetadataDataDefinition().getUniqueId(), - p -> p.getMetadataDataDefinition().getLastUpdateDate())); + Map<String, Long> components = notCertifiedHighest.stream().collect(Collectors.toMap(p -> p.getMetadataDataDefinition().getUniqueId(), p -> p.getMetadataDataDefinition().getLastUpdateDate())); - Either<ImmutablePair<List<Component>, Set<String>>, ActionStatus> componentsFromCacheForCatalog = this - .getComponentsFromCacheForCatalog(components, ComponentTypeEnum.PRODUCT); + Either<ImmutablePair<List<Component>, Set<String>>, ActionStatus> componentsFromCacheForCatalog = this.getComponentsFromCacheForCatalog(components, ComponentTypeEnum.PRODUCT); if (componentsFromCacheForCatalog.isLeft()) { - ImmutablePair<List<Component>, Set<String>> immutablePair = componentsFromCacheForCatalog.left() - .value(); + ImmutablePair<List<Component>, Set<String>> immutablePair = componentsFromCacheForCatalog.left().value(); List<Component> list = immutablePair.getLeft(); if (list != null) { for (Component component : list) { result.add((Product) component); } - List<String> addedUids = list.stream() - .map(p -> p.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId()) - .collect(Collectors.toList()); - notCertifiedHighest = notCertifiedHighest.stream() - .filter(p -> false == addedUids.contains(p.getMetadataDataDefinition().getUniqueId())) - .collect(Collectors.toList()); + List<String> addedUids = list.stream().map(p -> p.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId()).collect(Collectors.toList()); + notCertifiedHighest = notCertifiedHighest.stream().filter(p -> false == addedUids.contains(p.getMetadataDataDefinition().getUniqueId())).collect(Collectors.toList()); } } long endFetchAllFromCache = System.currentTimeMillis(); - log.debug("Fetch all catalog products metadata from cache took {} ms", - (endFetchAllFromCache - startFetchAllFromCache)); + log.debug("Fetch all catalog products metadata from cache took {} ms", (endFetchAllFromCache - startFetchAllFromCache)); log.debug("The number of products added to catalog from cache is {}", result.size()); - log.debug("The number of products needed to be fetch as light component is {}", - notCertifiedHighest.size()); + log.debug("The number of products needed to be fetch as light component is {}", notCertifiedHighest.size()); for (ProductMetadataData data : notCertifiedHighest) { - Either<Product, StorageOperationStatus> component = getLightComponent( - data.getMetadataDataDefinition().getUniqueId(), inTransaction); + Either<Product, StorageOperationStatus> component = getLightComponent(data.getMetadataDataDefinition().getUniqueId(), inTransaction); if (component.isRight()) { - log.debug("Failed to get product for id = {}, error : {}. skip product", data.getUniqueId(), - component.right().value()); + log.debug("Failed to get product for id = {}, error : {}. skip product", data.getUniqueId(), component.right().value()); } else { // get all versions Product product = component.left().value(); @@ -332,7 +281,7 @@ public class ProductOperation extends ComponentOperation implements IProductOper if (false == inTransaction) { titanGenericDao.commit(); } - log.debug("Fetch all catalog products took {} ms", (System.currentTimeMillis() - start)); + log.debug("Fetch all catalog products took {} ms", System.currentTimeMillis() - start); } } @@ -383,34 +332,29 @@ public class ProductOperation extends ComponentOperation implements IProductOper } log.trace("Finding groupings for product {}", uniqueId); - Either<List<GroupingData>, StorageOperationStatus> findGroupingsForComponent = findGroupingsForComponent( - NodeTypeEnum.ProductGrouping, product); + Either<List<GroupingData>, StorageOperationStatus> findGroupingsForComponent = findGroupingsForComponent(NodeTypeEnum.ProductGrouping, product); if (findGroupingsForComponent.isRight()) { return Either.right(findGroupingsForComponent.right().value()); } List<GroupingData> groupingDataToAssociate = findGroupingsForComponent.left().value(); log.debug("try to create product node on graph for id {}", uniqueId); - Either<ProductMetadataData, TitanOperationStatus> createNode = titanGenericDao.createNode(productData, - ProductMetadataData.class); + Either<ProductMetadataData, TitanOperationStatus> createNode = titanGenericDao.createNode(productData, ProductMetadataData.class); if (createNode.isRight()) { TitanOperationStatus status = createNode.right().value(); - log.error("Error returned after creating product data node {}. Status returned is {}", productData, - status); + log.error("Error returned after creating product data node {}. Status returned is {}", productData, status); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); return result; } log.debug("product node created on graph for id {}", productData.getUniqueId()); - TitanOperationStatus associateMetadata = associateMetadataToComponent(productData, creatorUserData, - updaterUserData, null, null); + TitanOperationStatus associateMetadata = associateMetadataToComponent(productData, creatorUserData, updaterUserData, null, null); if (associateMetadata != TitanOperationStatus.OK) { result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(associateMetadata)); return result; } - TitanOperationStatus associateCategories = associateCategoriesToProduct(productData, - groupingDataToAssociate); + TitanOperationStatus associateCategories = associateCategoriesToProduct(productData, groupingDataToAssociate); if (associateCategories != TitanOperationStatus.OK) { result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(associateCategories)); return result; @@ -442,14 +386,11 @@ public class ProductOperation extends ComponentOperation implements IProductOper } } - private TitanOperationStatus associateCategoriesToProduct(ProductMetadataData productData, - List<GroupingData> groupingDataToAssociate) { + private TitanOperationStatus associateCategoriesToProduct(ProductMetadataData productData, List<GroupingData> groupingDataToAssociate) { for (GroupingData groupingData : groupingDataToAssociate) { GraphEdgeLabels groupingLabel = GraphEdgeLabels.CATEGORIZED_TO; - Either<GraphRelation, TitanOperationStatus> result = titanGenericDao.createRelation(productData, - groupingData, groupingLabel, null); - log.debug("After associating grouping {} to product {}. Edge type is {}", groupingData, productData, - groupingLabel); + Either<GraphRelation, TitanOperationStatus> result = titanGenericDao.createRelation(productData, groupingData, groupingLabel, null); + log.debug("After associating grouping {} to product {}. Edge type is {}", groupingData, productData, groupingLabel); if (result.isRight()) { return result.right().value(); } @@ -458,14 +399,11 @@ public class ProductOperation extends ComponentOperation implements IProductOper return TitanOperationStatus.OK; } - private TitanOperationStatus dissociateCategoriesFromProduct(ProductMetadataData productData, - List<GroupingData> groupingDataToDissociate) { + private TitanOperationStatus dissociateCategoriesFromProduct(ProductMetadataData productData, List<GroupingData> groupingDataToDissociate) { for (GroupingData groupingData : groupingDataToDissociate) { GraphEdgeLabels groupingLabel = GraphEdgeLabels.CATEGORIZED_TO; - Either<GraphRelation, TitanOperationStatus> result = titanGenericDao.deleteRelation(productData, - groupingData, groupingLabel); - log.debug("After dissociating grouping {} from product {}. Edge type is {}", groupingData, productData, - groupingLabel); + Either<GraphRelation, TitanOperationStatus> result = titanGenericDao.deleteRelation(productData, groupingData, groupingLabel); + log.debug("After dissociating grouping {} from product {}. Edge type is {}", groupingData, productData, groupingLabel); if (result.isRight()) { return result.right().value(); } @@ -479,8 +417,7 @@ public class ProductOperation extends ComponentOperation implements IProductOper return getProduct(uniqueId, componentParametersView, inTransaction); } - private Either<Product, StorageOperationStatus> getProduct(String uniqueId, - ComponentParametersView componentParametersView, boolean inTransaction) { + private Either<Product, StorageOperationStatus> getProduct(String uniqueId, ComponentParametersView componentParametersView, boolean inTransaction) { Product product = null; Either<Product, StorageOperationStatus> result = null; try { @@ -488,8 +425,7 @@ public class ProductOperation extends ComponentOperation implements IProductOper NodeTypeEnum productNodeType = NodeTypeEnum.Product; NodeTypeEnum compInstNodeType = NodeTypeEnum.Service; - Either<ProductMetadataData, StorageOperationStatus> getComponentByLabel = getComponentByLabelAndId(uniqueId, - productNodeType, ProductMetadataData.class); + Either<ProductMetadataData, StorageOperationStatus> getComponentByLabel = getComponentByLabelAndId(uniqueId, productNodeType, ProductMetadataData.class); if (getComponentByLabel.isRight()) { result = Either.right(getComponentByLabel.right().value()); return result; @@ -499,12 +435,10 @@ public class ProductOperation extends ComponentOperation implements IProductOper // Try to fetch resource from the cache. The resource will be // fetched only if the time on the cache equals to // the time on the graph. - Either<Product, ActionStatus> componentFromCacheIfUpToDate = this.getComponentFromCacheIfUpToDate(uniqueId, - productData, componentParametersView, Product.class, ComponentTypeEnum.PRODUCT); + Either<Product, ActionStatus> componentFromCacheIfUpToDate = this.getComponentFromCacheIfUpToDate(uniqueId, productData, componentParametersView, Product.class, ComponentTypeEnum.PRODUCT); if (componentFromCacheIfUpToDate.isLeft()) { Product cachedProduct = componentFromCacheIfUpToDate.left().value(); - log.debug("Product {} with uid {} was fetched from cache.", cachedProduct.getName(), - cachedProduct.getUniqueId()); + log.debug("Product {} with uid {} was fetched from cache.", cachedProduct.getName(), cachedProduct.getUniqueId()); return Either.left(cachedProduct); } @@ -533,9 +467,7 @@ public class ProductOperation extends ComponentOperation implements IProductOper } } - if (false == componentParametersView.isIgnoreComponentInstances() - || false == componentParametersView.isIgnoreComponentInstancesProperties() - || false == componentParametersView.isIgnoreCapabilities() + if (false == componentParametersView.isIgnoreComponentInstances() || false == componentParametersView.isIgnoreComponentInstancesProperties() || false == componentParametersView.isIgnoreCapabilities() || false == componentParametersView.isIgnoreRequirements()) { status = setComponentInstancesFromGraph(uniqueId, product, productNodeType, compInstNodeType); if (status != TitanOperationStatus.OK) { @@ -545,7 +477,7 @@ public class ProductOperation extends ComponentOperation implements IProductOper } } if (false == componentParametersView.isIgnoreComponentInstancesProperties()) { - status = setComponentInstancesPropertiesFromGraph(uniqueId, product); + status = setComponentInstancesPropertiesFromGraph(product); if (status != TitanOperationStatus.OK) { result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); return result; @@ -683,8 +615,7 @@ public class ProductOperation extends ComponentOperation implements IProductOper // } private TitanOperationStatus setAllVersions(Product product) { - Either<Map<String, String>, TitanOperationStatus> res = getVersionList(NodeTypeEnum.Product, - product.getVersion(), product, ProductMetadataData.class); + Either<Map<String, String>, TitanOperationStatus> res = getVersionList(NodeTypeEnum.Product, product.getVersion(), product, ProductMetadataData.class); if (res.isRight()) { return res.right().value(); } @@ -692,8 +623,7 @@ public class ProductOperation extends ComponentOperation implements IProductOper return TitanOperationStatus.OK; } - private Either<Product, StorageOperationStatus> sendError(TitanOperationStatus status, - StorageOperationStatus statusIfNotFound) { + private Either<Product, StorageOperationStatus> sendError(TitanOperationStatus status, StorageOperationStatus statusIfNotFound) { Either<Product, StorageOperationStatus> result; if (status == TitanOperationStatus.NOT_FOUND) { result = Either.right(statusIfNotFound); @@ -708,9 +638,8 @@ public class ProductOperation extends ComponentOperation implements IProductOper TitanOperationStatus setComponentCategoriesFromGraph(Component component) { Product product = (Product) component; // Building the cat->subcat->grouping triples - Either<List<ImmutablePair<GroupingData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao - .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Product), product.getUniqueId(), - GraphEdgeLabels.CATEGORIZED_TO, NodeTypeEnum.ProductGrouping, GroupingData.class); + Either<List<ImmutablePair<GroupingData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Product), product.getUniqueId(), GraphEdgeLabels.CATEGORIZED_TO, + NodeTypeEnum.ProductGrouping, GroupingData.class); if (childrenNodes.isRight()) { if (childrenNodes.right().value() != TitanOperationStatus.NOT_FOUND) { log.debug("Error when finding groupings for this product, error {}", childrenNodes.right().value()); @@ -725,19 +654,15 @@ public class ProductOperation extends ComponentOperation implements IProductOper List<ImmutablePair<GroupingData, GraphEdge>> valueList = childrenNodes.left().value(); for (ImmutablePair<GroupingData, GraphEdge> groupPair : valueList) { GroupingData groupingData = groupPair.getLeft(); - Either<ImmutablePair<SubCategoryData, GraphEdge>, TitanOperationStatus> parentSubCat = titanGenericDao - .getParentNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ProductGrouping), - (String) groupingData.getUniqueId(), GraphEdgeLabels.GROUPING, - NodeTypeEnum.ProductSubcategory, SubCategoryData.class); + Either<ImmutablePair<SubCategoryData, GraphEdge>, TitanOperationStatus> parentSubCat = titanGenericDao.getParentNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ProductGrouping), (String) groupingData.getUniqueId(), + GraphEdgeLabels.GROUPING, NodeTypeEnum.ProductSubcategory, SubCategoryData.class); if (parentSubCat.isRight()) { log.debug("Cannot find subcategory for grouping {}", groupingData.getUniqueId()); return parentSubCat.right().value(); } SubCategoryData subCatData = parentSubCat.left().value().getLeft(); - Either<ImmutablePair<CategoryData, GraphEdge>, TitanOperationStatus> parentCat = titanGenericDao - .getParentNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ProductSubcategory), - (String) subCatData.getUniqueId(), GraphEdgeLabels.SUB_CATEGORY, - NodeTypeEnum.ProductCategory, CategoryData.class); + Either<ImmutablePair<CategoryData, GraphEdge>, TitanOperationStatus> parentCat = titanGenericDao.getParentNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ProductSubcategory), (String) subCatData.getUniqueId(), + GraphEdgeLabels.SUB_CATEGORY, NodeTypeEnum.ProductCategory, CategoryData.class); if (parentCat.isRight()) { log.debug("Cannot find category for subcategory {}", subCatData.getUniqueId()); return parentCat.right().value(); @@ -752,11 +677,7 @@ public class ProductOperation extends ComponentOperation implements IProductOper SubCategoryDefinition subDef = new SubCategoryDefinition(subDefinition); GroupingDefinition groupingDef = new GroupingDefinition(groupingDefinition); - if (log.isDebugEnabled()) { - log.debug("Found category {} -> subcategory {} -> grouping {} for product {}", - categoryDefinition.getUniqueId(), subCatData.getUniqueId(), groupingData.getUniqueId(), - product.getUniqueId()); - } + log.debug("Found category {} -> subcategory {} -> grouping {} for product {}", categoryDefinition.getUniqueId(), subCatData.getUniqueId(), groupingData.getUniqueId(), product.getUniqueId()); Map<SubCategoryDefinition, List<GroupingDefinition>> subMap = categoriesDataStructure.get(categoryDef); if (subMap == null) { subMap = new HashMap<>(); @@ -773,14 +694,12 @@ public class ProductOperation extends ComponentOperation implements IProductOper return TitanOperationStatus.OK; } - private void convertToCategoriesList(Product product, - Map<CategoryDefinition, Map<SubCategoryDefinition, List<GroupingDefinition>>> categoriesDataStructure) { + private void convertToCategoriesList(Product product, Map<CategoryDefinition, Map<SubCategoryDefinition, List<GroupingDefinition>>> categoriesDataStructure) { List<CategoryDefinition> categoryDataList = product.getCategories(); if (categoryDataList == null) { categoryDataList = new ArrayList<CategoryDefinition>(); } - for (Entry<CategoryDefinition, Map<SubCategoryDefinition, List<GroupingDefinition>>> triple : categoriesDataStructure - .entrySet()) { + for (Entry<CategoryDefinition, Map<SubCategoryDefinition, List<GroupingDefinition>>> triple : categoriesDataStructure.entrySet()) { CategoryDefinition categoryDefinition = triple.getKey(); List<SubCategoryDefinition> subList = new ArrayList<>(); categoryDefinition.setSubcategories(subList); @@ -795,13 +714,11 @@ public class ProductOperation extends ComponentOperation implements IProductOper categoryDataList.add(categoryDefinition); } product.setCategories(categoryDataList); - log.debug("Fetched categories for product {}, categories: {}", product.getUniqueId(), - Arrays.toString(categoryDataList.toArray())); + log.debug("Fetched categories for product {}, categories: {}", product.getUniqueId(), Arrays.toString(categoryDataList.toArray())); } private ProductMetadataData getProductMetadataDataFromProduct(Product product) { - ProductMetadataData productMetadata = new ProductMetadataData( - (ProductMetadataDataDefinition) product.getComponentMetadataDefinition().getMetadataDataDefinition()); + ProductMetadataData productMetadata = new ProductMetadataData((ProductMetadataDataDefinition) product.getComponentMetadataDefinition().getMetadataDataDefinition()); return productMetadata; } @@ -820,14 +737,11 @@ public class ProductOperation extends ComponentOperation implements IProductOper @SuppressWarnings("unchecked") @Override - public <T> Either<T, StorageOperationStatus> cloneComponent(T other, String version, - LifecycleStateEnum targetLifecycle, boolean inTransaction) { - return (Either<T, StorageOperationStatus>) cloneProduct((Product) other, version, targetLifecycle, - inTransaction); + public <T> Either<T, StorageOperationStatus> cloneComponent(T other, String version, LifecycleStateEnum targetLifecycle, boolean inTransaction) { + return (Either<T, StorageOperationStatus>) cloneProduct((Product) other, version, targetLifecycle, inTransaction); } - private Either<Product, StorageOperationStatus> cloneProduct(Product other, String version, - LifecycleStateEnum targetLifecycle, boolean inTransaction) { + private Either<Product, StorageOperationStatus> cloneProduct(Product other, String version, LifecycleStateEnum targetLifecycle, boolean inTransaction) { Either<Product, StorageOperationStatus> result = null; try { @@ -835,12 +749,10 @@ public class ProductOperation extends ComponentOperation implements IProductOper other.setVersion(version); other.setUniqueId(null); - Either<Integer, StorageOperationStatus> counterStatus = getComponentInstanceCoutner(origProductId, - NodeTypeEnum.Product); + Either<Integer, StorageOperationStatus> counterStatus = getComponentInstanceCoutner(origProductId, NodeTypeEnum.Product); if (counterStatus.isRight()) { StorageOperationStatus status = counterStatus.right().value(); - log.error("failed to get resource instance counter on product {}. status={}", origProductId, - counterStatus); + log.error("failed to get resource instance counter on product {}. status={}", origProductId, counterStatus); result = Either.right(status); return result; } @@ -861,12 +773,10 @@ public class ProductOperation extends ComponentOperation implements IProductOper return result; } - Either<Integer, StorageOperationStatus> setResourceInstanceCounter = setComponentInstanceCounter( - product.getUniqueId(), NodeTypeEnum.Product, counterStatus.left().value(), inTransaction); + Either<Integer, StorageOperationStatus> setResourceInstanceCounter = setComponentInstanceCounter(product.getUniqueId(), NodeTypeEnum.Product, counterStatus.left().value(), inTransaction); if (setResourceInstanceCounter.isRight()) { StorageOperationStatus status = setResourceInstanceCounter.right().value(); - log.error("failed to set resource instance counter on product {}. status={}", product.getUniqueId(), - setResourceInstanceCounter); + log.error("failed to set resource instance counter on product {}. status={}", product.getUniqueId(), setResourceInstanceCounter); result = Either.right(status); return result; } @@ -896,8 +806,7 @@ public class ProductOperation extends ComponentOperation implements IProductOper } } - private Either<Product, StorageOperationStatus> getByNamesAndVersion(String nameKey, String nameValue, - String version, Map<String, Object> additionalParams, boolean inTransaction) { + private Either<Product, StorageOperationStatus> getByNamesAndVersion(String nameKey, String nameValue, String version, Map<String, Object> additionalParams, boolean inTransaction) { Map<String, Object> props = new HashMap<String, Object>(); props.put(nameKey, nameValue); props.put(GraphPropertiesDictionary.VERSION.getProperty(), version); @@ -906,8 +815,7 @@ public class ProductOperation extends ComponentOperation implements IProductOper props.putAll(additionalParams); } - Either<List<ProductMetadataData>, TitanOperationStatus> byCriteria = titanGenericDao - .getByCriteria(NodeTypeEnum.Product, props, ProductMetadataData.class); + Either<List<ProductMetadataData>, TitanOperationStatus> byCriteria = titanGenericDao.getByCriteria(NodeTypeEnum.Product, props, ProductMetadataData.class); if (byCriteria.isRight()) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(byCriteria.right().value())); @@ -919,11 +827,9 @@ public class ProductOperation extends ComponentOperation implements IProductOper return Either.right(StorageOperationStatus.GENERAL_ERROR); } ProductMetadataData productData = dataList.get(0); - Either<Product, StorageOperationStatus> product = getProduct( - productData.getMetadataDataDefinition().getUniqueId(), inTransaction); + Either<Product, StorageOperationStatus> product = getProduct(productData.getMetadataDataDefinition().getUniqueId(), inTransaction); if (product.isRight()) { - log.debug("Failed to fetch product, name {} id {}", productData.getMetadataDataDefinition().getName(), - productData.getMetadataDataDefinition().getUniqueId()); + log.debug("Failed to fetch product, name {} id {}", productData.getMetadataDataDefinition().getName(), productData.getMetadataDataDefinition().getUniqueId()); } return product; } @@ -936,49 +842,42 @@ public class ProductOperation extends ComponentOperation implements IProductOper } @Override - protected <T extends org.openecomp.sdc.be.model.Component> StorageOperationStatus updateDerived( - org.openecomp.sdc.be.model.Component component, org.openecomp.sdc.be.model.Component currentComponent, - ComponentMetadataData componentData, Class<T> clazz) { + protected <T extends org.openecomp.sdc.be.model.Component> StorageOperationStatus updateDerived(org.openecomp.sdc.be.model.Component component, org.openecomp.sdc.be.model.Component currentComponent, ComponentMetadataData componentData, + Class<T> clazz) { log.debug("Derived class isn't supported for product"); return StorageOperationStatus.OK; } @Override - public Either<Integer, StorageOperationStatus> increaseAndGetComponentInstanceCounter(String componentId, - boolean inTransaction) { + public Either<Integer, StorageOperationStatus> increaseAndGetComponentInstanceCounter(String componentId, boolean inTransaction) { return increaseAndGetComponentInstanceCounter(componentId, NodeTypeEnum.Product, inTransaction); } @Override - protected StorageOperationStatus validateCategories(Component currentComponent, Component component, - ComponentMetadataData componentData, NodeTypeEnum type) { + protected StorageOperationStatus validateCategories(Component currentComponent, Component component, ComponentMetadataData componentData, NodeTypeEnum type) { // As agreed with Ella, update categories - delete old and create new StorageOperationStatus status = StorageOperationStatus.OK; List<CategoryDefinition> newcategories = component.getCategories(); List<CategoryDefinition> currentcategories = currentComponent.getCategories(); if (newcategories != null) { if (currentcategories != null && !currentcategories.isEmpty()) { - Either<List<GroupingData>, StorageOperationStatus> findGroupingsForComponent = findGroupingsForComponent( - NodeTypeEnum.ProductGrouping, currentComponent); + Either<List<GroupingData>, StorageOperationStatus> findGroupingsForComponent = findGroupingsForComponent(NodeTypeEnum.ProductGrouping, currentComponent); if (findGroupingsForComponent.isRight()) { status = findGroupingsForComponent.right().value(); } List<GroupingData> groupingDataToDissociate = findGroupingsForComponent.left().value(); - TitanOperationStatus titanStatus = dissociateCategoriesFromProduct((ProductMetadataData) componentData, - groupingDataToDissociate); + TitanOperationStatus titanStatus = dissociateCategoriesFromProduct((ProductMetadataData) componentData, groupingDataToDissociate); if (titanStatus != TitanOperationStatus.OK) { status = DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus); } } if (!newcategories.isEmpty()) { - Either<List<GroupingData>, StorageOperationStatus> findGroupingsForComponent = findGroupingsForComponent( - NodeTypeEnum.ProductGrouping, component); + Either<List<GroupingData>, StorageOperationStatus> findGroupingsForComponent = findGroupingsForComponent(NodeTypeEnum.ProductGrouping, component); if (findGroupingsForComponent.isRight()) { status = findGroupingsForComponent.right().value(); } List<GroupingData> groupingDataToAssociate = findGroupingsForComponent.left().value(); - TitanOperationStatus titanStatus = associateCategoriesToProduct((ProductMetadataData) componentData, - groupingDataToAssociate); + TitanOperationStatus titanStatus = associateCategoriesToProduct((ProductMetadataData) componentData, groupingDataToAssociate); if (titanStatus != TitanOperationStatus.OK) { status = DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus); } @@ -987,11 +886,10 @@ public class ProductOperation extends ComponentOperation implements IProductOper return status; } + @Override @SuppressWarnings("unchecked") - public Either<List<Product>, StorageOperationStatus> getFollowed(String userId, - Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, boolean inTransaction) { - return (Either<List<Product>, StorageOperationStatus>) (Either<?, StorageOperationStatus>) getFollowedComponent( - userId, lifecycleStates, lastStateStates, inTransaction, titanGenericDao, NodeTypeEnum.Product); + public Either<List<Product>, StorageOperationStatus> getFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, boolean inTransaction) { + return (Either<List<Product>, StorageOperationStatus>) (Either<?, StorageOperationStatus>) getFollowedComponent(userId, lifecycleStates, lastStateStates, inTransaction, titanGenericDao, NodeTypeEnum.Product); } @Override @@ -1011,11 +909,9 @@ public class ProductOperation extends ComponentOperation implements IProductOper @SuppressWarnings("unchecked") @Override - public Either<Component, StorageOperationStatus> markComponentToDelete(Component componentToDelete, - boolean inTransaction) { + public Either<Component, StorageOperationStatus> markComponentToDelete(Component componentToDelete, boolean inTransaction) { // markComponentToDelete is not defined yet for products - return (Either<Component, StorageOperationStatus>) (Either<?, StorageOperationStatus>) deleteProduct( - componentToDelete.getUniqueId(), inTransaction); + return (Either<Component, StorageOperationStatus>) (Either<?, StorageOperationStatus>) deleteProduct(componentToDelete.getUniqueId(), inTransaction); } @Override @@ -1040,28 +936,22 @@ public class ProductOperation extends ComponentOperation implements IProductOper return Either.left(new ArrayList<>()); } - public Either<Product, StorageOperationStatus> getProductByNameAndVersion(String productName, String productVersion, - boolean inTransaction) { - return getByNamesAndVersion(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), - ValidationUtils.normaliseComponentName(productName), productVersion, null, inTransaction); + public Either<Product, StorageOperationStatus> getProductByNameAndVersion(String productName, String productVersion, boolean inTransaction) { + return getByNamesAndVersion(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), ValidationUtils.normaliseComponentName(productName), productVersion, null, inTransaction); } @SuppressWarnings("unchecked") @Override - public <T> Either<T, StorageOperationStatus> getComponent(String id, - ComponentParametersView componentParametersView, boolean inTransaction) { + public <T> Either<T, StorageOperationStatus> getComponent(String id, ComponentParametersView componentParametersView, boolean inTransaction) { return (Either<T, StorageOperationStatus>) getProduct(id, false); } - public Either<Product, StorageOperationStatus> updateProduct(Product product, boolean inTransaction, - ComponentParametersView filterResultView) { - return (Either<Product, StorageOperationStatus>) updateComponentFilterResult(product, inTransaction, - titanGenericDao, product.getClass(), NodeTypeEnum.Service, filterResultView); + public Either<Product, StorageOperationStatus> updateProduct(Product product, boolean inTransaction, ComponentParametersView filterResultView) { + return (Either<Product, StorageOperationStatus>) updateComponentFilterResult(product, inTransaction, titanGenericDao, product.getClass(), NodeTypeEnum.Service, filterResultView); } @Override - protected <T> Either<T, StorageOperationStatus> updateComponentFilterResult(T component, boolean inTransaction, - ComponentParametersView filterResultView) { + protected <T> Either<T, StorageOperationStatus> updateComponentFilterResult(T component, boolean inTransaction, ComponentParametersView filterResultView) { return (Either<T, StorageOperationStatus>) updateProduct((Product) component, inTransaction, filterResultView); } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperation.java index 7d775b3b3d..9b900b0ae2 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PropertyOperation.java @@ -32,14 +32,11 @@ import java.util.Map.Entry; import java.util.Set; import java.util.StringJoiner; import java.util.function.Consumer; -import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; -import com.thinkaurelius.titan.core.TitanTransaction; -import com.thinkaurelius.titan.core.TitanVertex; - +import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.tinkerpop.gremlin.structure.Edge; import org.codehaus.jackson.JsonNode; @@ -60,7 +57,6 @@ import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyRule; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.model.ComponentInstanceInput; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.IComplexDefaultValue; @@ -69,7 +65,6 @@ import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.operations.api.IPropertyOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; -import org.openecomp.sdc.be.model.tosca.ToscaType; import org.openecomp.sdc.be.model.tosca.constraints.ConstraintType; import org.openecomp.sdc.be.model.tosca.constraints.GreaterOrEqualConstraint; import org.openecomp.sdc.be.model.tosca.constraints.GreaterThanConstraint; @@ -79,22 +74,18 @@ import org.openecomp.sdc.be.model.tosca.constraints.LessThanConstraint; import org.openecomp.sdc.be.model.tosca.constraints.MinLengthConstraint; import org.openecomp.sdc.be.model.tosca.constraints.ValidValuesConstraint; import org.openecomp.sdc.be.model.tosca.converters.PropertyValueConverter; -import org.openecomp.sdc.be.model.tosca.validators.DataTypeValidatorConverter; import org.openecomp.sdc.be.model.tosca.validators.PropertyTypeValidator; import org.openecomp.sdc.be.resources.data.ComponentInstanceData; import org.openecomp.sdc.be.resources.data.DataTypeData; -import org.openecomp.sdc.be.resources.data.InputValueData; import org.openecomp.sdc.be.resources.data.PropertyData; import org.openecomp.sdc.be.resources.data.PropertyValueData; import org.openecomp.sdc.be.resources.data.ResourceMetadataData; import org.openecomp.sdc.be.resources.data.UniqueIdData; -import org.openecomp.sdc.common.api.Constants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; @@ -104,13 +95,15 @@ import com.google.gson.JsonParseException; import com.google.gson.JsonParser; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; -import com.google.gson.reflect.TypeToken; +import com.thinkaurelius.titan.core.TitanVertex; import fj.data.Either; @Component("property-operation") public class PropertyOperation extends AbstractOperation implements IPropertyOperation { + private TitanGenericDao titanGenericDao; + public static void main(String[] args) { List<Pattern> buildFunctionPatterns = buildFunctionPatterns(); @@ -126,10 +119,9 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe } - public static final String PROPERTY = "property"; - - public PropertyOperation() { + public PropertyOperation(@Qualifier("titan-generic-dao") TitanGenericDao titanGenericDao) { super(); + this.titanGenericDao = titanGenericDao; } private static Logger log = LoggerFactory.getLogger(PropertyOperation.class.getName()); @@ -165,7 +157,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe @Override public Either<PropertyDefinition, StorageOperationStatus> getPropertyOfResource(String propertyName, String resourceId) { - String propertyId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, propertyName); + String propertyId = UniqueIdBuilder.buildComponentPropertyUniqueId(resourceId, propertyName); Either<PropertyData, TitanOperationStatus> getResult = this.titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), propertyId, PropertyData.class); if (getResult.isLeft()) { @@ -173,7 +165,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe return Either.left(convertPropertyDataToPropertyDefinition(propertyData, propertyName, resourceId)); } else { TitanOperationStatus titanStatus = getResult.right().value(); - log.debug("Node with id {} was not found in the graph. Status: {}", propertyId, titanStatus); + log.debug("Node with id {} was not found in the graph. status: {}", propertyId, titanStatus); StorageOperationStatus storageOperationStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus); return Either.right(storageOperationStatus); } @@ -192,10 +184,12 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe * * Either<PropertyData, TitanOperationStatus> status = addPropertyToGraph(propertyName, propertyDefinition, resourceId); * - * if (status.isRight()) { titanGenericDao.rollback(); log.error("Failed to add property " + propertyName + " to resource " + resourceId); return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status. right().value())); } else + * if (status.isRight()) { titanGenericDao.rollback(); + * log.error("Failed to add property {} to resource {}, propertyName, resourceId); + * return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status. right().value())); } else * { titanGenericDao.commit(); PropertyData propertyData = status.left().value(); * - * PropertyDefinition propertyDefResult = convertPropertyDataToPropertyDefinition(propertyData, propertyName, resourceId); log.debug("The returned PropertyDefintion is {}", propertyDefinition); return Either.left(propertyDefResult); } + * PropertyDefinition propertyDefResult = convertPropertyDataToPropertyDefinition(propertyData, propertyName, resourceId); log.debug("The returned PropertyDefintion is " + propertyDefinition); return Either.left(propertyDefResult); } * * * } @@ -244,7 +238,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe PropertyDefinition propertyDefResult = new PropertyDefinition(propertyDataResult.getPropertyDataDefinition()); propertyDefResult.setConstraints(convertConstraints(propertyDataResult.getConstraints())); propertyDefResult.setName(propertyName); - propertyDefResult.setParentUniqueId(resourceId); +// propertyDefResult.setParentUniqueId(resourceId); return propertyDefResult; } @@ -545,7 +539,9 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe * * ImmutablePair<JsonElement, Boolean> validateResult = dataTypeValidatorConverter.validateAndUpdate(value, dataTypeDefinition, allDataTypes); * - * if (validateResult.right.booleanValue() == false) { log.debug("The value {} of property from type {} is invalid", value, propertyType); return Either.right(false); } + * if (validateResult.right.booleanValue() == false) { + * log.debug("The value {} of property from type {} is invalid", value, propertyType); + * return Either.right(false); } * * JsonElement jsonElement = validateResult.left; * @@ -555,9 +551,9 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe * * } * - * log.trace("After validating property type " + propertyType); + * log.trace("After validating property type {}", propertyType); * - * boolean isValidProperty = isValidValue(type, value, innerType); if (false == isValidProperty) { log.debug("The value {} of property from type {} is invalid", value, type); return Either.right(false); } + * boolean isValidProperty = isValidValue(type, value, innerType); if (false == isValidProperty) { log.debug("The value " + value + " of property from type " + type + " is invalid"); return Either.right(false); } * * * Object convertedValue = value; if (false == isEmptyValue(value)) { PropertyValueConverter converter = type.getConverter(); convertedValue = converter.convert(value, null); } @@ -572,7 +568,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe List<PropertyConstraint> constraints = propertyDefinition.getConstraints(); - propertyDefinition.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, propertyName)); + propertyDefinition.setUniqueId(UniqueIdBuilder.buildComponentPropertyUniqueId(resourceId, propertyName)); PropertyData propertyData = new PropertyData(propertyDefinition, convertConstraintsToString(constraints)); log.debug("Before adding property to graph {}", propertyData); @@ -580,7 +576,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe log.debug("After adding property to graph {}", propertyData); if (createNodeResult.isRight()) { TitanOperationStatus operationStatus = createNodeResult.right().value(); - log.error("Failed to add property {} to graph. Status is {}", propertyName, operationStatus); + log.error("Failed to add property {} to graph. status is {}", propertyName, operationStatus); return Either.right(operationStatus); } @@ -589,7 +585,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(resourceData, propertyData, GraphEdgeLabels.PROPERTY, props); if (createRelResult.isRight()) { TitanOperationStatus operationStatus = createNodeResult.right().value(); - log.error("Failed to associate resource {} to property {} in graph. Status is {}", resourceId, propertyName, operationStatus); + log.error("Failed to associate resource {} to property {} in graph. status is {}", resourceId, propertyName, operationStatus); return Either.right(operationStatus); } @@ -601,7 +597,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe List<PropertyConstraint> constraints = propertyDefinition.getConstraints(); - propertyDefinition.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, propertyName)); + propertyDefinition.setUniqueId(UniqueIdBuilder.buildComponentPropertyUniqueId(resourceId, propertyName)); PropertyData propertyData = new PropertyData(propertyDefinition, convertConstraintsToString(constraints)); log.debug("Before adding property to graph {}", propertyData); @@ -609,7 +605,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe log.debug("After adding property to graph {}", propertyData); if (createNodeResult.isRight()) { TitanOperationStatus operationStatus = createNodeResult.right().value(); - log.error("Failed to add property {} to graph. status is {}", propertyName, operationStatus); + log.error("Failed to add property {} to graph. status is ", propertyName, operationStatus); return operationStatus; } @@ -731,7 +727,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe log.debug("After adding property to graph {}", propertyData); if (createNodeResult.isRight()) { TitanOperationStatus operationStatus = createNodeResult.right().value(); - log.error("Failed to add property {} to graph. Status is {}", propertyName, operationStatus); + log.error("Failed to add property {} to graph. status is {}", propertyName, operationStatus); return Either.right(operationStatus); } @@ -739,11 +735,11 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe props.put(GraphPropertiesDictionary.NAME.getProperty(), propertyName); UniqueIdData uniqueIdData = new UniqueIdData(nodeType, uniqueId); - log.debug("Before associating {} to property {}.", uniqueIdData, propertyName); + log.debug("Before associating {} to property {}", uniqueIdData, propertyName); Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(uniqueIdData, propertyData, GraphEdgeLabels.PROPERTY, props); if (createRelResult.isRight()) { TitanOperationStatus operationStatus = createNodeResult.right().value(); - log.error("Failed to associate resource {} to property {} in graph. Status is {}", uniqueId, propertyName, operationStatus); + log.error("Failed to associate resource {} to property {} in graph. status is {}", uniqueId, propertyName, operationStatus); return Either.right(operationStatus); } @@ -830,7 +826,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe String propertyUid = propertyDefinition.getUniqueId(); Either<PropertyData, TitanOperationStatus> deletePropertyRes = deletePropertyFromGraph(propertyUid); if (deletePropertyRes.isRight()) { - log.error("Failed to delete property with id " + propertyUid); + log.error("Failed to delete property with id {}", propertyUid); TitanOperationStatus status = deletePropertyRes.right().value(); if (status == TitanOperationStatus.NOT_FOUND) { status = TitanOperationStatus.INVALID_ID; @@ -887,8 +883,10 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe log.debug("Property {} is associated to node {}", propertyName, uniqueId); PropertyData propertyData = immutablePair.getKey(); PropertyDefinition propertyDefinition = this.convertPropertyDataToPropertyDefinition(propertyData, propertyName, uniqueId); - - properties.add(propertyDefinition); + //Adds parent property to List if it hasn't been overrided in one of the children + if(!properties.stream().filter(p -> p.getName().equals(propertyDefinition.getName())).findAny().isPresent()){ + properties.add(propertyDefinition); + } if (log.isTraceEnabled()) log.trace("findPropertiesOfNode - property {} associated to node {}", propertyDefinition, uniqueId); @@ -898,24 +896,28 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe return TitanOperationStatus.OK; } - - public boolean isPropertyExist(List<PropertyDefinition> properties, String resourceUid, String propertyName) { - - if (properties == null) { - return false; - } - - for (PropertyDefinition propertyDefinition : properties) { - String parentUniqueId = propertyDefinition.getParentUniqueId(); - String name = propertyDefinition.getName(); - - if (parentUniqueId.equals(resourceUid) && name.equals(propertyName)) { - return true; +/** + * Checks existence of a property with the same name belonging to the same resource + * or existence of property with the same name and different type (including derived from hierarchy) + * @param properties + * @param resourceUid + * @param propertyName + * @param propertyType + * @return + */ + public boolean isPropertyExist(List<PropertyDefinition> properties, String resourceUid, String propertyName, String propertyType) { + boolean result = false; + if (!CollectionUtils.isEmpty(properties)) { + for (PropertyDefinition propertyDefinition : properties) { + + if ( propertyDefinition.getName().equals(propertyName) && + (propertyDefinition.getParentUniqueId().equals(resourceUid) || !propertyDefinition.getType().equals(propertyType)) ) { + result = true; + break; + } } } - - return false; - + return result; } /** @@ -947,7 +949,9 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe * "Failed to update property value on instance. Status is " + updatePropertyOfResourceInstance.right().value(), ErrorSeverity.ERROR); return Either.right(updatePropertyOfResourceInstance.right().value()); } return * Either.left(updatePropertyOfResourceInstance.left().value()); } * - * if (isPropertyValueExists.getLeft() != TitanOperationStatus.NOT_FOUND) { log.debug("After finding property value of {} on component instance {}", propertyId, resourceInstanceId); return Either.right(isPropertyValueExists.getLeft()); } + * if (isPropertyValueExists.getLeft() != TitanOperationStatus.NOT_FOUND) { + * log.debug("After finding property value of {} on componenet instance {}", propertyId, resourceInstanceId); + * return Either.right(isPropertyValueExists.getLeft()); } * * String propertyType = propertyData.getPropertyDataDefinition().getType(); String value = resourceInstanceProperty.getValue(); Either<Object, Boolean> isValid = validateAndUpdatePropertyValue(propertyType, value); * @@ -961,7 +965,8 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe * logBeInvalidValueError("Add property value", pair.getLeft(), resourceInstanceProperty.getName(), propertyType); return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); } addRulesToNewPropertyValue(propertyValueData, * resourceInstanceProperty, resourceInstanceId); * - * log.debug("Before adding property value to graph {}", propertyValueData); Either<PropertyValueData, TitanOperationStatus> createNodeResult = titanGenericDao .createNode(propertyValueData, PropertyValueData.class); + * log.debug("Before adding property value to graph {}", propertyValueData); + * Either<PropertyValueData, TitanOperationStatus> createNodeResult = titanGenericDao .createNode(propertyValueData, PropertyValueData.class); * log.debug("After adding property value to graph {}", propertyValueData); * * Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao .createRelation(propertyValueData, propertyData, GraphEdgeLabels.PROPERTY_IMPL, null); @@ -1108,7 +1113,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe * Either<Object, Boolean> isValid = validateAndUpdatePropertyValue(propertyType, value); * * String newValue = value; if (isValid.isRight()) { Boolean res = isValid.right().value(); if (res == false) { return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); } } else { Object object = isValid.left().value(); if (object != null) { - * newValue = object.toString(); } } PropertyValueData propertyValueData = findPropertyValueRes.left().value(); log.debug("Going to update property value from {} to {}", propertyValueData.getValue(), newValue); + * newValue = object.toString(); } } PropertyValueData propertyValueData = findPropertyValueRes.left().value(); log.debug("Going to update property value from " + propertyValueData.getValue() + " to " + newValue); * propertyValueData.setValue(newValue); * * ImmutablePair<String, Boolean> pair = validateAndUpdateRules(propertyType, resourceInstanceProperty.getRules()); if (pair.getRight() != null && pair.getRight() == false) { BeEcompErrorManager.getInstance(). @@ -1220,7 +1225,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe * * ComponentInstanceProperty propertyValueResult = buildResourceInstanceProperty( propertyValueData, resourceInstanceProperty); * - * log.debug("The returned ResourceInstanceProperty is {}", propertyValueResult); result = Either.left(propertyValueResult); return result; } } + * log.debug("The returned ResourceInstanceProperty is {}", propertyValueResult); result = Either.left(propertyValueResult); return result; } } * * finally { if (false == inTransaction) { if (result == null || result.isRight()) { log.error("Going to execute rollback on graph."); titanGenericDao.rollback(); } else { log.debug("Going to execute commit on graph."); titanGenericDao.commit(); * } } } @@ -1238,7 +1243,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe * * ComponentInstanceProperty propertyValueResult = buildResourceInstanceProperty( propertyValueData, resourceInstanceProperty); * - * log.debug("The returned ResourceInstanceProperty is {}", propertyValueResult); result = Either.left(propertyValueResult); return result; } } + * log.debug("The returned ResourceInstanceProperty is {}", propertyValueResult); result = Either.left(propertyValueResult); return result; } } * * finally { if (false == inTransaction) { if (result == null || result.isRight()) { log.error("Going to execute rollback on graph."); titanGenericDao.rollback(); } else { log.debug("Going to execute commit on graph."); titanGenericDao.commit(); * } } } @@ -1306,7 +1311,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe propertyValueResult.setUniqueId(resourceInstanceId); propertyValueResult.setValue(propertyValueData.getValue()); - log.debug("The returned ResourceInstanceProperty is {}", propertyValueResult); + log.debug("The returned ResourceInstanceProperty is {}", propertyValueResult); result = Either.left(propertyValueResult); return result; } @@ -1425,7 +1430,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe if (innerToscaType == null) { DataTypeDefinition dataTypeDefinition = dataTypes.get(innerType); if (dataTypeDefinition == null) { - log.debug("The inner type {} is not a data type", innerType); + log.debug("The inner type {} is not a data type.", innerType); return new ImmutablePair<String, Boolean>(innerType, false); } else { log.debug("The inner type {} is a data type. Data type definition is {}", innerType, dataTypeDefinition); @@ -1438,7 +1443,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe private boolean isValidComplexValue(DataTypeDefinition foundDt, String value, Map<String, DataTypeDefinition> dataTypes) { /* * Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypesRes = getAllDataTypes(); if (allDataTypesRes.isRight()) { TitanOperationStatus status = allDataTypesRes.right().value(); - * log.debug("Failed to fetch data types from graph. Status is {}", status); return false; } + * return false; } * * Map<String, DataTypeDefinition> allDataTypes = allDataTypesRes.left().value(); */ @@ -1483,10 +1488,6 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe public Either<List<ComponentInstanceProperty>, TitanOperationStatus> getAllPropertiesOfResourceInstanceOnlyPropertyDefId(String resourceInstanceUid, NodeTypeEnum instanceNodeType) { - // Either<ComponentInstanceData, TitanOperationStatus> - // findResInstanceRes = - // titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(instanceNodeType), - // resourceInstanceUid, ComponentInstanceData.class); Either<TitanVertex, TitanOperationStatus> findResInstanceRes = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(instanceNodeType), resourceInstanceUid); if (findResInstanceRes.isRight()) { @@ -1497,11 +1498,6 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe return Either.right(status); } - // Either<List<ImmutablePair<PropertyValueData, GraphEdge>>, - // TitanOperationStatus> propertyImplNodes = - // titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(instanceNodeType), - // resourceInstanceUid, GraphEdgeLabels.PROPERTY_VALUE, - // NodeTypeEnum.PropertyValue, PropertyValueData.class); Either<List<ImmutablePair<TitanVertex, Edge>>, TitanOperationStatus> propertyImplNodes = titanGenericDao.getChildrenVertecies(UniqueIdBuilder.getKeyByNodeType(instanceNodeType), resourceInstanceUid, GraphEdgeLabels.PROPERTY_VALUE); if (propertyImplNodes.isRight()) { @@ -1558,7 +1554,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe */ public Either<String, TitanOperationStatus> findDefaultValueFromSecondPosition(List<String> pathOfComponentInstances, String propertyUniqueId, String defaultValue) { - log.trace("In find default value: path=" + pathOfComponentInstances + "propertyUniqId=" + propertyUniqueId + "defaultValue=" + defaultValue); + log.trace("In find default value: path= {} propertyUniqId={} defaultValue= {}", pathOfComponentInstances, propertyUniqueId, defaultValue); if (pathOfComponentInstances == null || pathOfComponentInstances.size() < 2) { return Either.left(defaultValue); @@ -1583,7 +1579,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe } ComponentInstanceProperty foundCompInstanceProperty = fetchByPropertyUid(propertyValuesResult.left().value(), propertyUniqueId); - log.trace("After finding the component instance property on {}. {}", compInstanceId, foundCompInstanceProperty); + log.trace("After finding the component instance property on{} . {}", compInstanceId, foundCompInstanceProperty); if (foundCompInstanceProperty == null) { continue; @@ -1695,7 +1691,9 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe Matcher matcher = pattern.matcher(stringForMatch); if (matcher.matches()) { - log.trace("{} matches the rule {}", stringForMatch, patternStr); + if (log.isTraceEnabled()) { + log.trace("{} matches the rule {}", stringForMatch, patternStr); + } propertyRule = rule; break; } @@ -1752,14 +1750,14 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe if (numberOfMatches == 1) { instanceProperty.setValue(value); if (log.isDebugEnabled()) { - log.debug("Set the value of property " + propertyUniqueId + " " + instanceProperty.getName() + " on path " + pathOfInstances + " to be " + value); + log.debug("Set the value of property {} {} on path {} to be {}", propertyUniqueId, instanceProperty.getName(), pathOfInstances, value); } } else if (numberOfMatches == 2) { // In case of another property value match, then use the // value to be the default value of the property. instanceProperty.setDefaultValue(value); if (log.isDebugEnabled()) { - log.debug("Set the default value of property " + propertyUniqueId + " " + instanceProperty.getName() + " on path " + pathOfInstances + " to be " + value); + log.debug("Set the default value of property {} {} on path {} to be {}", propertyUniqueId, instanceProperty.getName(), pathOfInstances, value); } break; } @@ -1820,19 +1818,19 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe */ private Either<DataTypeData, TitanOperationStatus> addDataTypeToGraph(DataTypeDefinition dataTypeDefinition) { - log.debug("Got data type " + dataTypeDefinition); + log.debug("Got data type {}", dataTypeDefinition); String dtUniqueId = UniqueIdBuilder.buildDataTypeUid(dataTypeDefinition.getName()); DataTypeData dataTypeData = buildDataTypeData(dataTypeDefinition, dtUniqueId); - log.debug("Before adding data type to graph. dataTypeData = " + dataTypeData); + log.debug("Before adding data type to graph. dataTypeData = {}", dataTypeData); Either<DataTypeData, TitanOperationStatus> createDataTypeResult = titanGenericDao.createNode(dataTypeData, DataTypeData.class); log.debug("After adding data type to graph. status is = {}", createDataTypeResult); if (createDataTypeResult.isRight()) { TitanOperationStatus operationStatus = createDataTypeResult.right().value(); - log.debug("Failed to data type " + dataTypeDefinition.getName() + " to graph. status is " + operationStatus); + log.debug("Failed to data type {} to graph. status is {}", dataTypeDefinition.getName(), operationStatus); BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError("AddDataType", NodeTypeEnum.DataType.getName()); return Either.right(operationStatus); } @@ -1841,19 +1839,19 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe List<PropertyDefinition> properties = dataTypeDefinition.getProperties(); Either<Map<String, PropertyData>, TitanOperationStatus> addPropertiesToDataType = addPropertiesToDataType(resultCTD.getUniqueId(), properties); if (addPropertiesToDataType.isRight()) { - log.debug("Failed add properties " + properties + " to data type " + dataTypeDefinition.getName()); + log.debug("Failed add properties {} to data type {}", properties, dataTypeDefinition.getName()); return Either.right(addPropertiesToDataType.right().value()); } String derivedFrom = dataTypeDefinition.getDerivedFromName(); if (derivedFrom != null) { - log.debug("Before creating relation between data type " + dtUniqueId + " to its parent " + derivedFrom); + log.debug("Before creating relation between data type {} to its parent {}", dtUniqueId, derivedFrom); UniqueIdData from = new UniqueIdData(NodeTypeEnum.DataType, dtUniqueId); String deriveFromUid = UniqueIdBuilder.buildDataTypeUid(derivedFrom); UniqueIdData to = new UniqueIdData(NodeTypeEnum.DataType, deriveFromUid); Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(from, to, GraphEdgeLabels.DERIVED_FROM, null); - log.debug("After create relation between capability type " + dtUniqueId + " to its parent " + derivedFrom + ". status is " + createRelation); + log.debug("After create relation between capability type {} to its parent {}. status is {}", dtUniqueId, derivedFrom, createRelation); if (createRelation.isRight()) { return Either.right(createRelation.right().value()); } @@ -1898,19 +1896,19 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe String propertyType = propertyDefinition.getType(); Either<Boolean, TitanOperationStatus> validPropertyType = isValidPropertyType(propertyType); if (validPropertyType.isRight()) { - log.debug("Data type " + uniqueId + " contains invalid property type " + propertyType); + log.debug("Data type {} contains invalid property type {}", uniqueId, propertyType); return Either.right(validPropertyType.right().value()); } Boolean isValid = validPropertyType.left().value(); if (isValid == null || isValid.booleanValue() == false) { - log.debug("Data type " + uniqueId + " contains invalid property type " + propertyType); + log.debug("Data type {} contains invalid property type {}", uniqueId, propertyType); return Either.right(TitanOperationStatus.INVALID_TYPE); } Either<PropertyData, TitanOperationStatus> addPropertyToNodeType = this.addPropertyToNodeType(propertyName, propertyDefinition, NodeTypeEnum.DataType, uniqueId); if (addPropertyToNodeType.isRight()) { TitanOperationStatus operationStatus = addPropertyToNodeType.right().value(); - log.debug("Failed to associate data type " + uniqueId + " to property " + propertyName + " in graph. status is " + operationStatus); + log.debug("Failed to associate data type {} to property {} in graph. status is {}", uniqueId, propertyName, operationStatus); BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToDataType", "Failed to associate property to data type. Status is " + operationStatus, ErrorSeverity.ERROR); return Either.right(operationStatus); } @@ -1925,7 +1923,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe Either<DataTypeData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(dataTypeData, DataTypeData.class); if (updateNode.isRight()) { TitanOperationStatus operationStatus = updateNode.right().value(); - log.debug("Failed to update modification time data type " + uniqueId + " from graph. status is " + operationStatus); + log.debug("Failed to update modification time data type {} from graph. status is {}", uniqueId, operationStatus); BeEcompErrorManager.getInstance().logInternalFlowError("AddPropertyToDataType", "Failed to fetch data type. Status is " + operationStatus, ErrorSeverity.ERROR); return Either.right(operationStatus); } else { @@ -1952,7 +1950,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe if (dataTypesRes.isRight()) { TitanOperationStatus status = dataTypesRes.right().value(); - log.debug("Data type " + uniqueId + " cannot be found in graph. status is " + status); + log.debug("Data type {} cannot be found in graph. status is {}", uniqueId, status); return Either.right(status); } @@ -1961,17 +1959,17 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe TitanOperationStatus propertiesStatus = fillProperties(uniqueId, dataTypeDefinition); if (propertiesStatus != TitanOperationStatus.OK) { - log.error("Failed to fetch properties of data type " + uniqueId); + log.error("Failed to fetch properties of data type {}", uniqueId); return Either.right(propertiesStatus); } Either<ImmutablePair<DataTypeData, GraphEdge>, TitanOperationStatus> parentNode = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), uniqueId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.DataType, DataTypeData.class); - log.debug("After retrieving DERIVED_FROM node of " + uniqueId + ". status is " + parentNode); + log.debug("After retrieving DERIVED_FROM node of {}. status is {}", uniqueId, parentNode); if (parentNode.isRight()) { TitanOperationStatus titanOperationStatus = parentNode.right().value(); if (titanOperationStatus != TitanOperationStatus.NOT_FOUND) { - log.error("Failed to find the parent data type of data type " + uniqueId + ". status is " + titanOperationStatus); + log.error("Failed to find the parent data type of data type {}. status is {}", uniqueId, titanOperationStatus); result = Either.right(titanOperationStatus); return result; } @@ -2002,7 +2000,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe Either<Map<String, PropertyDefinition>, TitanOperationStatus> findPropertiesOfNode = this.findPropertiesOfNode(NodeTypeEnum.DataType, uniqueId); if (findPropertiesOfNode.isRight()) { TitanOperationStatus titanOperationStatus = findPropertiesOfNode.right().value(); - log.debug("After looking for properties of vertex " + uniqueId + ". status is " + titanOperationStatus); + log.debug("After looking for properties of vertex {}. status is {}", uniqueId, titanOperationStatus); if (TitanOperationStatus.NOT_FOUND.equals(titanOperationStatus)) { return TitanOperationStatus.OK; } else { @@ -2044,7 +2042,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe DataTypeData capabilityTypeData = eitherStatus.left().value(); DataTypeDefinition dataTypeDefResult = convertDTDataToDTDefinition(capabilityTypeData); - log.debug("The returned CapabilityTypeDefinition is " + dataTypeDefResult); + log.debug("The returned CapabilityTypeDefinition is {}", dataTypeDefResult); result = Either.left(dataTypeDefResult); return result; } @@ -2079,7 +2077,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe if (ctResult.isRight()) { TitanOperationStatus status = ctResult.right().value(); if (status != TitanOperationStatus.NOT_FOUND) { - log.error("Failed to retrieve information on capability type " + name + "status is " + status); + log.error("Failed to retrieve information on capability type {} status is {}", name, status); } result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(ctResult.right().value())); return result; @@ -2124,7 +2122,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe if (ctResult.isRight()) { TitanOperationStatus status = ctResult.right().value(); if (status != TitanOperationStatus.NOT_FOUND) { - log.error("Failed to retrieve information on capability type " + name + "status is " + status); + log.error("Failed to retrieve information on capability type {} status is {}", name, status); } result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(ctResult.right().value())); return result; @@ -2153,7 +2151,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe if (dataTypesRes.isRight()) { TitanOperationStatus status = dataTypesRes.right().value(); - log.debug("Data type " + uniqueId + " cannot be found in graph. status is " + status); + log.debug("Data type {} cannot be found in graph. status is {}", uniqueId, status); return Either.right(status); } @@ -2162,7 +2160,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe TitanOperationStatus propertiesStatus = fillProperties(uniqueId, dataTypeDefinition); if (propertiesStatus != TitanOperationStatus.OK) { - log.error("Failed to fetch properties of data type " + uniqueId); + log.error("Failed to fetch properties of data type {}", uniqueId); return Either.right(propertiesStatus); } @@ -2184,7 +2182,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe * @return */ protected DataTypeDefinition convertDTDataToDTDefinition(DataTypeData dataTypeData) { - log.debug("The object returned after create data type is " + dataTypeData); + log.debug("The object returned after create data type is {}", dataTypeData); DataTypeDefinition dataTypeDefResult = new DataTypeDefinition(dataTypeData.getDataTypeDataDefinition()); @@ -2206,7 +2204,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe } } - private Either<Boolean, TitanOperationStatus> isDefinedInDataTypes(String propertyType) { + public Either<Boolean, TitanOperationStatus> isDefinedInDataTypes(String propertyType) { String dataTypeUid = UniqueIdBuilder.buildDataTypeUid(propertyType); Either<DataTypeDefinition, TitanOperationStatus> dataTypeByUid = getDataTypeByUid(dataTypeUid); @@ -2253,14 +2251,14 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe List<DataTypeData> list = getAllDataTypes.left().value(); if (list != null) { - log.trace("Number of data types to load is " + list.size()); + log.trace("Number of data types to load is {}" , list.size()); List<String> collect = list.stream().map(p -> p.getDataTypeDataDefinition().getName()).collect(Collectors.toList()); - log.trace("The data types to load are " + collect); + log.trace("The data types to load are {}" , collect); for (DataTypeData dataTypeData : list) { - log.trace("Going to fetch data type " + dataTypeData.getDataTypeDataDefinition().getName() + ". uid is " + dataTypeData.getUniqueId()); + log.trace("Going to fetch data type {}. uid is {}", dataTypeData.getDataTypeDataDefinition().getName(), dataTypeData.getUniqueId()); Either<DataTypeDefinition, TitanOperationStatus> dataTypeByUid = this.getAndAddDataTypeByUid(dataTypeData.getUniqueId(), dataTypes); if (dataTypeByUid.isRight()) { TitanOperationStatus status = dataTypeByUid.right().value(); @@ -2274,12 +2272,12 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe if (log.isTraceEnabled()) { if (result.isRight()) { - log.trace("After fetching all data types " + result); + log.trace("After fetching all data types {}" , result); } else { Map<String, DataTypeDefinition> map = result.left().value(); if (map != null) { String types = map.keySet().stream().collect(Collectors.joining(",", "[", "]")); - log.trace("After fetching all data types " + types); + log.trace("After fetching all data types {} " , types); } } } @@ -2305,7 +2303,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe if (dataTypesRes.isRight()) { TitanOperationStatus status = dataTypesRes.right().value(); - log.debug("Data type " + uniqueId + " cannot be found in graph. status is " + status); + log.debug("Data type {} cannot be found in graph. status is {}", uniqueId, status); return Either.right(status); } @@ -2314,7 +2312,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe TitanOperationStatus propertiesStatus = fillProperties(uniqueId, dataTypeDefinition); if (propertiesStatus != TitanOperationStatus.OK) { - log.error("Failed to fetch properties of data type " + uniqueId); + log.error("Failed to fetch properties of data type {}", uniqueId); return Either.right(propertiesStatus); } @@ -2331,11 +2329,11 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe Either<ImmutablePair<DataTypeData, GraphEdge>, TitanOperationStatus> parentNode = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.DataType), uniqueId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.DataType, DataTypeData.class); - log.debug("After retrieving DERIVED_FROM node of " + uniqueId + ". status is " + parentNode); + log.debug("After retrieving DERIVED_FROM node of {}. status is {}", uniqueId, parentNode); if (parentNode.isRight()) { TitanOperationStatus titanOperationStatus = parentNode.right().value(); if (titanOperationStatus != TitanOperationStatus.NOT_FOUND) { - log.error("Failed to find the parent data type of data type " + uniqueId + ". status is " + titanOperationStatus); + log.error("Failed to find the parent data type of data type {}. status is {}", uniqueId, titanOperationStatus); result = Either.right(titanOperationStatus); return result; } @@ -2436,7 +2434,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe Either<Map<String, PropertyDefinition>, TitanOperationStatus> findPropertiesOfNode = this.findPropertiesOfNode(NodeTypeEnum.GroupType, uniqueId); if (findPropertiesOfNode.isRight()) { TitanOperationStatus titanOperationStatus = findPropertiesOfNode.right().value(); - log.debug("After looking for properties of vertex " + uniqueId + ". status is " + titanOperationStatus); + log.debug("After looking for properties of vertex {}. status is {}", uniqueId, titanOperationStatus); if (TitanOperationStatus.NOT_FOUND.equals(titanOperationStatus)) { return TitanOperationStatus.OK; } else { @@ -2461,7 +2459,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe * * @param uniqueId * @param propertiesMap - * TODO + * * @return */ protected Either<Map<String, PropertyData>, TitanOperationStatus> addPropertiesToElementType(String uniqueId, NodeTypeEnum nodeType, Map<String, PropertyDefinition> propertiesMap) { @@ -2477,7 +2475,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe if (addPropertyToNodeType.isRight()) { TitanOperationStatus operationStatus = addPropertyToNodeType.right().value(); - log.error("Failed to associate " + nodeType.getName() + " " + uniqueId + " to property " + propertyName + " in graph. status is " + operationStatus); + log.error("Failed to associate {} {} to property {} in graph. status is {}", nodeType.getName(), uniqueId, propertyName, operationStatus); return Either.right(operationStatus); } propertiesData.put(propertyName, addPropertyToNodeType.left().value()); @@ -2556,14 +2554,14 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe List<PropertyDefinition> propertiesToAdd = new ArrayList<>(); if (isPropertyOmitted(newProperties, oldProperties, dataTypeName) || isPropertyTypeChanged(dataTypeName, newProperties, oldProperties, propertiesToAdd) || isDerivedFromNameChanged(dataTypeName, newDerivedFromName, oldDerivedFromName)) { - log.debug("The new data type " + dataTypeName + " is invalid."); + log.debug("The new data type {} is invalid.", dataTypeName); result = Either.right(StorageOperationStatus.CANNOT_UPDATE_EXISTING_ENTITY); return result; } if (propertiesToAdd == null || propertiesToAdd.isEmpty()) { - log.debug("No new properties has been defined in the new data type " + newDataTypeDefinition); + log.debug("No new properties has been defined in the new data type {}", newDataTypeDefinition); result = Either.right(StorageOperationStatus.OK); return result; } @@ -2606,15 +2604,6 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe private String getDerivedFromName(DataTypeDefinition dataTypeDefinition) { String derivedFromName = dataTypeDefinition.getDerivedFromName(); - // if (derivedFromName == null) { - // DataTypeDefinition derivedFrom = dataTypeDefinition.getDerivedFrom(); - // if (derivedFrom != null) { - // log.debug("Dervied from is taken from definition"); - // derivedFromName = derivedFrom.getName(); - // } - // } else { - // log.debug("Dervied from is taken from field derivedFromName"); - // } return derivedFromName; } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/RequirementOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/RequirementOperation.java index e8892ad333..a2fe3d61d3 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/RequirementOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/RequirementOperation.java @@ -95,10 +95,9 @@ public class RequirementOperation implements IRequirementOperation { } protected CapabilityTypeDefinition convertCTDataToCTDefinition(CapabilityTypeData capabilityTypeData) { - log.debug("The object returned after create capability is " + capabilityTypeData); + log.debug("The object returned after create capability is {}", capabilityTypeData); - CapabilityTypeDefinition capabilityTypeDefResult = new CapabilityTypeDefinition( - capabilityTypeData.getCapabilityTypeDataDefinition()); + CapabilityTypeDefinition capabilityTypeDefResult = new CapabilityTypeDefinition(capabilityTypeData.getCapabilityTypeDataDefinition()); return capabilityTypeDefResult; } @@ -117,14 +116,12 @@ public class RequirementOperation implements IRequirementOperation { } @Override - public Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource(String reqName, - RequirementDefinition reqDefinition, String resourceId) { + public Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource(String reqName, RequirementDefinition reqDefinition, String resourceId) { return addRequirementToResource(reqName, reqDefinition, resourceId, false); } - private Either<GraphRelation, TitanOperationStatus> associateRequirementToRelationshipType(RequirementData reqData, - RequirementDefinition reqDefinition) { + private Either<GraphRelation, TitanOperationStatus> associateRequirementToRelationshipType(RequirementData reqData, RequirementDefinition reqDefinition) { String relationship = reqDefinition.getRelationship(); @@ -133,8 +130,7 @@ public class RequirementOperation implements IRequirementOperation { return Either.right(TitanOperationStatus.NOT_FOUND); } UniqueIdData uniqueIdData = new UniqueIdData(NodeTypeEnum.RelationshipType, relationship); - Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(reqData, - uniqueIdData, GraphEdgeLabels.RELATIONSHIP_TYPE, null); + Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(reqData, uniqueIdData, GraphEdgeLabels.RELATIONSHIP_TYPE, null); return createRelation; @@ -147,32 +143,26 @@ public class RequirementOperation implements IRequirementOperation { * @param reqDefinition * @return */ - private Either<GraphRelation, TitanOperationStatus> associateRequirementToCapabilityType(RequirementData reqData, - RequirementDefinition reqDefinition) { + private Either<GraphRelation, TitanOperationStatus> associateRequirementToCapabilityType(RequirementData reqData, RequirementDefinition reqDefinition) { String capability = reqDefinition.getCapability(); UniqueIdData uniqueIdData = new UniqueIdData(NodeTypeEnum.CapabilityType, capability); - Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(reqData, - uniqueIdData, GraphEdgeLabels.CAPABILITY_TYPE, null); + Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(reqData, uniqueIdData, GraphEdgeLabels.CAPABILITY_TYPE, null); - log.debug("After associating requirementData " + reqData + " to capability " + capability + ". status is " - + createRelation); + log.debug("After associating requirementData {} to capability {}. status is {}", reqData, capability, createRelation); return createRelation; } - private TitanOperationStatus associateRequirementToCapabilityType(TitanVertex reqData, - RequirementDefinition reqDefinition) { + private TitanOperationStatus associateRequirementToCapabilityType(TitanVertex reqData, RequirementDefinition reqDefinition) { String capability = reqDefinition.getCapability(); UniqueIdData uniqueIdData = new UniqueIdData(NodeTypeEnum.CapabilityType, capability); - TitanOperationStatus createRelation = titanGenericDao.createEdge(reqData, uniqueIdData, - GraphEdgeLabels.CAPABILITY_TYPE, null); + TitanOperationStatus createRelation = titanGenericDao.createEdge(reqData, uniqueIdData, GraphEdgeLabels.CAPABILITY_TYPE, null); - log.debug("After associating requirementData {} to capability {}. status is {}" + reqData, capability, - createRelation); + log.debug("After associating requirementData {} to capability {}. status is {}", reqData, capability, createRelation); return createRelation; } @@ -185,18 +175,14 @@ public class RequirementOperation implements IRequirementOperation { * @param capabilityName * @return */ - private Either<GraphRelation, TitanOperationStatus> associateRequirementImplToCapabilityInst( - RequirementImplData reqImplData, CapabilityInstData capabilityInstData, String capabilityName) { + private Either<GraphRelation, TitanOperationStatus> associateRequirementImplToCapabilityInst(RequirementImplData reqImplData, CapabilityInstData capabilityInstData, String capabilityName) { Map<String, Object> props = new HashMap<String, Object>(); props.put(GraphPropertiesDictionary.NAME.getProperty(), capabilityName); - log.debug( - "Before associating requirement impl " + reqImplData + " to capability instance " + capabilityInstData); - Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(reqImplData, - capabilityInstData, GraphEdgeLabels.CAPABILITY_INST, props); - log.debug("After associating requirement impl " + reqImplData + " to capability instance " + capabilityInstData - + ".status is " + createRelation); + log.debug("Before associating requirement impl {} to capability instance {}", reqImplData, capabilityInstData); + Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(reqImplData, capabilityInstData, GraphEdgeLabels.CAPABILITY_INST, props); + log.debug("After associating requirement impl {} to capability instance {}.status is {}", reqImplData, capabilityInstData, createRelation); return createRelation; @@ -210,8 +196,7 @@ public class RequirementOperation implements IRequirementOperation { * @param reqDefinition * @return */ - private Either<RequirementData, TitanOperationStatus> addRequirementData(String resourceId, String reqName, - RequirementDefinition reqDefinition) { + private Either<RequirementData, TitanOperationStatus> addRequirementData(String resourceId, String reqName, RequirementDefinition reqDefinition) { ResourceMetadataData resourceData = new ResourceMetadataData(); resourceData.getMetadataDataDefinition().setUniqueId(resourceId); @@ -219,19 +204,16 @@ public class RequirementOperation implements IRequirementOperation { RequirementData requirementData = buildRequirementData(resourceId, reqName, reqDefinition); log.debug("Before adding requirement data to graph {}", requirementData); - Either<RequirementData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(requirementData, - RequirementData.class); + Either<RequirementData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(requirementData, RequirementData.class); log.debug("After adding requirement to graph {}", requirementData); if (createNodeResult.isRight()) { TitanOperationStatus operationStatus = createNodeResult.right().value(); - log.error("Failed to add requirement " + reqName + " [ " + requirementData + " ] " + " to graph. status is " - + operationStatus); + log.error("Failed to add requirement {} [{}] to graph. status is {}", reqName, requirementData, operationStatus); return Either.right(operationStatus); } - TitanOperationStatus status = associateResourceDataToRequirementData(resourceId, reqName, resourceData, - requirementData); + TitanOperationStatus status = associateResourceDataToRequirementData(resourceId, reqName, resourceData, requirementData); if (status != TitanOperationStatus.OK) { return Either.right(status); } @@ -240,8 +222,7 @@ public class RequirementOperation implements IRequirementOperation { } - private Either<TitanVertex, TitanOperationStatus> addRequirementData(TitanVertex vertex, String resourceId, - String reqName, RequirementDefinition reqDefinition) { + private Either<TitanVertex, TitanOperationStatus> addRequirementData(TitanVertex vertex, String resourceId, String reqName, RequirementDefinition reqDefinition) { RequirementData requirementData = buildRequirementData(resourceId, reqName, reqDefinition); @@ -251,13 +232,11 @@ public class RequirementOperation implements IRequirementOperation { log.debug("After adding requirement to graph {}", requirementData); if (createNodeResult.isRight()) { TitanOperationStatus operationStatus = createNodeResult.right().value(); - log.error("Failed to add requirement " + reqName + " [ " + requirementData + " ] " + " to graph. status is " - + operationStatus); + log.error("Failed to add requirement {} [{}] to graph. status is {}", reqName, requirementData, operationStatus); return Either.right(operationStatus); } - TitanOperationStatus status = associateResourceDataToRequirementData(resourceId, reqName, vertex, - createNodeResult.left().value()); + TitanOperationStatus status = associateResourceDataToRequirementData(resourceId, reqName, vertex, createNodeResult.left().value()); if (!status.equals(TitanOperationStatus.OK)) { return Either.right(status); } @@ -265,8 +244,7 @@ public class RequirementOperation implements IRequirementOperation { } /** - * Asssociate resource node to requirement node with REQUIREMENT label and - * requirement name as property on the edge. + * Asssociate resource node to requirement node with REQUIREMENT label and requirement name as property on the edge. * * @param resourceId * @param reqName @@ -274,39 +252,32 @@ public class RequirementOperation implements IRequirementOperation { * @param requirementData * @return */ - private TitanOperationStatus associateResourceDataToRequirementData(String resourceId, String reqName, - ResourceMetadataData resourceData, RequirementData requirementData) { + private TitanOperationStatus associateResourceDataToRequirementData(String resourceId, String reqName, ResourceMetadataData resourceData, RequirementData requirementData) { Map<String, Object> props = new HashMap<String, Object>(); props.put(GraphPropertiesDictionary.NAME.getProperty(), reqName); - Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(resourceData, - requirementData, GraphEdgeLabels.REQUIREMENT, props); - log.debug("After creatin edge between resource " + resourceId + " to requirement " + requirementData); + Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(resourceData, requirementData, GraphEdgeLabels.REQUIREMENT, props); + log.debug("After creatin edge between resource {} to requirement {}", resourceId, requirementData); if (createRelResult.isRight()) { TitanOperationStatus operationStatus = createRelResult.right().value(); - log.error("Failed to associate resource " + resourceId + " to requirement " + reqName + "[ " - + requirementData + "] in graph. status is " + operationStatus); + log.error("Failed to associate resource {} to requirement {} [ {} ] in graph. status is {}", resourceId, reqName, requirementData, operationStatus); } return TitanOperationStatus.OK; } - private TitanOperationStatus associateResourceDataToRequirementData(String resourceId, String reqName, - TitanVertex resourceVertex, TitanVertex requirementVertex) { + private TitanOperationStatus associateResourceDataToRequirementData(String resourceId, String reqName, TitanVertex resourceVertex, TitanVertex requirementVertex) { Map<String, Object> props = new HashMap<String, Object>(); props.put(GraphPropertiesDictionary.NAME.getProperty(), reqName); - TitanOperationStatus createRelResult = titanGenericDao.createEdge(resourceVertex, requirementVertex, - GraphEdgeLabels.REQUIREMENT, props); + TitanOperationStatus createRelResult = titanGenericDao.createEdge(resourceVertex, requirementVertex, GraphEdgeLabels.REQUIREMENT, props); log.debug("After creatin edge between resource {} to requirement {}", resourceId, requirementVertex); if (!createRelResult.equals(TitanOperationStatus.OK)) { - log.error("Failed to associate resource {} to requirement {} in graph. status is " + resourceId, reqName, - createRelResult); + log.error("Failed to associate resource {} to requirement {} in graph. status is {}", resourceId, reqName, createRelResult); } return TitanOperationStatus.OK; } - private RequirementData buildRequirementData(String resourceId, String reqName, - RequirementDefinition reqDefinition) { + private RequirementData buildRequirementData(String resourceId, String reqName, RequirementDefinition reqDefinition) { RequirementData requirementData = new RequirementData(); requirementData.setNode(reqDefinition.getNode()); @@ -322,8 +293,7 @@ public class RequirementOperation implements IRequirementOperation { } /** - * build requirement impl node associate it to resource, requirement & - * implementation resource + * build requirement impl node associate it to resource, requirement & implementation resource * * [RESOURCE] --> [REQUIREMENT IMPL] --> [ RESOURCE IMPL ] | V [REQUIREMENT] * @@ -334,47 +304,37 @@ public class RequirementOperation implements IRequirementOperation { * @param reqImplDefinition * @return */ - private Either<RequirementImplData, TitanOperationStatus> addRequirementImplData(NodeTypeEnum resourceLabel, - String resourceId, String reqName, String requirementUid, RequirementImplDef reqImplDefinition) { + private Either<RequirementImplData, TitanOperationStatus> addRequirementImplData(NodeTypeEnum resourceLabel, String resourceId, String reqName, String requirementUid, RequirementImplDef reqImplDefinition) { RequirementImplData requirementImplData = buildRequirementImplData(resourceId, reqName, reqImplDefinition); - log.debug("Before adding requirement impl data to graph " + requirementImplData); - Either<RequirementImplData, TitanOperationStatus> createNodeResult = titanGenericDao - .createNode(requirementImplData, RequirementImplData.class); - log.debug("After adding requirement to graph " + requirementImplData + ". status is " + createNodeResult); + log.debug("Before adding requirement impl data to graph {}", requirementImplData); + Either<RequirementImplData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(requirementImplData, RequirementImplData.class); + log.debug("After adding requirement to graph {}. status is {}", requirementImplData, createNodeResult); if (createNodeResult.isRight()) { TitanOperationStatus operationStatus = createNodeResult.right().value(); - log.error("Failed to add requirement " + reqName + " [ " + requirementImplData + " ] " - + " to graph. status is " + operationStatus); + log.error("Failed to add requirement {} [ {} ] to graph. status is {}", reqName, requirementImplData, operationStatus); return Either.right(operationStatus); } - Either<GraphRelation, TitanOperationStatus> createRelResult = associateReqImplRoResource(resourceLabel, - resourceId, reqName, requirementImplData); + Either<GraphRelation, TitanOperationStatus> createRelResult = associateReqImplRoResource(resourceLabel, resourceId, reqName, requirementImplData); if (createRelResult.isRight()) { TitanOperationStatus operationStatus = createRelResult.right().value(); - log.error("Failed to associate resource " + resourceId + " to requirement impl " + requirementImplData - + "[ " + requirementImplData + "] in graph. status is " + operationStatus); + log.error("Failed to associate resource {} to requirement impl {} [ {} ] in graph. status is {}", resourceId, requirementImplData, requirementImplData, operationStatus); return Either.right(operationStatus); } - Either<GraphRelation, TitanOperationStatus> associateToResourceImpl = associateReqImplToImplResource( - requirementImplData, reqImplDefinition.getNodeId()); + Either<GraphRelation, TitanOperationStatus> associateToResourceImpl = associateReqImplToImplResource(requirementImplData, reqImplDefinition.getNodeId()); if (associateToResourceImpl.isRight()) { TitanOperationStatus operationStatus = associateToResourceImpl.right().value(); - log.error("Failed to associate requirement impl " + requirementImplData + " to resource impl " - + reqImplDefinition.getNodeId() + "[ " + requirementImplData + "] in graph. status is " - + operationStatus); + log.error("Failed to associate requirement impl {} to resource impl {} [ {} ] in graph. status is {}", requirementImplData, reqImplDefinition.getNodeId(), requirementImplData, operationStatus); return Either.right(operationStatus); } - Either<GraphRelation, TitanOperationStatus> associateToRequirement = associateReqImplToRequirement( - requirementImplData, requirementUid); + Either<GraphRelation, TitanOperationStatus> associateToRequirement = associateReqImplToRequirement(requirementImplData, requirementUid); if (associateToRequirement.isRight()) { TitanOperationStatus operationStatus = associateToRequirement.right().value(); - log.error("Failed to associate requirement impl " + requirementImplData + " to requirement " + reqName - + " in graph. status is " + operationStatus); + log.error("Failed to associate requirement impl {} to requirement {} in graph. status is {}", requirementImplData, reqName, operationStatus); return Either.right(operationStatus); } @@ -382,8 +342,7 @@ public class RequirementOperation implements IRequirementOperation { } - private RequirementImplData buildRequirementImplData(String resourceId, String reqName, - RequirementImplDef reqImplDefinition) { + private RequirementImplData buildRequirementImplData(String resourceId, String reqName, RequirementImplDef reqImplDefinition) { String reqImplUid = UniqueIdBuilder.buildRequirementImplUid(resourceId, reqName); RequirementImplData requirementImplData = new RequirementImplData(); requirementImplData.setName(reqName); @@ -400,53 +359,43 @@ public class RequirementOperation implements IRequirementOperation { } /** - * associate requirement impl node to the source requirement. The source - * requirement maybe belongs to one of parents. + * associate requirement impl node to the source requirement. The source requirement maybe belongs to one of parents. * * @param requirementImplData * @param requirementUid * @return */ - private Either<GraphRelation, TitanOperationStatus> associateReqImplToRequirement( - RequirementImplData requirementImplData, String requirementUid) { + private Either<GraphRelation, TitanOperationStatus> associateReqImplToRequirement(RequirementImplData requirementImplData, String requirementUid) { UniqueIdData to = new UniqueIdData(NodeTypeEnum.Requirement, requirementUid); - log.debug("Before creating edge between requirement impl " + requirementImplData + " to requirement " - + requirementUid); - Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao - .createRelation(requirementImplData, to, GraphEdgeLabels.IMPLEMENTATION_OF, null); - log.debug("Before creating edge between requirement impl " + requirementImplData + " to requirement " - + requirementUid + ". status is " + createRelResult); + log.debug("Before creating edge between requirement impl {} to requirement {}", requirementImplData, requirementUid); + Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(requirementImplData, to, GraphEdgeLabels.IMPLEMENTATION_OF, null); + log.debug("Before creating edge between requirement impl {} to requirement {}. status is {}", requirementImplData, requirementUid, createRelResult); return createRelResult; } /** - * Associate requirement impl node to the node which supply this - * requirement. + * Associate requirement impl node to the node which supply this requirement. * * @param requirementImplData * @param nodeId * @return */ - private Either<GraphRelation, TitanOperationStatus> associateReqImplToImplResource( - RequirementImplData requirementImplData, String nodeId) { + private Either<GraphRelation, TitanOperationStatus> associateReqImplToImplResource(RequirementImplData requirementImplData, String nodeId) { UniqueIdData nodeImpl = new UniqueIdData(NodeTypeEnum.Resource, nodeId); Map<String, Object> props = new HashMap<String, Object>(); props.put(GraphPropertiesDictionary.NAME.getProperty(), nodeId); - log.debug("Before creating edge between requirement impl " + requirementImplData + " to node impl " + nodeId); - Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao - .createRelation(requirementImplData, nodeImpl, GraphEdgeLabels.NODE_IMPL, props); - log.debug("After creating edge between requirement " + requirementImplData + " to node impl " + nodeId - + ". status is " + createRelResult); + log.debug("Before creating edge between requirement impl {} to node impl {}", requirementImplData, nodeId); + Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(requirementImplData, nodeImpl, GraphEdgeLabels.NODE_IMPL, props); + log.debug("After creating edge between requirement {} to node impl {}. status is {}", requirementImplData, nodeId, createRelResult); return createRelResult; } /** - * create an edge between the requirement impl node to the implementation - * resource. + * create an edge between the requirement impl node to the implementation resource. * * @param resourceLabel * @param resourceId @@ -454,18 +403,14 @@ public class RequirementOperation implements IRequirementOperation { * @param requirementImplData * @return */ - private Either<GraphRelation, TitanOperationStatus> associateReqImplRoResource(NodeTypeEnum resourceLabel, - String resourceId, String reqName, RequirementImplData requirementImplData) { + private Either<GraphRelation, TitanOperationStatus> associateReqImplRoResource(NodeTypeEnum resourceLabel, String resourceId, String reqName, RequirementImplData requirementImplData) { UniqueIdData resource = new UniqueIdData(resourceLabel, resourceId); Map<String, Object> props = new HashMap<String, Object>(); props.put(GraphPropertiesDictionary.NAME.getProperty(), reqName); - log.debug( - "Before creating edge between resource " + resourceId + " to requirement impl " + requirementImplData); - Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(resource, - requirementImplData, GraphEdgeLabels.REQUIREMENT_IMPL, props); - log.debug("After creating edge between to requirement impl " + requirementImplData + " to resource " + resource - + ". status is " + createRelResult); + log.debug("Before creating edge between resource {} to requirement impl {}", resourceId, requirementImplData); + Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(resource, requirementImplData, GraphEdgeLabels.REQUIREMENT_IMPL, props); + log.debug("After creating edge between to requirement impl {} to resource {}. status is {}", requirementImplData, resource, createRelResult); return createRelResult; } @@ -476,65 +421,46 @@ public class RequirementOperation implements IRequirementOperation { } @Override - public Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource(String reqName, - RequirementDefinition reqDefinition, String resourceId, boolean inTransaction) { + public Either<RequirementDefinition, StorageOperationStatus> addRequirementToResource(String reqName, RequirementDefinition reqDefinition, String resourceId, boolean inTransaction) { Either<RequirementDefinition, StorageOperationStatus> result = null; try { - log.debug("Going to add requirement " + reqName + " to resource " + resourceId - + ". requirement definition is " + reqDefinition); + log.debug("Going to add requirement {} to resource {}. requirement definition is {}", reqName, resourceId, reqDefinition); validateNodeExists(reqDefinition.getNode()); // 1. add requirement node in graph and associate it to the resource log.debug("Going to add requirement node in graph and associate it to the resource"); - Either<RequirementData, TitanOperationStatus> addRequirementData = addRequirementData(resourceId, reqName, - reqDefinition); + Either<RequirementData, TitanOperationStatus> addRequirementData = addRequirementData(resourceId, reqName, reqDefinition); if (addRequirementData.isRight()) { - log.error("Failed to add requirement " + reqName + " node to graph. status is " + addRequirementData); - result = Either.right( - DaoStatusConverter.convertTitanStatusToStorageStatus(addRequirementData.right().value())); + log.error("Failed to add requirement {} node to graph. status is {}", reqName, addRequirementData); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(addRequirementData.right().value())); return result; } RequirementData requirementData = addRequirementData.left().value(); log.debug("Going to associate the requirement to the appriopriate capability type"); - Either<GraphRelation, TitanOperationStatus> associateReqToCapabilityType = associateRequirementToCapabilityType( - requirementData, reqDefinition); + Either<GraphRelation, TitanOperationStatus> associateReqToCapabilityType = associateRequirementToCapabilityType(requirementData, reqDefinition); if (associateReqToCapabilityType.isRight()) { - log.error("Failed to associate requirement data node " + requirementData - + " to the capability type node " + reqDefinition.getCapability()); - result = Either.right(DaoStatusConverter - .convertTitanStatusToStorageStatus(associateReqToCapabilityType.right().value())); + log.error("Failed to associate requirement data node {} to the capability type node {}", requirementData, reqDefinition.getCapability()); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(associateReqToCapabilityType.right().value())); return result; } // TODO: esofer associate requirement to the relationship type /* - * Either<GraphRelation, TitanOperationStatus> - * associateReqToRelshipType = - * associateRequirementToRelationshipType( requirementData, - * reqDefinition); + * Either<GraphRelation, TitanOperationStatus> associateReqToRelshipType = associateRequirementToRelationshipType( requirementData, reqDefinition); * - * if (associateReqToRelshipType.isRight() && - * associateReqToRelshipType.right().value() != - * TitanOperationStatus.NOT_FOUND) { - * log.error("Failed to associate requirement data node " + - * requirementData + " to the relationship type node " + - * reqDefinition.getRelationship()); result = Either - * .right(TitanStatusConverter - * .convertTitanStatusToStorageStatus(associateReqToRelshipType - * .right().value())); return result; } + * if (associateReqToRelshipType.isRight() && associateReqToRelshipType.right().value() != TitanOperationStatus.NOT_FOUND) { log.error("Failed to associate requirement data node " + requirementData + " to the relationship type node " + + * reqDefinition.getRelationship()); result = Either .right(TitanStatusConverter .convertTitanStatusToStorageStatus(associateReqToRelshipType .right().value())); return result; } */ - log.debug("Going to fetch the requirement " + reqName + " from graph"); - Either<RequirementDefinition, TitanOperationStatus> requirementDefinitionRes = getRequirement( - requirementData.getUniqueId()); + log.debug("Going to fetch the requirement {} from graph", reqName); + Either<RequirementDefinition, TitanOperationStatus> requirementDefinitionRes = getRequirement(requirementData.getUniqueId()); if (requirementDefinitionRes.isRight()) { - result = Either.right( - DaoStatusConverter.convertTitanStatusToStorageStatus(requirementDefinitionRes.right().value())); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(requirementDefinitionRes.right().value())); return result; } @@ -557,34 +483,28 @@ public class RequirementOperation implements IRequirementOperation { } @Override - public StorageOperationStatus addRequirementToResource(TitanVertex metadataVertex, String reqName, - RequirementDefinition reqDefinition, String resourceId, boolean inTransaction) { + public StorageOperationStatus addRequirementToResource(TitanVertex metadataVertex, String reqName, RequirementDefinition reqDefinition, String resourceId, boolean inTransaction) { StorageOperationStatus result = StorageOperationStatus.OK; try { - log.debug("Going to add requirement {} to resource . requirement definition is ", reqName, resourceId, - reqDefinition); + log.debug("Going to add requirement {} to resource . requirement definition is ", reqName, resourceId, reqDefinition); validateNodeExists(reqDefinition.getNode()); // 1. add requirement node in graph and associate it to the resource log.debug("Going to add requirement node in graph and associate it to the resource"); - Either<TitanVertex, TitanOperationStatus> addRequirementData = addRequirementData(metadataVertex, - resourceId, reqName, reqDefinition); + Either<TitanVertex, TitanOperationStatus> addRequirementData = addRequirementData(metadataVertex, resourceId, reqName, reqDefinition); if (addRequirementData.isRight()) { - log.error("Failed to add requirement {} node to graph. status is {}", reqName, - addRequirementData.right().value()); + log.error("Failed to add requirement {} node to graph. status is {}", reqName, addRequirementData.right().value()); result = DaoStatusConverter.convertTitanStatusToStorageStatus(addRequirementData.right().value()); return result; } log.debug("Going to associate the requirement to the appriopriate capability type"); - TitanOperationStatus associateReqToCapabilityType = associateRequirementToCapabilityType( - addRequirementData.left().value(), reqDefinition); + TitanOperationStatus associateReqToCapabilityType = associateRequirementToCapabilityType(addRequirementData.left().value(), reqDefinition); if (!associateReqToCapabilityType.equals(TitanOperationStatus.OK)) { - log.error("Failed to associate requirement data node {} to the capability type node {}" + reqDefinition, - reqDefinition.getCapability()); + log.error("Failed to associate requirement data node {} to the capability type node {}", reqDefinition.getCapability(), reqDefinition); result = DaoStatusConverter.convertTitanStatusToStorageStatus(associateReqToCapabilityType); return result; } @@ -614,22 +534,19 @@ public class RequirementOperation implements IRequirementOperation { public Either<RequirementDefinition, TitanOperationStatus> getRequirement(String uniqueId) { log.debug("Going to fetch the requirement {} from graph.", uniqueId); - Either<RequirementData, TitanOperationStatus> reqDataResult = titanGenericDao - .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Requirement), uniqueId, RequirementData.class); + Either<RequirementData, TitanOperationStatus> reqDataResult = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Requirement), uniqueId, RequirementData.class); if (reqDataResult.isRight()) { - log.error("Failed to find requirement node in graph " + uniqueId + ". status is " + reqDataResult); + log.error("Failed to find requirement node in graph {}. status is {}", uniqueId, reqDataResult); return Either.right(reqDataResult.right().value()); } log.debug("Going to fetch the capability type associate to requirement {}", uniqueId); - Either<ImmutablePair<CapabilityTypeData, GraphEdge>, TitanOperationStatus> capabilityTypeRes = titanGenericDao - .getChild(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), uniqueId, GraphEdgeLabels.CAPABILITY_TYPE, - NodeTypeEnum.CapabilityType, CapabilityTypeData.class); + Either<ImmutablePair<CapabilityTypeData, GraphEdge>, TitanOperationStatus> capabilityTypeRes = titanGenericDao.getChild(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), uniqueId, GraphEdgeLabels.CAPABILITY_TYPE, NodeTypeEnum.CapabilityType, + CapabilityTypeData.class); if (capabilityTypeRes.isRight()) { - log.error("Cannot find the capability of a given requirement " + uniqueId + ". status is " - + capabilityTypeRes); + log.error("Cannot find the capability of a given requirement {}. status is {}", uniqueId, capabilityTypeRes); return Either.right(capabilityTypeRes.right().value()); } @@ -639,37 +556,23 @@ public class RequirementOperation implements IRequirementOperation { // TODO: esofer add relationship as edge /* - * Either<List<ImmutablePair<RelationshipTypeData, GraphEdge>>, - * TitanOperationStatus> relationshipRes = titanGenericDao - * .getChildrenNodes( GraphPropertiesDictionary.UNIQUE_ID.getProperty(), - * uniqueId, GraphEdgeLabels.RELATIONSHIP_TYPE, + * Either<List<ImmutablePair<RelationshipTypeData, GraphEdge>>, TitanOperationStatus> relationshipRes = titanGenericDao .getChildrenNodes( GraphPropertiesDictionary.UNIQUE_ID.getProperty(), uniqueId, GraphEdgeLabels.RELATIONSHIP_TYPE, * NodeTypeEnum.RelationshipType, RelationshipTypeData.class); * - * if (relationshipRes.isRight() && relationshipRes.right().value() != - * TitanOperationStatus.NOT_FOUND) { - * log.error("Cannot find the capability of a given requirement " + - * uniqueId + ". status is " + capabilityTypesRes); return - * Either.right(relationshipRes.right().value()); } + * if (relationshipRes.isRight() && relationshipRes.right().value() != TitanOperationStatus.NOT_FOUND) { + * return Either.right(relationshipRes.right().value()); } * - * String relationshipType = null; if (relationshipRes.isLeft()) { - * List<ImmutablePair<RelationshipTypeData, GraphEdge>> rstPairs = - * relationshipRes .left().value(); if (rstPairs == null || true == - * rstPairs.isEmpty()) { log.error( - * "Cannot find the capability of a given requirement " + uniqueId); - * return Either.right(TitanOperationStatus.NOT_FOUND); } + * String relationshipType = null; if (relationshipRes.isLeft()) { List<ImmutablePair<RelationshipTypeData, GraphEdge>> rstPairs = relationshipRes .left().value(); if (rstPairs == null || true == rstPairs.isEmpty()) { log.error( + * "Cannot find the capability of a given requirement " + uniqueId); return Either.right(TitanOperationStatus.NOT_FOUND); } * - * ImmutablePair<RelationshipTypeData, GraphEdge> relationship = - * rstPairs .get(0); relationshipType = relationship.getKey().getType(); - * } + * ImmutablePair<RelationshipTypeData, GraphEdge> relationship = rstPairs .get(0); relationshipType = relationship.getKey().getType(); } */ log.debug("Going to fetch the capability type associate to requirement {}", uniqueId); - Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> parentNode = titanGenericDao - .getParentNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), uniqueId, GraphEdgeLabels.REQUIREMENT, - NodeTypeEnum.Resource, ResourceMetadataData.class); + Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> parentNode = titanGenericDao.getParentNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), uniqueId, GraphEdgeLabels.REQUIREMENT, NodeTypeEnum.Resource, + ResourceMetadataData.class); if (parentNode.isRight()) { - log.error("Cannot find the parent resource for a given requirement " + uniqueId + ". status is " - + parentNode.right().value()); + log.error("Cannot find the parent resource for a given requirement {}. status is {}", uniqueId, parentNode.right().value()); return Either.right(parentNode.right().value()); } @@ -689,15 +592,13 @@ public class RequirementOperation implements IRequirementOperation { } @Override - public Either<RequirementDefinition, StorageOperationStatus> getRequirementOfResource(String reqName, - String resourceId) { + public Either<RequirementDefinition, StorageOperationStatus> getRequirementOfResource(String reqName, String resourceId) { return getRequirementOfResource(reqName, resourceId, false); } @Override - public Either<RequirementDefinition, StorageOperationStatus> getRequirementOfResource(String reqName, - String resourceId, boolean inTransaction) { + public Either<RequirementDefinition, StorageOperationStatus> getRequirementOfResource(String reqName, String resourceId, boolean inTransaction) { Either<RequirementDefinition, StorageOperationStatus> result = null; @@ -706,9 +607,8 @@ public class RequirementOperation implements IRequirementOperation { Either<RequirementDefinition, TitanOperationStatus> requirementRes = getRequirement(reqUniqueId); if (requirementRes.isRight()) { - log.debug("Failed to retrieve requirement " + reqName + " associated to resource " + resourceId); - result = Either - .right(DaoStatusConverter.convertTitanStatusToStorageStatus(requirementRes.right().value())); + log.debug("Failed to retrieve requirement {} associated to resource {}", reqName, resourceId); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(requirementRes.right().value())); } else { result = Either.left(requirementRes.left().value()); } @@ -730,16 +630,14 @@ public class RequirementOperation implements IRequirementOperation { } @Override - public Either<RequirementDefinition, StorageOperationStatus> addRequirementImplToResource(String reqName, - RequirementImplDef reqDefinition, String resourceId, String parentReqUniqueId) { + public Either<RequirementDefinition, StorageOperationStatus> addRequirementImplToResource(String reqName, RequirementImplDef reqDefinition, String resourceId, String parentReqUniqueId) { return addRequirementImplToResource(reqName, reqDefinition, resourceId, parentReqUniqueId, false); } @Override - public Either<RequirementDefinition, StorageOperationStatus> addRequirementImplToResource(String reqName, - RequirementImplDef reqImplDefinition, String resourceId, String parentReqUniqueId, boolean inTransaction) { + public Either<RequirementDefinition, StorageOperationStatus> addRequirementImplToResource(String reqName, RequirementImplDef reqImplDefinition, String resourceId, String parentReqUniqueId, boolean inTransaction) { Either<RequirementDefinition, StorageOperationStatus> result = null; @@ -748,11 +646,10 @@ public class RequirementOperation implements IRequirementOperation { // find the requirement defined at the resource itself or under one // of its parents Either<RequirementDefinition, TitanOperationStatus> findReq = getRequirement(parentReqUniqueId); - log.debug("After looking for requirement " + parentReqUniqueId + ". status is " + findReq); + log.debug("After looking for requirement {}. status is {}", parentReqUniqueId, findReq); if (findReq.isRight()) { TitanOperationStatus status = findReq.right().value(); - log.error("The requirment " + parentReqUniqueId + " was not found in the graph. status is " - + findReq.right().value()); + log.error("The requirment {} was not found in the graph. status is {}", parentReqUniqueId, findReq.right().value()); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); return result; } @@ -765,27 +662,22 @@ public class RequirementOperation implements IRequirementOperation { checkNodeIdImplementsRequirementNode(nodeIdImpl, reqNode); - Either<RequirementImplData, TitanOperationStatus> addRequirementImplData = addRequirementImplData( - NodeTypeEnum.Resource, resourceId, reqName, parentReqUniqueId, reqImplDefinition); + Either<RequirementImplData, TitanOperationStatus> addRequirementImplData = addRequirementImplData(NodeTypeEnum.Resource, resourceId, reqName, parentReqUniqueId, reqImplDefinition); if (addRequirementImplData.isRight()) { TitanOperationStatus status = addRequirementImplData.right().value(); - log.error("Failed to add requirement data impl node in the graph. status is " - + addRequirementImplData.right().value()); + log.error("Failed to add requirement data impl node in the graph. status is {}", addRequirementImplData.right().value()); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); return result; } RequirementImplData requirementImplData = addRequirementImplData.left().value(); - log.debug("Add the properties of the capabilities of the target node " + nodeIdImpl - + " to the requirement impl node " + requirementImplData.getUniqueId() + " in graph."); - Map<String, CapabiltyInstance> requirementPropertiesPerCapability = reqImplDefinition - .getRequirementProperties(); - TitanOperationStatus addPropsResult = addCapabilityPropertiesToReqImpl(requirementImplData, reqCapability, - nodeIdImpl, requirementPropertiesPerCapability); + log.debug("Add the properties of the capabilities of the target node {} to the requirement impl node {} in graph.", nodeIdImpl, requirementImplData.getUniqueId()); + Map<String, CapabiltyInstance> requirementPropertiesPerCapability = reqImplDefinition.getRequirementProperties(); + TitanOperationStatus addPropsResult = addCapabilityPropertiesToReqImpl(requirementImplData, reqCapability, nodeIdImpl, requirementPropertiesPerCapability); if (addPropsResult != TitanOperationStatus.OK) { - log.error("Failed to add capabilities properties to Requirement impl " + requirementImplData); + log.error("Failed to add capabilities properties to Requirement impl {}", requirementImplData); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(addPropsResult)); return result; } @@ -807,15 +699,13 @@ public class RequirementOperation implements IRequirementOperation { return result; } - private Either<RequirementImplDef, TitanOperationStatus> getRequirementImplOfResource(String reqName, - String resourceId) { + private Either<RequirementImplDef, TitanOperationStatus> getRequirementImplOfResource(String reqName, String resourceId) { RequirementImplDef requirementImplDef = new RequirementImplDef(); - Either<List<ImmutablePair<RequirementImplData, GraphEdge>>, TitanOperationStatus> reqImplNodesRes = titanGenericDao - .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, - GraphEdgeLabels.REQUIREMENT_IMPL, NodeTypeEnum.RequirementImpl, RequirementImplData.class); - log.debug("After looking for requirement impl edge of resource " + resourceId); + Either<List<ImmutablePair<RequirementImplData, GraphEdge>>, TitanOperationStatus> reqImplNodesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.REQUIREMENT_IMPL, + NodeTypeEnum.RequirementImpl, RequirementImplData.class); + log.debug("After looking for requirement impl edge of resource {}", resourceId); if (reqImplNodesRes.isRight()) { TitanOperationStatus status = reqImplNodesRes.right().value(); return Either.right(status); @@ -832,15 +722,12 @@ public class RequirementOperation implements IRequirementOperation { requirementImplDef.setUniqueId(requirementImplData.getUniqueId()); - Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> nodeImplRes = titanGenericDao - .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.RequirementImpl), - requirementImplData.getUniqueId(), GraphEdgeLabels.NODE_IMPL, NodeTypeEnum.Resource, - ResourceMetadataData.class); + Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> nodeImplRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.RequirementImpl), requirementImplData.getUniqueId(), + GraphEdgeLabels.NODE_IMPL, NodeTypeEnum.Resource, ResourceMetadataData.class); if (nodeImplRes.isRight()) { TitanOperationStatus status = nodeImplRes.right().value(); - log.debug("No implementation resource was found under requirement impl " - + requirementImplData.getUniqueId() + ". status is " + status); + log.debug("No implementation resource was found under requirement impl {}. status is {}", requirementImplData.getUniqueId(), status); return Either.right(status); } @@ -854,14 +741,11 @@ public class RequirementOperation implements IRequirementOperation { requirementImplDef.setPoint(point); } - Either<List<ImmutablePair<CapabilityInstData, GraphEdge>>, TitanOperationStatus> capaInstDataRes = titanGenericDao - .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.RequirementImpl), - requirementImplData.getUniqueId(), GraphEdgeLabels.CAPABILITY_INST, - NodeTypeEnum.CapabilityInst, CapabilityInstData.class); + Either<List<ImmutablePair<CapabilityInstData, GraphEdge>>, TitanOperationStatus> capaInstDataRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.RequirementImpl), requirementImplData.getUniqueId(), + GraphEdgeLabels.CAPABILITY_INST, NodeTypeEnum.CapabilityInst, CapabilityInstData.class); if (capaInstDataRes.isRight()) { TitanOperationStatus status = capaInstDataRes.right().value(); - log.debug("No capability instance was found under requirement impl " - + requirementImplData.getUniqueId() + ". status is " + status); + log.debug("No capability instance was found under requirement impl {}. status is {}", requirementImplData.getUniqueId(), status); return Either.right(status); } @@ -874,14 +758,12 @@ public class RequirementOperation implements IRequirementOperation { GraphEdge edge = capabilityInst.getValue(); Map<String, Object> properties = edge.getProperties(); if (properties == null) { - log.error("Cannot find the property " + GraphPropertiesDictionary.NAME.getProperty() - + " on the edge " + edge); + log.error("Cannot find the property {} on the edge {}", GraphPropertiesDictionary.NAME.getProperty(), edge); return Either.right(TitanOperationStatus.INVALID_ELEMENT); } String capabilityName = (String) properties.get(GraphPropertiesDictionary.NAME.getProperty()); if (capabilityName == null) { - log.error("Cannot find the property " + GraphPropertiesDictionary.NAME.getProperty() - + " on the edge " + edge); + log.error("Cannot find the property {} on the edge {}", GraphPropertiesDictionary.NAME.getProperty(), edge); return Either.right(TitanOperationStatus.INVALID_ELEMENT); } @@ -896,30 +778,25 @@ public class RequirementOperation implements IRequirementOperation { // capabiltyInstance.setProperties(actualValues); requirementProperties.put(capabilityName, capabiltyInstance); - Either<List<ImmutablePair<PropertyValueData, GraphEdge>>, TitanOperationStatus> propertyValueNodesRes = titanGenericDao - .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityInst), - capabilityInstData.getUniqueId(), GraphEdgeLabels.PROPERTY_VALUE, - NodeTypeEnum.PropertyValue, PropertyValueData.class); + Either<List<ImmutablePair<PropertyValueData, GraphEdge>>, TitanOperationStatus> propertyValueNodesRes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityInst), + capabilityInstData.getUniqueId(), GraphEdgeLabels.PROPERTY_VALUE, NodeTypeEnum.PropertyValue, PropertyValueData.class); if (propertyValueNodesRes.isRight()) { TitanOperationStatus status = propertyValueNodesRes.right().value(); if (status != TitanOperationStatus.NOT_FOUND) { - log.error("Failed to find the property values of capability instance " + capabilityInstData - + ". status is " + status); + log.error("Failed to find the property values of capability instance {}. status is {}", capabilityInstData, status); return Either.right(status); } } else { - List<ImmutablePair<PropertyValueData, GraphEdge>> propertyValueNodes = propertyValueNodesRes - .left().value(); + List<ImmutablePair<PropertyValueData, GraphEdge>> propertyValueNodes = propertyValueNodesRes.left().value(); if (propertyValueNodes != null) { Map<String, String> actualValues = new HashMap<String, String>(); - TitanOperationStatus fillPropertiesResult = fillPropertiesMapFromNodes(propertyValueNodes, - actualValues); + TitanOperationStatus fillPropertiesResult = fillPropertiesMapFromNodes(propertyValueNodes, actualValues); if (fillPropertiesResult != TitanOperationStatus.OK) { - log.error("Failed to fetch properties of capability " + capabilityName); + log.error("Failed to fetch properties of capability {}", capabilityName); return Either.right(fillPropertiesResult); } @@ -940,7 +817,7 @@ public class RequirementOperation implements IRequirementOperation { } if (false == found) { - log.debug("Cannot find requirement impl under resource " + resourceId); + log.debug("Cannot find requirement impl under resource {}", resourceId); return Either.right(TitanOperationStatus.NOT_FOUND); } @@ -965,22 +842,19 @@ public class RequirementOperation implements IRequirementOperation { } - private TitanOperationStatus fillPropertiesMapFromNodes( - List<ImmutablePair<PropertyValueData, GraphEdge>> propertyValueNodes, Map<String, String> actualValues) { + private TitanOperationStatus fillPropertiesMapFromNodes(List<ImmutablePair<PropertyValueData, GraphEdge>> propertyValueNodes, Map<String, String> actualValues) { if (propertyValueNodes != null) { for (ImmutablePair<PropertyValueData, GraphEdge> propertyValuePair : propertyValueNodes) { PropertyValueData propertyValueData = propertyValuePair.getKey(); GraphEdge propertyValueEdge = propertyValuePair.getValue(); Map<String, Object> propertyEdgeProps = propertyValueEdge.getProperties(); if (propertyEdgeProps == null) { - log.error("Cannot find the property " + GraphPropertiesDictionary.NAME.getProperty() - + " on the edge " + propertyValueEdge); + log.error("Cannot find the property {} on the edge {}", GraphPropertiesDictionary.NAME.getProperty(), propertyValueEdge); return TitanOperationStatus.INVALID_ELEMENT; } String paramName = (String) propertyEdgeProps.get(GraphPropertiesDictionary.NAME.getProperty()); if (paramName == null) { - log.error("Cannot find the property " + GraphPropertiesDictionary.NAME.getProperty() - + " on the edge " + propertyValueEdge); + log.error("Cannot find the property {} on the edge {}", GraphPropertiesDictionary.NAME.getProperty(), propertyValueEdge); return TitanOperationStatus.INVALID_ELEMENT; } actualValues.put(paramName, propertyValueData.getValue()); @@ -989,18 +863,16 @@ public class RequirementOperation implements IRequirementOperation { return TitanOperationStatus.OK; } - private TitanOperationStatus addCapabilityPropertiesToReqImpl(RequirementImplData reqImplData, String reqCapability, - String nodeIdImpl, Map<String, CapabiltyInstance> propertiesValuePerCapability) { + private TitanOperationStatus addCapabilityPropertiesToReqImpl(RequirementImplData reqImplData, String reqCapability, String nodeIdImpl, Map<String, CapabiltyInstance> propertiesValuePerCapability) { TitanOperationStatus result = null; - Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> allCapabilities = capabilityOperation - .getAllCapabilitiesPairs(nodeIdImpl); - log.trace("Atter looking for the capabilities of resource " + nodeIdImpl + ". result is " + allCapabilities); + Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> allCapabilities = capabilityOperation.getAllCapabilitiesPairs(nodeIdImpl); + log.trace("Atter looking for the capabilities of resource {}. result is {}", nodeIdImpl, allCapabilities); if (allCapabilities.isRight()) { TitanOperationStatus status = allCapabilities.right().value(); if (status != TitanOperationStatus.NOT_FOUND) { - log.error("Failed to find capabilities of resource " + nodeIdImpl + ". status is " + status); + log.error("Failed to find capabilities of resource {}. status is {}", nodeIdImpl, status); return status; } } else { @@ -1014,37 +886,32 @@ public class RequirementOperation implements IRequirementOperation { GraphEdge graphEdge = entry.getValue(); - Either<String, TitanOperationStatus> capabilityNameResult = findCapabilityName(capabilityData, - graphEdge); + Either<String, TitanOperationStatus> capabilityNameResult = findCapabilityName(capabilityData, graphEdge); if (capabilityNameResult.isRight()) { TitanOperationStatus status = capabilityNameResult.right().value(); - log.error( - "Failed to find capability name from the edge associated to capability " + capabilityData); + log.error("Failed to find capability name from the edge associated to capability {}", capabilityData); return status; } String capabilityName = capabilityNameResult.left().value(); - log.debug("Going to set properties of capability " + capabilityName); + log.debug("Going to set properties of capability {}", capabilityName); String cabilityDataUid = capabilityData.getUniqueId(); - Either<CapabilityTypeData, TitanOperationStatus> ctDataResult = capabilityOperation - .getCapabilityTypeOfCapability(cabilityDataUid); + Either<CapabilityTypeData, TitanOperationStatus> ctDataResult = capabilityOperation.getCapabilityTypeOfCapability(cabilityDataUid); if (ctDataResult.isRight()) { - log.error("Cannot find capability type of capbility " + cabilityDataUid + ". status is " - + ctDataResult); + log.error("Cannot find capability type of capbility {}. status is {}", cabilityDataUid, ctDataResult); TitanOperationStatus status = ctDataResult.right().value(); return status; } CapabilityTypeData capabilityTypeData = ctDataResult.left().value(); - Either<Map<String, PropertyDefinition>, TitanOperationStatus> propertiesStatus = findPropertiesOfCapability( - capabilityTypeData); + Either<Map<String, PropertyDefinition>, TitanOperationStatus> propertiesStatus = findPropertiesOfCapability(capabilityTypeData); if (propertiesStatus.isRight()) { TitanOperationStatus status = propertiesStatus.right().value(); - log.error("Failed to fetch properties definitions from capability. status is " + status); + log.error("Failed to fetch properties definitions from capability. status is {}", status); return status; } @@ -1055,43 +922,35 @@ public class RequirementOperation implements IRequirementOperation { capabiltyInstance = propertiesValuePerCapability.get(capabilityName); } - Either<CapabilityInstData, TitanOperationStatus> createCapabilityInstanceNode = createCapabilityInstanceNode( - capabilityName, reqImplData); + Either<CapabilityInstData, TitanOperationStatus> createCapabilityInstanceNode = createCapabilityInstanceNode(capabilityName, reqImplData); if (createCapabilityInstanceNode.isRight()) { TitanOperationStatus status = createCapabilityInstanceNode.right().value(); - log.error("Failed to create capability instance node (" + capabilityName + ") in graph. status is " - + status); + log.error("Failed to create capability instance node ({}) in graph. status is {}", capabilityName, status); return status; } CapabilityInstData capabilityInstData = createCapabilityInstanceNode.left().value(); - Either<List<GraphRelation>, TitanOperationStatus> instanceProperties = addPropertiesToCapabilityInstance( - properties, capabiltyInstance, capabilityInstData); + Either<List<GraphRelation>, TitanOperationStatus> instanceProperties = addPropertiesToCapabilityInstance(properties, capabiltyInstance, capabilityInstData); if (instanceProperties.isRight()) { TitanOperationStatus status = instanceProperties.right().value(); - log.debug("Failed to add properties to capability instance. status is " + status); + log.debug("Failed to add properties to capability instance. status is {}", status); return status; } - Either<GraphRelation, TitanOperationStatus> associateCapabilityInstToCapabilityType = associateCapabilityInstToCapabilityType( - capabilityInstData, capabilityTypeData); + Either<GraphRelation, TitanOperationStatus> associateCapabilityInstToCapabilityType = associateCapabilityInstToCapabilityType(capabilityInstData, capabilityTypeData); if (associateCapabilityInstToCapabilityType.isRight()) { TitanOperationStatus status = associateCapabilityInstToCapabilityType.right().value(); - log.error("Failed to associate capability instance " + capabilityInstData - + " to capability type node " + capabilityTypeData + " in graph. status is " + status); + log.error("Failed to associate capability instance {} to capability type node {} in graph. status is {}", capabilityInstData, capabilityTypeData, status); return status; } - Either<GraphRelation, TitanOperationStatus> associateCapabilityInst = associateRequirementImplToCapabilityInst( - reqImplData, capabilityInstData, capabilityName); + Either<GraphRelation, TitanOperationStatus> associateCapabilityInst = associateRequirementImplToCapabilityInst(reqImplData, capabilityInstData, capabilityName); if (associateCapabilityInst.isRight()) { TitanOperationStatus status = associateCapabilityInst.right().value(); - log.error("Failed to associate requirement impl " + reqImplData + " to capability instance node " - + capabilityInstData + " of capability " + capabilityName + ") in graph. status is " - + status); + log.error("Failed to associate requirement impl {} to capability instance node {} of capability {}) in graph. status is {}", reqImplData, capabilityInstData, capabilityName, status); return status; } @@ -1102,16 +961,13 @@ public class RequirementOperation implements IRequirementOperation { return result; } - private Either<Map<String, PropertyDefinition>, TitanOperationStatus> findPropertiesOfCapability( - CapabilityTypeData capabilityTypeData) { + private Either<Map<String, PropertyDefinition>, TitanOperationStatus> findPropertiesOfCapability(CapabilityTypeData capabilityTypeData) { String capabilityTypeUid = capabilityTypeData.getUniqueId(); - Either<CapabilityTypeDefinition, TitanOperationStatus> capabilityTypeResult = capabilityTypeOperation - .getCapabilityTypeByUid(capabilityTypeUid); + Either<CapabilityTypeDefinition, TitanOperationStatus> capabilityTypeResult = capabilityTypeOperation.getCapabilityTypeByUid(capabilityTypeUid); if (capabilityTypeResult.isRight()) { - log.error("Failed to find capabilityType " + capabilityTypeUid + " in the graph. status is " - + capabilityTypeResult); + log.error("Failed to find capabilityType {} in the graph. status is {}", capabilityTypeUid, capabilityTypeResult); return Either.right(capabilityTypeResult.right().value()); } @@ -1121,44 +977,37 @@ public class RequirementOperation implements IRequirementOperation { return Either.left(properties); } - private Either<String, TitanOperationStatus> findCapabilityName(CapabilityData capabilityData, - GraphEdge graphEdge) { + private Either<String, TitanOperationStatus> findCapabilityName(CapabilityData capabilityData, GraphEdge graphEdge) { Map<String, Object> edgeProps = graphEdge.getProperties(); String capabilityName = (String) edgeProps.get(GraphPropertiesDictionary.NAME.getProperty()); if (capabilityName == null) { - log.debug("Cannot find the name of the capability associated to node " + capabilityData); + log.debug("Cannot find the name of the capability associated to node {}", capabilityData); return Either.right(TitanOperationStatus.NOT_FOUND); } return Either.left(capabilityName); } - private Either<GraphRelation, TitanOperationStatus> associateCapabilityInstToCapabilityType( - CapabilityInstData capabilityInstData, CapabilityTypeData capabilityTypeData) { + private Either<GraphRelation, TitanOperationStatus> associateCapabilityInstToCapabilityType(CapabilityInstData capabilityInstData, CapabilityTypeData capabilityTypeData) { - Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(capabilityInstData, - capabilityTypeData, GraphEdgeLabels.INSTANCE_OF, null); + Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(capabilityInstData, capabilityTypeData, GraphEdgeLabels.INSTANCE_OF, null); return createRelation; } /** - * add property value node with default value of override value and - * associate it to the capability instance node + * add property value node with default value of override value and associate it to the capability instance node * * @param properties * - properties definition. old also default value * @param capabilityInstance * - hold also properties new value(if exists) * @param capabilityInstData - * - the graph node which we associate the properties value node - * to. + * - the graph node which we associate the properties value node to. * @return */ - private Either<List<GraphRelation>, TitanOperationStatus> addPropertiesToCapabilityInstance( - Map<String, PropertyDefinition> properties, CapabiltyInstance capabilityInstance, - CapabilityInstData capabilityInstData) { + private Either<List<GraphRelation>, TitanOperationStatus> addPropertiesToCapabilityInstance(Map<String, PropertyDefinition> properties, CapabiltyInstance capabilityInstance, CapabilityInstData capabilityInstData) { List<GraphRelation> relationsResult = new ArrayList<GraphRelation>(); @@ -1171,31 +1020,24 @@ public class RequirementOperation implements IRequirementOperation { String propertyValue = setPropertyValue(capabilityInstance, paramName, propertyDefinition); - PropertyValueData propertyValueData = buildPropertyValueData(capabilityInstData.getUniqueId(), - paramName, propertyValue); + PropertyValueData propertyValueData = buildPropertyValueData(capabilityInstData.getUniqueId(), paramName, propertyValue); - log.debug("Before creating property value data node " + propertyValueData + " in graph."); - Either<PropertyValueData, TitanOperationStatus> createNode = titanGenericDao - .createNode(propertyValueData, PropertyValueData.class); - log.debug("Before creating property value data node " + propertyValueData + " in graph. status is " - + createNode); + log.debug("Before creating property value data node {} in graph.", propertyValueData); + Either<PropertyValueData, TitanOperationStatus> createNode = titanGenericDao.createNode(propertyValueData, PropertyValueData.class); + log.debug("Before creating property value data node {} in graph. status is {}", propertyValueData, createNode); if (createNode.isRight()) { TitanOperationStatus status = createNode.right().value(); - log.error("Failed to create property value node in graph " + propertyValueData + ". status is " - + status); + log.error("Failed to create property value node in graph {}. status is {}", propertyValueData, status); return Either.right(status); } PropertyValueData propertyValueDataCreated = createNode.left().value(); - Either<GraphRelation, TitanOperationStatus> createRelation = associateCapabilityInstToPropertyValue( - capabilityInstData, paramName, propertyValueDataCreated); + Either<GraphRelation, TitanOperationStatus> createRelation = associateCapabilityInstToPropertyValue(capabilityInstData, paramName, propertyValueDataCreated); if (createRelation.isRight()) { TitanOperationStatus status = createNode.right().value(); - log.error("Failed to create relation between capability instance " - + capabilityInstData.getUniqueId() + " to property value " - + propertyValueDataCreated.getUniqueId() + " in graph. status is " + status); + log.error("Failed to create relation between capability instance {} to property value {} in graph. status is {}", capabilityInstData.getUniqueId(), propertyValueDataCreated.getUniqueId(), status); return Either.right(status); } @@ -1207,23 +1049,18 @@ public class RequirementOperation implements IRequirementOperation { return Either.left(relationsResult); } - private Either<GraphRelation, TitanOperationStatus> associateCapabilityInstToPropertyValue( - CapabilityInstData capabilityInstData, String paramName, PropertyValueData propertyValueDataCreated) { + private Either<GraphRelation, TitanOperationStatus> associateCapabilityInstToPropertyValue(CapabilityInstData capabilityInstData, String paramName, PropertyValueData propertyValueDataCreated) { Map<String, Object> edgeProps = new HashMap<String, Object>(); edgeProps.put(GraphPropertiesDictionary.NAME.getProperty(), paramName); - log.debug("Begin creating relation between capability instance " + capabilityInstData + " to property value " - + propertyValueDataCreated + " in graph."); - Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(capabilityInstData, - propertyValueDataCreated, GraphEdgeLabels.PROPERTY_VALUE, edgeProps); - log.debug("After creating relation between capability instance " + capabilityInstData + " to property value " - + propertyValueDataCreated + " in graph. status is " + createRelation); + log.debug("Begin creating relation between capability instance {} to property value {} in graph.", capabilityInstData, propertyValueDataCreated); + Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(capabilityInstData, propertyValueDataCreated, GraphEdgeLabels.PROPERTY_VALUE, edgeProps); + log.debug("After creating relation between capability instance {} to property value {} in graph. status is {}", capabilityInstData, propertyValueDataCreated, createRelation); return createRelation; } - private String setPropertyValue(CapabiltyInstance capabilityInstance, String paramName, - PropertyDefinition propertyDefinition) { + private String setPropertyValue(CapabiltyInstance capabilityInstance, String paramName, PropertyDefinition propertyDefinition) { String propertyValue = NA; if (propertyDefinition.getDefaultValue() != null) { propertyValue = propertyDefinition.getDefaultValue(); @@ -1245,8 +1082,7 @@ public class RequirementOperation implements IRequirementOperation { return paramName + EQUAL_SIGN + paramValue; } - private PropertyValueData buildPropertyValueData(String capabilityInstDataUid, String paramName, - String propertyValue) { + private PropertyValueData buildPropertyValueData(String capabilityInstDataUid, String paramName, String propertyValue) { PropertyValueData propertyValueData = new PropertyValueData(); propertyValueData.setValue(propertyValue); String uid = UniqueIdBuilder.buildPropertyValueUniqueId(capabilityInstDataUid, paramName); @@ -1257,8 +1093,7 @@ public class RequirementOperation implements IRequirementOperation { return propertyValueData; } - private Either<CapabilityInstData, TitanOperationStatus> createCapabilityInstanceNode(String capabilityName, - RequirementImplData reqImplData) { + private Either<CapabilityInstData, TitanOperationStatus> createCapabilityInstanceNode(String capabilityName, RequirementImplData reqImplData) { CapabilityInstData capabilityInstData = new CapabilityInstData(); String uniqueId = UniqueIdBuilder.buildCapabilityInstanceUid(reqImplData.getUniqueId(), capabilityName); @@ -1269,11 +1104,9 @@ public class RequirementOperation implements IRequirementOperation { capabilityInstData.setCreationTime(creationDate); capabilityInstData.setModificationTime(creationDate); - log.debug("Before creating capability instance node in graph " + capabilityInstData); - Either<CapabilityInstData, TitanOperationStatus> createNode = titanGenericDao.createNode(capabilityInstData, - CapabilityInstData.class); - log.debug( - "After creating capability instance node in graph " + capabilityInstData + ". status is " + createNode); + log.debug("Before creating capability instance node in graph {}", capabilityInstData); + Either<CapabilityInstData, TitanOperationStatus> createNode = titanGenericDao.createNode(capabilityInstData, CapabilityInstData.class); + log.debug("After creating capability instance node in graph {}. status is {}", capabilityInstData, createNode); return createNode; } @@ -1283,14 +1116,12 @@ public class RequirementOperation implements IRequirementOperation { } - private void checkImplNodeContainsReqCapability(String reqCapability, - List<ImmutablePair<CapabilityData, GraphEdge>> capabilitiesValue) { + private void checkImplNodeContainsReqCapability(String reqCapability, List<ImmutablePair<CapabilityData, GraphEdge>> capabilitiesValue) { // TODO Auto-generated method stub } - public Either<Map<String, List<RequirementDefinition>>, StorageOperationStatus> getAllRequirementsOfResourceOnly( - String resourceId, boolean inTransaction) { + public Either<Map<String, List<RequirementDefinition>>, StorageOperationStatus> getAllRequirementsOfResourceOnly(String resourceId, boolean inTransaction) { Either<Map<String, List<RequirementDefinition>>, StorageOperationStatus> result = null; @@ -1298,11 +1129,10 @@ public class RequirementOperation implements IRequirementOperation { Map<String, RequirementDefinition> requirements = new HashMap<String, RequirementDefinition>(); Set<String> caseInsensitiveReqNames = new HashSet<>(); - TitanOperationStatus status = findAllRequirementsNonRecursive(resourceId, requirements, - caseInsensitiveReqNames); + TitanOperationStatus status = findAllRequirementsNonRecursive(resourceId, requirements, caseInsensitiveReqNames); if (status != TitanOperationStatus.OK) { - log.error("Failed to get all requirements of resource " + resourceId + ". status is " + status); + log.error("Failed to get all requirements of resource {}. status is {}", resourceId, status); return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); } else { // TODO handle requirementImpl @@ -1332,7 +1162,7 @@ public class RequirementOperation implements IRequirementOperation { TitanOperationStatus status = findAllRequirementsRecursively(resourceId, requirements, caseInsensitiveReqNames); if (status != TitanOperationStatus.OK) { - log.error("Failed to get all requirements of resource " + resourceId + ". status is " + status); + log.error("Failed to get all requirements of resource {}. status is {}", resourceId, status); return Either.right(status); } else { log.debug("The requirements returned for resource {} are {}", resourceId, requirements); @@ -1340,17 +1170,14 @@ public class RequirementOperation implements IRequirementOperation { if (requirements != null) { for (Entry<String, RequirementDefinition> entry : requirements.entrySet()) { String reqName = entry.getKey(); - Either<RequirementImplDef, TitanOperationStatus> reqImplRes = this - .getRequirementImplOfResource(reqName, resourceId); + Either<RequirementImplDef, TitanOperationStatus> reqImplRes = this.getRequirementImplOfResource(reqName, resourceId); if (reqImplRes.isRight()) { TitanOperationStatus reqImplResStatus = reqImplRes.right().value(); if (reqImplResStatus == TitanOperationStatus.NOT_FOUND) { - log.debug("Cannot find implementation of requirement {} under resource {}", reqName, - resourceId); + log.debug("Cannot find implementation of requirement {} under resource {}", reqName, resourceId); } else { - log.error("Cannot find implementation of requirement {} under resource {}", reqName, - resourceId); + log.error("Cannot find implementation of requirement {} under resource {}", reqName, resourceId); return Either.right(reqImplResStatus); } } else { @@ -1361,8 +1188,7 @@ public class RequirementOperation implements IRequirementOperation { } } } - log.debug("The requirements returned for resource {} after fetching requirement impl are {}", resourceId, - requirements); + log.debug("The requirements returned for resource {} after fetching requirement impl are {}", resourceId, requirements); result = Either.left(requirements); @@ -1372,15 +1198,13 @@ public class RequirementOperation implements IRequirementOperation { } @Override - public Either<Map<String, RequirementDefinition>, StorageOperationStatus> getAllResourceRequirements( - String resourceId, boolean inTransaction) { + public Either<Map<String, RequirementDefinition>, StorageOperationStatus> getAllResourceRequirements(String resourceId, boolean inTransaction) { Either<Map<String, RequirementDefinition>, StorageOperationStatus> result = null; try { - Either<Map<String, RequirementDefinition>, TitanOperationStatus> internalResult = getResourceRequirements( - resourceId); + Either<Map<String, RequirementDefinition>, TitanOperationStatus> internalResult = getResourceRequirements(resourceId); if (internalResult.isRight()) { TitanOperationStatus status = internalResult.right().value(); if (status != TitanOperationStatus.NOT_FOUND) { @@ -1394,67 +1218,8 @@ public class RequirementOperation implements IRequirementOperation { result = Either.left(value); return result; - - // Map<String, RequirementDefinition> requirements = new - // HashMap<String, RequirementDefinition>(); - // TitanOperationStatus status = findAllRequirementsRecursively( - // resourceId, requirements); - // if (status != TitanOperationStatus.OK) { - // log.error("Failed to get all requirements of resource " - // + resourceId + ". status is " + status); - // return Either.right(TitanStatusConverter - // .convertTitanStatusToStorageStatus(status)); - // } else { - // log.debug("The requirements returned for resource " - // + resourceId + " are " + requirements); - // - // if (requirements != null) { - // for (Entry<String, RequirementDefinition> entry : requirements - // .entrySet()) { - // String reqName = entry.getKey(); - // Either<RequirementImplDef, TitanOperationStatus> reqImplRes = - // this - // .getRequirementImplOfResource(reqName, - // resourceId); - // if (reqImplRes.isRight()) { - // - // TitanOperationStatus reqImplResStatus = reqImplRes - // .right().value(); - // if (reqImplResStatus == TitanOperationStatus.NOT_FOUND) { - // log.warn("Cannot find implementation of requirement " - // + reqName - // + " under resource " - // + resourceId); - // } else { - // log.error("Cannot find implementation of requirement " - // + reqName - // + " under resource " - // + resourceId); - // return Either - // .right(TitanStatusConverter - // .convertTitanStatusToStorageStatus(reqImplResStatus)); - // } - // } else { - // RequirementDefinition requirementDefinition = entry - // .getValue(); - // RequirementImplDef requirementImplDef = reqImplRes - // .left().value(); - // requirementDefinition - // .setRequirementImpl(requirementImplDef); - // } - // } - // } - // log.debug("The requirements returned for resource " - // + resourceId + " after fetching requirement impl are " - // + requirements); - // - // result = Either.left(requirements); - // - // return result; - // } - } finally { - if (false == inTransaction) { + if (!inTransaction) { if (result == null || result.isRight()) { log.error("Going to execute rollback on graph."); titanGenericDao.rollback(); @@ -1467,26 +1232,21 @@ public class RequirementOperation implements IRequirementOperation { } - public Either<Map<String, RequirementDefinition>, StorageOperationStatus> getAllResourceRequirements( - String resourceId) { + public Either<Map<String, RequirementDefinition>, StorageOperationStatus> getAllResourceRequirements(String resourceId) { return getAllResourceRequirements(resourceId, false); } - public TitanOperationStatus findAllRequirementsRecursively(String resourceId, - Map<String, RequirementDefinition> requirements, Set<String> caseInsensitiveReqNames) { + public TitanOperationStatus findAllRequirementsRecursively(String resourceId, Map<String, RequirementDefinition> requirements, Set<String> caseInsensitiveReqNames) { - TitanOperationStatus nonRecursiveResult = findAllRequirementsNonRecursive(resourceId, requirements, - caseInsensitiveReqNames); - if (!nonRecursiveResult.equals(TitanOperationStatus.OK) - && !nonRecursiveResult.equals(TitanOperationStatus.NOT_FOUND)) { + TitanOperationStatus nonRecursiveResult = findAllRequirementsNonRecursive(resourceId, requirements, caseInsensitiveReqNames); + if (!nonRecursiveResult.equals(TitanOperationStatus.OK) && !nonRecursiveResult.equals(TitanOperationStatus.NOT_FOUND)) { return nonRecursiveResult; } - Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> parentNodes = titanGenericDao - .getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, - GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource, ResourceMetadataData.class); + Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> parentNodes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource, + ResourceMetadataData.class); if (parentNodes.isRight()) { TitanOperationStatus parentNodesStatus = parentNodes.right().value(); @@ -1494,15 +1254,13 @@ public class RequirementOperation implements IRequirementOperation { log.debug("Finish to lookup for parnet requirements"); return TitanOperationStatus.OK; } else { - log.error("Failed to find parent requirements of resource {} . status is {}", resourceId, - parentNodesStatus); + log.error("Failed to find parent requirements of resource {} . status is {}", resourceId, parentNodesStatus); return parentNodesStatus; } } ImmutablePair<ResourceMetadataData, GraphEdge> parnetNodePair = parentNodes.left().value(); String parentUniqueId = parnetNodePair.getKey().getMetadataDataDefinition().getUniqueId(); - TitanOperationStatus addParentReqStatus = findAllRequirementsRecursively(parentUniqueId, requirements, - caseInsensitiveReqNames); + TitanOperationStatus addParentReqStatus = findAllRequirementsRecursively(parentUniqueId, requirements, caseInsensitiveReqNames); if (addParentReqStatus != TitanOperationStatus.OK) { log.error("Failed to fetch all requirements of resource {}", parentUniqueId); @@ -1512,11 +1270,9 @@ public class RequirementOperation implements IRequirementOperation { return TitanOperationStatus.OK; } - private TitanOperationStatus findAllRequirementsNonRecursive(String resourceId, - Map<String, RequirementDefinition> requirements, Set<String> caseInsensitiveReqNames) { - Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> requirementNodes = titanGenericDao - .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, - GraphEdgeLabels.REQUIREMENT, NodeTypeEnum.Requirement, RequirementData.class); + private TitanOperationStatus findAllRequirementsNonRecursive(String resourceId, Map<String, RequirementDefinition> requirements, Set<String> caseInsensitiveReqNames) { + Either<List<ImmutablePair<RequirementData, GraphEdge>>, TitanOperationStatus> requirementNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.REQUIREMENT, + NodeTypeEnum.Requirement, RequirementData.class); if (requirementNodes.isRight()) { TitanOperationStatus status = requirementNodes.right().value(); @@ -1533,18 +1289,17 @@ public class RequirementOperation implements IRequirementOperation { if (edgeProps != null) { reqName = (String) edgeProps.get(GraphPropertiesDictionary.NAME.getProperty()); if (reqName == null) { - log.error("The requirement name is missing on the edge of requirement " + reqUniqueId); + log.error("The requirement name is missing on the edge of requirement {}", reqUniqueId); return TitanOperationStatus.INVALID_ELEMENT; } } else { - log.error("The requirement name is missing on the edge of requirement " + reqUniqueId); + log.error("The requirement name is missing on the edge of requirement {}", reqUniqueId); return TitanOperationStatus.INVALID_ELEMENT; } - Either<RequirementDefinition, TitanOperationStatus> requirementDefRes = this - .getRequirement(reqUniqueId); + Either<RequirementDefinition, TitanOperationStatus> requirementDefRes = this.getRequirement(reqUniqueId); if (requirementDefRes.isRight()) { TitanOperationStatus status = requirementDefRes.right().value(); - log.error("Failed to get requirement properties of requirement " + reqUniqueId); + log.error("Failed to get requirement properties of requirement {}", reqUniqueId); return status; } @@ -1552,9 +1307,7 @@ public class RequirementOperation implements IRequirementOperation { requirementDefinition.setName(reqName); // US631462 if (caseInsensitiveReqNames.contains(reqName.toLowerCase())) { - log.debug( - "The requirement {} was already defined in derived resource (case insensitive). Ignore {} from resource {}", - reqName, reqName, resourceId); + log.debug("The requirement {} was already defined in derived resource (case insensitive). Ignore {} from resource {}", reqName, reqName, resourceId); } else { requirements.put(reqName, requirementDefinition); caseInsensitiveReqNames.add(reqName.toLowerCase()); @@ -1567,12 +1320,10 @@ public class RequirementOperation implements IRequirementOperation { } public StorageOperationStatus deleteRequirementFromGraph(String requirementId) { - log.debug("Before deleting requirement from graph " + requirementId); - Either<RequirementData, TitanOperationStatus> deleteNodeStatus = titanGenericDao.deleteNode( - UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Requirement), requirementId, RequirementData.class); + log.debug("Before deleting requirement from graph {}", requirementId); + Either<RequirementData, TitanOperationStatus> deleteNodeStatus = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Requirement), requirementId, RequirementData.class); if (deleteNodeStatus.isRight()) { - log.error("failed to delete requirement with id {}. status={}", requirementId, - deleteNodeStatus.right().value()); + log.error("failed to delete requirement with id {}. status={}", requirementId, deleteNodeStatus.right().value()); return DaoStatusConverter.convertTitanStatusToStorageStatus(deleteNodeStatus.right().value()); } return StorageOperationStatus.OK; @@ -1584,18 +1335,16 @@ public class RequirementOperation implements IRequirementOperation { } - public Either<Map<String, RequirementDefinition>, StorageOperationStatus> deleteAllRequirements(String resourceId, - boolean inTransaction) { + public Either<Map<String, RequirementDefinition>, StorageOperationStatus> deleteAllRequirements(String resourceId, boolean inTransaction) { Either<Map<String, RequirementDefinition>, StorageOperationStatus> result = null; try { - Either<Map<String, RequirementDefinition>, TitanOperationStatus> deleteAllRes = deleteAllRequirementsOfResource( - resourceId); + Either<Map<String, RequirementDefinition>, TitanOperationStatus> deleteAllRes = deleteAllRequirementsOfResource(resourceId); if (deleteAllRes.isRight()) { TitanOperationStatus status = deleteAllRes.right().value(); if (status != TitanOperationStatus.NOT_FOUND) { - log.error("Failed to delete requirements of resource " + resourceId + ". status is " + status); + log.error("Failed to delete requirements of resource {}. status is {}", resourceId, status); } result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); return result; @@ -1620,13 +1369,11 @@ public class RequirementOperation implements IRequirementOperation { } - public Either<Map<String, RequirementDefinition>, TitanOperationStatus> deleteAllRequirementsOfResource( - String resourceId) { + public Either<Map<String, RequirementDefinition>, TitanOperationStatus> deleteAllRequirementsOfResource(String resourceId) { Map<String, RequirementDefinition> requirements = new HashMap<String, RequirementDefinition>(); Set<String> caseInsensitiveReqNames = new HashSet<>(); - TitanOperationStatus requirementsRes = findAllRequirementsNonRecursive(resourceId, requirements, - caseInsensitiveReqNames); + TitanOperationStatus requirementsRes = findAllRequirementsNonRecursive(resourceId, requirements, caseInsensitiveReqNames); if (requirementsRes != TitanOperationStatus.OK) { return Either.right(requirementsRes); } @@ -1640,11 +1387,10 @@ public class RequirementOperation implements IRequirementOperation { String requirementUid = requirementDefinition.getUniqueId(); - Either<RequirementData, TitanOperationStatus> deleteNodeRes = titanGenericDao.deleteNode( - UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Requirement), requirementUid, RequirementData.class); + Either<RequirementData, TitanOperationStatus> deleteNodeRes = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Requirement), requirementUid, RequirementData.class); if (deleteNodeRes.isRight()) { TitanOperationStatus status = deleteNodeRes.right().value(); - log.error("Failed to delete requirement " + requirementUid + " of resource " + resourceId); + log.error("Failed to delete requirement {} of resource ", requirementUid, resourceId); return Either.right(status); } } @@ -1653,8 +1399,7 @@ public class RequirementOperation implements IRequirementOperation { } - public Map<String, List<RequirementDefinition>> convertRequirementMap( - Map<String, RequirementDefinition> requirementMap, String ownerId, String ownerName) { + public Map<String, List<RequirementDefinition>> convertRequirementMap(Map<String, RequirementDefinition> requirementMap, String ownerId, String ownerName) { Map<String, List<RequirementDefinition>> typeToRequirementMap = new HashMap<String, List<RequirementDefinition>>(); requirementMap.forEach((reqName, requirement) -> { diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ResourceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ResourceOperation.java index 22c693d8b3..4dce650f18 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ResourceOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ResourceOperation.java @@ -21,6 +21,7 @@ package org.openecomp.sdc.be.model.operations.impl; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; @@ -33,6 +34,8 @@ import java.util.function.Predicate; import java.util.regex.Pattern; import java.util.stream.Collectors; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.openecomp.sdc.be.config.BeEcompErrorManager; @@ -79,14 +82,19 @@ import org.openecomp.sdc.be.model.operations.api.IAttributeOperation; import org.openecomp.sdc.be.model.operations.api.IElementOperation; import org.openecomp.sdc.be.model.operations.api.IResourceOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.migration.MigrationErrorInformer; import org.openecomp.sdc.be.model.operations.utils.GraphDeleteUtil; import org.openecomp.sdc.be.resources.data.ComponentMetadataData; +import org.openecomp.sdc.be.resources.data.PropertyData; import org.openecomp.sdc.be.resources.data.ResourceMetadataData; import org.openecomp.sdc.be.resources.data.TagData; import org.openecomp.sdc.be.resources.data.UniqueIdData; import org.openecomp.sdc.be.resources.data.UserData; import org.openecomp.sdc.be.resources.data.category.CategoryData; import org.openecomp.sdc.be.resources.data.category.SubCategoryData; +import org.openecomp.sdc.common.api.ArtifactTypeEnum; +import org.openecomp.sdc.common.datastructure.Wrapper; +import org.openecomp.sdc.common.util.PairUtils; import org.openecomp.sdc.common.util.ValidationUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -97,9 +105,11 @@ import com.google.gson.GsonBuilder; import com.thinkaurelius.titan.core.TitanGraph; import com.thinkaurelius.titan.core.TitanVertex; +import fj.Function; import fj.data.Either; @org.springframework.stereotype.Component("resource-operation") +@Deprecated public class ResourceOperation extends ComponentOperation implements IResourceOperation { public ResourceOperation() { @@ -139,8 +149,8 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp private GraphDeleteUtil graphDeleteUtil = new GraphDeleteUtil(); - private static Pattern uuidNewVersion = Pattern.compile("^\\d{1,}.1"); - private static Pattern uuidNormativeNewVersion = Pattern.compile("^\\d{1,}.0"); + public static Pattern uuidNewVersion = Pattern.compile("^\\d{1,}.1"); + public static Pattern uuidNormativeNewVersion = Pattern.compile("^\\d{1,}.0"); @Override public Either<Resource, StorageOperationStatus> createResource(Resource resource) { @@ -169,19 +179,18 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp if (findUser.isRight()) { TitanOperationStatus status = findUser.right().value(); - log.error("Cannot find user " + userId + " in the graph. status is " + status); + log.error("Cannot find user {} in the graph. status is {}", userId, status); return sendError(status, StorageOperationStatus.USER_NOT_FOUND); } TitanVertex creatorVertex = findUser.left().value(); TitanVertex updaterVertex = creatorVertex; - String updaterUserId = resource.getLastUpdaterUserId(); if (updaterUserId != null && !updaterUserId.equals(userId)) { findUser = findUserVertex(updaterUserId); if (findUser.isRight()) { TitanOperationStatus status = findUser.right().value(); - log.error("Cannot find user " + userId + " in the graph. status is " + status); + log.error("Cannot find user {} in the graph. status is {}", userId, status); return sendError(status, StorageOperationStatus.USER_NOT_FOUND); } else { updaterVertex = findUser.left().value(); @@ -232,8 +241,8 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp result = Either.right(associateCategory); return result; } - - TitanOperationStatus associateProperties = associatePropertiesToResource(metadataVertex, resourceUniqueId, resource.getProperties()); + + TitanOperationStatus associateProperties = associatePropertiesToResource(metadataVertex, resourceUniqueId, resource.getProperties(), derivedResources); if (associateProperties != TitanOperationStatus.OK) { result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(associateProperties)); return result; @@ -302,13 +311,13 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp result = this.getResource(resourceUniqueId, true); if (result.isRight()) { - log.error("Cannot get full resource from the graph. status is " + result.right().value()); + log.error("Cannot get full resource from the graph. status is {}", result.right().value()); return Either.right(result.right().value()); } if (log.isDebugEnabled()) { String json = prettyJson.toJson(result.left().value()); - log.debug("Resource retrieved is " + json); + log.debug("Resource retrieved is {}", json); } return result; @@ -335,7 +344,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp Either<CategoryData, StorageOperationStatus> categoryResult = elementOperation.getNewCategoryData(categoryName, NodeTypeEnum.ResourceNewCategory, CategoryData.class); if (categoryResult.isRight()) { StorageOperationStatus status = categoryResult.right().value(); - log.error("Cannot find category " + categoryName + " in the graph. status is " + status); + log.error("Cannot find category {} in the graph. status is {}", categoryName, status); return categoryResult.right().value(); } categoryData = categoryResult.left().value(); @@ -343,16 +352,16 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceNewCategory), (String) categoryData.getUniqueId(), GraphEdgeLabels.SUB_CATEGORY, NodeTypeEnum.ResourceSubcategory, SubCategoryData.class); if (childrenNodes.isRight()) { - log.debug("Faield to fetch sub categories for resource category" + categoryData.getCategoryDataDefinition().getName()); + log.debug("Faield to fetch sub categories for resource category {}", categoryData.getCategoryDataDefinition().getName()); return DaoStatusConverter.convertTitanStatusToStorageStatus(childrenNodes.right().value()); } for (ImmutablePair<SubCategoryData, GraphEdge> pair : childrenNodes.left().value()) { SubCategoryData subcategoryData = pair.left; if (subcategoryData.getSubCategoryDataDefinition().getName().equals(subcategoryName)) { Either<GraphRelation, TitanOperationStatus> result = titanGenericDao.createRelation(resourceData, subcategoryData, GraphEdgeLabels.CATEGORY, null); - log.debug("After associating resource " + resourceData.getUniqueId() + " to subcategory " + subcategoryData + ". Edge type is " + GraphEdgeLabels.CATEGORY); + log.debug("After associating resource {} to subcategory {}. Edge type is {}", resourceData.getUniqueId(), subcategoryData, GraphEdgeLabels.CATEGORY); if (result.isRight()) { - log.error("Faield to associate resource " + resourceData.getUniqueId() + " to category " + categoryData + ". Edge type is " + GraphEdgeLabels.CATEGORY); + log.error("Faield to associate resource {} to category {}. Edge type is {}", resourceData.getUniqueId(), categoryData, GraphEdgeLabels.CATEGORY); return DaoStatusConverter.convertTitanStatusToStorageStatus(result.right().value()); } @@ -492,15 +501,34 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp StorageOperationStatus status = StorageOperationStatus.OK; if (artifacts != null) { + Map<ArtifactDefinition, ArtifactDefinition> heatEnvMap = new HashMap<ArtifactDefinition, ArtifactDefinition>(); for (Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) { ArtifactDefinition artifactDefinition = entry.getValue(); - status = artifactOperation.addArifactToComponent(artifactDefinition, resourceId, NodeTypeEnum.Resource, false, metadataVertex); + + ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactDefinition.getArtifactType()); + if(artifactType != ArtifactTypeEnum.HEAT_ENV){ + status = artifactOperation.addArifactToComponent(artifactDefinition, resourceId, NodeTypeEnum.Resource, false, metadataVertex); + }else{ + Optional<ArtifactDefinition> op = artifacts.values().stream().filter(p -> p.getUniqueId().equals(artifactDefinition.getGeneratedFromId())).findAny(); + if(op.isPresent()){ + heatEnvMap.put(artifactDefinition, op.get()); + } + + + } if (!status.equals(StorageOperationStatus.OK)) { return status; } } + for(Entry<ArtifactDefinition, ArtifactDefinition> entry : heatEnvMap.entrySet()){ + Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = artifactOperation.addHeatEnvArtifact(entry.getKey(), entry.getValue(), resourceId, NodeTypeEnum.Resource, false); + if (addHeatEnvArtifact.isRight()) { + log.debug("failed to create heat env artifact on resource instance"); + return addHeatEnvArtifact.right().value(); + } + } } return status; @@ -539,7 +567,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp } } - private TitanOperationStatus associatePropertiesToResource(TitanVertex metadatVertex, String resourceId, List<PropertyDefinition> properties) { + private TitanOperationStatus associatePropertiesToResource(TitanVertex metadatVertex, String resourceId, List<PropertyDefinition> properties, List<ResourceMetadataData> derivedResources) { Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = applicationDataTypeCache.getAll(); if (allDataTypes.isRight()) { @@ -547,21 +575,82 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp log.debug("Cannot find any data type. Status is {}.", status); return status; } - + Map<String, PropertyDefinition> convertedProperties = new HashMap<>(); if (properties != null) { for (PropertyDefinition propertyDefinition : properties) { convertedProperties.put(propertyDefinition.getName(), propertyDefinition); } - TitanOperationStatus operationStatus = propertyOperation.addPropertiesToGraph(metadatVertex, convertedProperties, allDataTypes.left().value(), resourceId); - return operationStatus; + + Either<Map<String, PropertyDefinition>, TitanOperationStatus> getPropertiesOfAllDerivedFromRes = getPropertiesOfAllDerivedFrom(derivedResources); + + if(getPropertiesOfAllDerivedFromRes.isRight()){ + TitanOperationStatus status = getPropertiesOfAllDerivedFromRes.right().value(); + log.debug("Cannot fetch properties of all derived from resources. Status is {}.", status); + return status; + } + + Map<String, PropertyDefinition> allDerivedFromProperties = getPropertiesOfAllDerivedFromRes.left().value(); + + TitanOperationStatus validatePropertyNamesUniqunessStatus = validatePropertyNamesUniquness(properties, allDerivedFromProperties); + + if(validatePropertyNamesUniqunessStatus != TitanOperationStatus.OK){ + return validatePropertyNamesUniqunessStatus; + } + + return propertyOperation.addPropertiesToGraph(metadatVertex, convertedProperties, allDataTypes.left().value(), resourceId); } return TitanOperationStatus.OK; } + private TitanOperationStatus validatePropertyNamesUniquness(List<PropertyDefinition> properties, Map<String, PropertyDefinition> allDerivedFromProperties) { + + TitanOperationStatus result = TitanOperationStatus.OK; + Optional<PropertyDefinition> propertyOptional= properties.stream() + //filters out properties with the same name and different type + .filter(prop -> allDerivedFromProperties.containsKey(prop.getName()) && !prop.getType().equals(allDerivedFromProperties.get(prop.getName()).getType())) + //Searches for any matching value + .findAny(); + if(propertyOptional.isPresent()){ + log.error("Property with name {} and type {} already exists in derived from resource. ", propertyOptional.get().getName(), allDerivedFromProperties.get( propertyOptional.get().getName()).getType()); + result = TitanOperationStatus.ALREADY_EXIST; + } + return result; + } + + private Either<Map<String, PropertyDefinition>, TitanOperationStatus> getPropertiesOfAllDerivedFrom(List<ResourceMetadataData> derivedResources) { + Map<String, PropertyDefinition> allDerivedProperties = new HashMap<>(); + Either<Map<String, PropertyDefinition>, TitanOperationStatus> getPropertiesOfAllDerivedFromRes = Either.left(allDerivedProperties); + String currResourceName = null ; + if(!CollectionUtils.isEmpty(derivedResources)){ + try{ + for(int i = derivedResources.size() - 1; i >= 0 ; --i){ + ResourceMetadataData currDerivedResource = derivedResources.get(i); + currResourceName = currDerivedResource.getMetadataDataDefinition().getName(); + Either<List<ImmutablePair<PropertyData, GraphEdge>>, TitanOperationStatus> res = + titanGenericDao.getChildrenNodes( currDerivedResource.getUniqueIdKey(), (String)currDerivedResource.getUniqueId(), GraphEdgeLabels.PROPERTY, NodeTypeEnum.Property, PropertyData.class); + if(res.isRight() && res.right().value() != TitanOperationStatus.NOT_FOUND){ + getPropertiesOfAllDerivedFromRes = Either.right(res.right().value()); + break; + }else if(res.isLeft()){ + allDerivedProperties.putAll(res.left().value().stream() + //Maps PropertyData converted to PropertyDefinition + .map(pair-> propertyOperation.convertPropertyDataToPropertyDefinition(pair.getLeft(), (String)pair.getRight().getProperties().get(GraphPropertiesDictionary.NAME.getProperty()), (String)currDerivedResource.getUniqueId())) + //and collects it to a map + .collect(Collectors.toMap(entry->entry.getName(), entry->entry))); + } + } + } + catch(Exception e){ + log.error("Exception occured during fetch properties of resource {}. ", currResourceName); + } + } + return getPropertiesOfAllDerivedFromRes; + } + private TitanOperationStatus associateAttributesToResource(TitanVertex metadataVertex, List<AttributeDefinition> attributes, String resourceId) { TitanOperationStatus operationStatus = TitanOperationStatus.OK; @@ -605,7 +694,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp // TODO Evg : need to change too.. if (derivedResources != null) { for (ResourceMetadataData derivedResource : derivedResources) { - log.debug("After associating resource " + resourceData.getUniqueId() + " to parent resource " + derivedResource.getUniqueId() + ". Edge type is " + GraphEdgeLabels.DERIVED_FROM); + log.debug("After associating resource {} to parent resource {}. Edge type is {}", resourceData.getUniqueId(), derivedResource.getUniqueId(), GraphEdgeLabels.DERIVED_FROM); Either<GraphRelation, TitanOperationStatus> createRelationResult = titanGenericDao.createRelation(resourceData, derivedResource, GraphEdgeLabels.DERIVED_FROM, null); if (createRelationResult.isRight()) { log.error("Failed to associate resource {} to derived ", resourceData.getUniqueId()); @@ -636,26 +725,27 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp List<ResourceMetadataData> resources = null; if (getParentResources.isRight()) { /* - * log.debug( "Cannot find parent resource by tosca resource name" + parentResource + " in the graph. Try to find by name"); Map<String, Object> propertiesWithResourceNameToMatch = new HashMap<String, Object>(); + * log.debug( "Cannot find parent resource by tosca resource name {} in the graph. Try to find by name", parentResource); + * Map<String, Object> propertiesWithResourceNameToMatch = new HashMap<String, Object>(); * propertiesWithResourceNameToMatch.put( GraphPropertiesDictionary.STATE.getProperty(), LifecycleStateEnum.CERTIFIED.name()); propertiesWithResourceNameToMatch.put( GraphPropertiesDictionary.NAME.getProperty(), parentResource); * propertiesWithResourceNameToMatch.put( GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty( ), true); * * getParentResources = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, propertiesWithResourceNameToMatch, ResourceData.class); if (getParentResources.isRight()) { log.error( * "Cannot find parent resource by tosca resource name" + parentResource + " in the graph."); return Either.right(StorageOperationStatus. PARENT_RESOURCE_NOT_FOUND); }else{ resources = getParentResources.left().value(); - * + * hea * } */ - log.error("Cannot find parent resource by tosca resource name" + parentResource + " in the graph."); + 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 tosc name" + parentResource + " in the graph. resources size is empty"); + log.error("Cannot find parent resource by tosc name {} in the graph. resources size is empty", parentResource); return Either.right(StorageOperationStatus.PARENT_RESOURCE_NOT_FOUND); } else { if (resources.size() > 1) { - log.error("Multiple parent resources called " + parentResource + " found in the graph."); + log.error("Multiple parent resources called {} found in the graph.", parentResource); return Either.right(StorageOperationStatus.MULTIPLE_PARENT_RESOURCE_FOUND); } ResourceMetadataData parentResourceData = resources.get(0); @@ -714,133 +804,6 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp return getResource(uniqueId, componentParametersView, inTransaction); } - // public Either<Resource, StorageOperationStatus> getResource(String - // uniqueId, boolean inTransaction) { - // - // Resource resource = null; - // try { - // - // NodeTypeEnum resourceNodeType = NodeTypeEnum.Resource; - // NodeTypeEnum compInstNodeType = NodeTypeEnum.Resource; - // - // Either<ResourceMetadataData, StorageOperationStatus> - // componentByLabelAndId = getComponentByLabelAndId(uniqueId, - // resourceNodeType, ResourceMetadataData.class); - // if (componentByLabelAndId.isRight()) { - // return Either.right(componentByLabelAndId.right().value()); - // } - // ResourceMetadataData resourceData = componentByLabelAndId.left().value(); - // resource = convertResourceDataToResource(resourceData); - // - // TitanOperationStatus status = setResourceCreatorFromGraph(resource, - // uniqueId); - // if (status != TitanOperationStatus.OK) { - // return - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // } - // - // status = setResourceLastModifierFromGraph(resource, uniqueId); - // if (status != TitanOperationStatus.OK) { - // return - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // } - // - // status = setResourcePropertiesFromGraph(uniqueId, resource); - // if (status != TitanOperationStatus.OK) { - // return - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // } - // - // status = setResourceAttributesFromGraph(uniqueId, resource); - // if (status != TitanOperationStatus.OK) { - // return - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // } - // - // status = setResourceDerivedFromGraph(uniqueId, resource); - // if (status != TitanOperationStatus.OK) { - // return - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // } - // - // status = setComponentCategoriesFromGraph(resource); - // if (status != TitanOperationStatus.OK) { - // return - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // } - // - // status = setComponentInstancesFromGraph(uniqueId, resource, - // resourceNodeType, compInstNodeType); - // if (status != TitanOperationStatus.OK) { - // return - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // - // } - // - // StorageOperationStatus setRequirementsStatus = - // setResourceRequirementsFromGraph(uniqueId, resource, true); - // if (setRequirementsStatus != StorageOperationStatus.OK) { - // log.error("Failed to set requirement of resource " + uniqueId + ". status - // is " + setRequirementsStatus); - // return Either.right(setRequirementsStatus); - // } - // - // StorageOperationStatus storageStatus = - // setResourceCapabilitiesFromGraph(uniqueId, resource); - // if (storageStatus != StorageOperationStatus.OK) { - // return Either.right(storageStatus); - // } - // - // storageStatus = setArtifactFromGraph(uniqueId, resource); - // if (storageStatus != StorageOperationStatus.OK) { - // return Either.right(storageStatus); - // } - // - // status = setComponentInstancesAttributesFromGraph(uniqueId, resource); - // if (status != TitanOperationStatus.OK) { - // return - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // - // } - // - // status = setComponentInstancesPropertiesFromGraph(uniqueId, resource); - // if (status != TitanOperationStatus.OK) { - // return - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // - // } - // - // storageStatus = setResourceInterfacesFromGraph(uniqueId, resource); - // if (storageStatus != StorageOperationStatus.OK) { - // return Either.right(storageStatus); - // } - // - // storageStatus = setResourceAdditionalInformationFromGraph(uniqueId, - // resource); - // if (storageStatus != StorageOperationStatus.OK) { - // return Either.right(storageStatus); - // } - // status = setAllVersions(resource); - // if (status != TitanOperationStatus.OK) { - // return - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // } - // - // status = setGroupsFromGraph(uniqueId, resource, NodeTypeEnum.Resource); - // if (status != TitanOperationStatus.OK) { - // return - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // } - // - // } finally { - // if (false == inTransaction) { - // titanGenericDao.commit(); - // } - // } - // - // return Either.left(resource); - // } - private TitanOperationStatus setComponentInstancesAttributesFromGraph(String uniqueId, Resource component) { Map<String, List<ComponentInstanceAttribute>> resourceInstancesAttributes = new HashMap<>(); TitanOperationStatus status = TitanOperationStatus.OK; @@ -863,114 +826,6 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp } - // public Either<Resource, StorageOperationStatus> getResource_tx(String - // uniqueId, boolean inTransaction) { - // - // Resource resource = null; - // try { - // - // NodeTypeEnum resourceNodeType = NodeTypeEnum.Resource; - // NodeTypeEnum compInstNodeType = NodeTypeEnum.Resource; - // - // Either<ResourceMetadataData, StorageOperationStatus> - // componentByLabelAndId = getComponentByLabelAndId_tx(uniqueId, - // resourceNodeType, ResourceMetadataData.class); - // if (componentByLabelAndId.isRight()) { - // return Either.right(componentByLabelAndId.right().value()); - // } - // ResourceMetadataData resourceData = componentByLabelAndId.left().value(); - // resource = convertResourceDataToResource(resourceData); - // - // TitanOperationStatus status = setResourceCreatorFromGraph(resource, - // uniqueId); - // if (status != TitanOperationStatus.OK) { - // return - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // } - // - // status = setResourceLastModifierFromGraph(resource, uniqueId); - // if (status != TitanOperationStatus.OK) { - // return - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // } - // - // status = setResourcePropertiesFromGraph(uniqueId, resource); - // if (status != TitanOperationStatus.OK) { - // return - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // } - // - // status = setResourceDerivedFromGraph(uniqueId, resource); - // if (status != TitanOperationStatus.OK) { - // return - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // } - // - // status = setComponentCategoriesFromGraph(resource); - // if (status != TitanOperationStatus.OK) { - // return - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // } - // - // status = setComponentInstancesFromGraph(uniqueId, resource, - // resourceNodeType, compInstNodeType); - // if (status != TitanOperationStatus.OK) { - // return - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // - // } - // - // StorageOperationStatus setRequirementsStatus = - // setResourceRequirementsFromGraph(uniqueId, resource, true); - // if (setRequirementsStatus != StorageOperationStatus.OK) { - // log.error("Failed to set requirement of resource " + uniqueId + ". status - // is " + setRequirementsStatus); - // return Either.right(setRequirementsStatus); - // } - // - // StorageOperationStatus storageStatus = - // setResourceCapabilitiesFromGraph(uniqueId, resource); - // if (storageStatus != StorageOperationStatus.OK) { - // return Either.right(storageStatus); - // } - // - // storageStatus = setArtifactFromGraph(uniqueId, resource); - // if (storageStatus != StorageOperationStatus.OK) { - // return Either.right(storageStatus); - // } - // - // status = setComponentInstancesPropertiesFromGraph(uniqueId, resource); - // if (status != TitanOperationStatus.OK) { - // return - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // - // } - // - // storageStatus = setResourceInterfacesFromGraph(uniqueId, resource); - // if (storageStatus != StorageOperationStatus.OK) { - // return Either.right(storageStatus); - // } - // - // storageStatus = setResourceAdditionalInformationFromGraph(uniqueId, - // resource); - // if (storageStatus != StorageOperationStatus.OK) { - // return Either.right(storageStatus); - // } - // status = setAllVersions(resource); - // if (status != TitanOperationStatus.OK) { - // return - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // } - // - // } finally { - // if (false == inTransaction) { - // titanGenericDao.commit(); - // } - // } - // - // return Either.left(resource); - // } - private StorageOperationStatus setResourceAdditionalInformationFromGraph(String uniqueId, Resource resource) { List<AdditionalInformationDefinition> additionalInformation = new ArrayList<>(); @@ -1019,7 +874,11 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp } } else { Map<String, CapabilityDefinition> capabilities = result.left().value(); - if (capabilities == null || capabilities.isEmpty()) { + if (capabilities != null && !capabilities.isEmpty() && resource.getResourceType().equals(ResourceTypeEnum.VF)) { + log.error(String.format("VF %s has direct capabilities.!!!!!!!!!!!!!", resource.getName())); + MigrationErrorInformer.addMalformedVF(resource.getUniqueId()); + } + if (capabilities == null || capabilities.isEmpty() || resource.getResourceType().equals(ResourceTypeEnum.VF)) { Either<Map<String, List<CapabilityDefinition>>, TitanOperationStatus> eitherCapabilities = super.getCapabilities(resource, NodeTypeEnum.Resource, true); if (eitherCapabilities.isLeft()) { retStatus = StorageOperationStatus.OK; @@ -1086,7 +945,11 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp } } else { Map<String, RequirementDefinition> requirements = result.left().value(); - if (requirements == null || requirements.isEmpty()) { + if (requirements != null && !requirements.isEmpty() && resource.getResourceType().equals(ResourceTypeEnum.VF)) { + log.error(String.format("VF %s has direct requirements.!!!!!!!!!!!!!", resource.getName())); + MigrationErrorInformer.addMalformedVF(resource.getUniqueId()); + } + if (requirements == null || requirements.isEmpty() || resource.getResourceType() == ResourceTypeEnum.VF) { Either<Map<String, List<RequirementDefinition>>, TitanOperationStatus> eitherCapabilities = super.getRequirements(resource, NodeTypeEnum.Resource, true); if (eitherCapabilities.isLeft()) { retStatus = StorageOperationStatus.OK; @@ -1197,10 +1060,8 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp log.debug("Found parent node {}", value); UserData userData = value.getKey(); - if (log.isDebugEnabled()) { + if (log.isDebugEnabled()) log.debug("Build resource : set last modifier userId to {}", userData.getUserId()); - } - String fullName = buildFullName(userData); if (log.isDebugEnabled()) log.debug("Build resource : set last modifier full name to {}", fullName); @@ -1222,9 +1083,8 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp if (log.isDebugEnabled()) log.debug("Found parent node {}", value); UserData userData = value.getKey(); - if (log.isDebugEnabled()) { + if (log.isDebugEnabled()) log.debug("Build resource : set creator userId to {}", userData.getUserId()); - } String fullName = buildFullName(userData); if (log.isDebugEnabled()) log.debug("Build resource : set creator full name to {}", fullName); @@ -1310,7 +1170,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp propertiesToMatch.put(GraphPropertiesDictionary.NAME.getProperty(), resourceName); Either<List<ResourceMetadataData>, TitanOperationStatus> getParentResources = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, propertiesToMatch, ResourceMetadataData.class); - log.debug("result after searching for resources called " + resourceName + " is " + getParentResources); + log.debug("result after searching for resources called {} is {}", resourceName, getParentResources); if (getParentResources.isRight()) { TitanOperationStatus titanStatus = getParentResources.right().value(); if (titanStatus == TitanOperationStatus.NOT_FOUND) { @@ -1321,7 +1181,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp } else { List<ResourceMetadataData> value = getParentResources.left().value(); int numberOFResources = (value == null ? 0 : value.size()); - log.debug("The number of resources returned after searching for resource called " + resourceName + " is " + numberOFResources); + log.debug("The number of resources returned after searching for resource called {} is {}", resourceName, numberOFResources); return Either.left(numberOFResources); } } @@ -1418,67 +1278,67 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp if (iterator != null && iterator.hasNext()) { Vertex rootVertex = iterator.next(); TitanOperationStatus deleteChildrenNodes = graphDeleteUtil.deleteChildrenNodes(rootVertex, GraphEdgeLabels.PROPERTY); - log.debug("After deleting properties nodes in the graph. status is " + deleteChildrenNodes); + log.debug("After deleting properties nodes in the graph. status is {}", deleteChildrenNodes); if (deleteChildrenNodes != TitanOperationStatus.OK) { result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(deleteChildrenNodes)); return result; } StorageOperationStatus removeInterfacesFromResource = removeInterfacesFromResource(resource); - log.debug("After deleting interfaces nodes in the graph. status is " + removeInterfacesFromResource); + log.debug("After deleting interfaces nodes in the graph. status is {}", removeInterfacesFromResource); if (!removeInterfacesFromResource.equals(StorageOperationStatus.OK)) { result = Either.right(removeInterfacesFromResource); return result; } StorageOperationStatus removeArtifactsFromResource = removeArtifactsFromResource(resource); - log.debug("After deleting artifacts nodes in the graph. status is " + removeArtifactsFromResource); + log.debug("After deleting artifacts nodes in the graph. status is {}", removeArtifactsFromResource); if (!removeArtifactsFromResource.equals(StorageOperationStatus.OK)) { result = Either.right(removeArtifactsFromResource); return result; } StorageOperationStatus removeCapabilitiesFromResource = removeCapabilitiesFromResource(resource); - log.debug("After deleting capabilities nodes in the graph. status is " + removeCapabilitiesFromResource); + log.debug("After deleting capabilities nodes in the graph. status is {}", removeCapabilitiesFromResource); if (!removeCapabilitiesFromResource.equals(StorageOperationStatus.OK)) { result = Either.right(removeCapabilitiesFromResource); return result; } StorageOperationStatus removeRequirementsFromResource = removeRequirementsFromResource(resource); - log.debug("After deleting requirements nodes in the graph. status is " + removeRequirementsFromResource); + log.debug("After deleting requirements nodes in the graph. status is {}", removeRequirementsFromResource); if (!removeRequirementsFromResource.equals(StorageOperationStatus.OK)) { result = Either.right(removeRequirementsFromResource); return result; } StorageOperationStatus removeRIsFromResource = removeResourceInstanceFromResource(resource); - log.debug("After deleting resource instance nodes in the graph. status is " + removeRIsFromResource); + log.debug("After deleting resource instance nodes in the graph. status is {}", removeRIsFromResource); if (!removeRIsFromResource.equals(StorageOperationStatus.OK)) { result = Either.right(removeRIsFromResource); return result; } StorageOperationStatus removeAttributesFromResource = removeAttributesFromResource(resource); - log.debug("After deleting requirements nodes in the graph. status is " + removeRequirementsFromResource); + log.debug("After deleting requirements nodes in the graph. status is {}", removeRequirementsFromResource); if (removeAttributesFromResource != StorageOperationStatus.OK) { result = Either.right(removeAttributesFromResource); return result; } StorageOperationStatus removeInputsFromResource = removeInputsFromComponent(NodeTypeEnum.Resource, resource); - log.debug("After deleting requirements nodes in the graph. status is " + removeInputsFromResource); + log.debug("After deleting requirements nodes in the graph. status is {}", removeInputsFromResource); if (removeInputsFromResource != StorageOperationStatus.OK) { result = Either.right(removeInputsFromResource); return result; } StorageOperationStatus removeAdditionalInformationFromResource = super.deleteAdditionalInformation(NodeTypeEnum.Resource, resource.getUniqueId()); - log.debug("After deleting additional information node in the graph. status is " + removeAdditionalInformationFromResource); + log.debug("After deleting additional information node in the graph. status is {}", removeAdditionalInformationFromResource); if (!removeAdditionalInformationFromResource.equals(StorageOperationStatus.OK)) { result = Either.right(removeAdditionalInformationFromResource); return result; } StorageOperationStatus removeGroupsFromResource = super.deleteGroups(NodeTypeEnum.Resource, resource.getUniqueId()); - log.debug("After deleting group nodes in the graph. status is " + removeGroupsFromResource); + log.debug("After deleting group nodes in the graph. status is {}", removeGroupsFromResource); if (!removeGroupsFromResource.equals(StorageOperationStatus.OK)) { result = Either.right(removeGroupsFromResource); return result; @@ -1698,12 +1558,12 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp categoryRelation.setFrom(relationEndPoint); Either<GraphRelation, TitanOperationStatus> deleteOutgoingRelation = titanGenericDao.deleteOutgoingRelation(categoryRelation); if (deleteOutgoingRelation.isRight()) { - log.error("Failed to delete category from resource " + resourceData.getUniqueId() + ". Edge type is " + GraphEdgeLabels.CATEGORY); + log.error("Failed to delete category from resource {}. Edge type is {}", resourceData.getUniqueId(), GraphEdgeLabels.CATEGORY); result = DaoStatusConverter.convertTitanStatusToStorageStatus(deleteOutgoingRelation.right().value()); return result; } - log.debug("After removing edge from graph " + deleteOutgoingRelation); + log.debug("After removing edge from graph {}", deleteOutgoingRelation); return assosiateMetadataToCategory(resource, resourceData); } @@ -1718,15 +1578,15 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp lastModifierRelation.setTo(relationEndPoint); Either<GraphRelation, TitanOperationStatus> deleteIncomingRelation = titanGenericDao.deleteIncomingRelation(lastModifierRelation); if (deleteIncomingRelation.isRight()) { - log.error("Failed to delete user from resource " + resourceData.getUniqueId() + ". Edge type is " + GraphEdgeLabels.LAST_MODIFIER); + log.error("Failed to delete user from resource {}. Edge type is {}", resourceData.getUniqueId(),GraphEdgeLabels.LAST_MODIFIER); result = DaoStatusConverter.convertTitanStatusToStorageStatus(deleteIncomingRelation.right().value()); return result; } Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(modifierUserData, resourceData, GraphEdgeLabels.LAST_MODIFIER, null); - log.debug("After associating user " + modifierUserData + " to resource " + resourceData.getUniqueId() + ". Edge type is " + GraphEdgeLabels.LAST_MODIFIER); + log.debug("After associating user {} to resource {}. Edge type is {}", modifierUserData, resourceData.getUniqueId(), GraphEdgeLabels.LAST_MODIFIER); if (createRelation.isRight()) { - log.error("Failed to associate user " + modifierUserData + " to resource " + resourceData.getUniqueId() + ". Edge type is " + GraphEdgeLabels.LAST_MODIFIER); + log.error("Failed to associate user {} to resource {}. Edge type is {}", modifierUserData, resourceData.getUniqueId(), GraphEdgeLabels.LAST_MODIFIER); result = DaoStatusConverter.convertTitanStatusToStorageStatus(createRelation.right().value()); return result; } @@ -1783,6 +1643,30 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExists(String templateName) { return validateToscaResourceNameUniqueness(templateName, titanGenericDao); } + + //Tal G for US815447 + public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends) { + + String currentTemplateNameChecked = templateNameExtends; + + while(currentTemplateNameChecked != null && !currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)){ + Either<Resource, StorageOperationStatus> latestByToscaResourceName = getLatestByToscaResourceName(currentTemplateNameChecked, true); + + 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<ArtifactDefinition>, StorageOperationStatus> getAdditionalArtifacts(String resourceId, boolean recursively, boolean inTransaction) { List<ArtifactDefinition> artifacts = new ArrayList<>(); @@ -1798,12 +1682,12 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp for (Entry<String, InterfaceDefinition> entry : interfaces.entrySet()) { InterfaceDefinition interfaceDefinition = entry.getValue(); - Map<String, Operation> operations = interfaceDefinition.getOperations(); + Map<String, Operation> operations = interfaceDefinition.getOperationsMap(); if (operations != null && !operations.isEmpty()) { for (Entry<String, Operation> opEntry : operations.entrySet()) { Operation operation = opEntry.getValue(); - ArtifactDefinition artifactDefinition = operation.getImplementation(); + ArtifactDefinition artifactDefinition = operation.getImplementationArtifact(); if (artifactDefinition != null) { artifacts.add(artifactDefinition); } @@ -1825,6 +1709,13 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp return (Either<T, StorageOperationStatus>) getResource(id, inTransaction); } + // @Override + // public <T> Either<T, StorageOperationStatus> getComponent_tx(String id, + // boolean inTransaction) { + // return (Either<T, StorageOperationStatus>) getResource_tx(id, + // inTransaction); + // } + private Optional<ImmutablePair<SubCategoryData, GraphEdge>> validateCategoryHierarcy(List<ImmutablePair<SubCategoryData, GraphEdge>> childNodes, String subCategoryName) { Predicate<ImmutablePair<SubCategoryData, GraphEdge>> matchName = p -> p.getLeft().getSubCategoryDataDefinition().getName().equals(subCategoryName); return childNodes.stream().filter(matchName).findAny(); @@ -1850,8 +1741,9 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp String subCategoryName = filters.get(FilterKeyEnum.SUB_CATEGORY); String categoryName = filters.get(FilterKeyEnum.CATEGORY); + ResourceTypeEnum resourceType = ResourceTypeEnum.getType( filters.get(FilterKeyEnum.RESOURCE_TYPE)); Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, StorageOperationStatus> subcategories = null; - Optional<ImmutablePair<SubCategoryData, GraphEdge>> subCategoryData = null; + Optional<ImmutablePair<SubCategoryData, GraphEdge>> subCategoryData; if (categoryName != null) { subcategories = getAllSubCategories(categoryName); @@ -1867,20 +1759,59 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp return Either.right(StorageOperationStatus.MATCH_NOT_FOUND); } return fetchByCategoryOrSubCategoryUid((String) subCategoryData.get().getLeft().getUniqueId(), NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource, inTransaction, - ResourceMetadataData.class); + ResourceMetadataData.class, resourceType); } - return fetchByCategoryOrSubCategoryName(subCategoryName, NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource, inTransaction, ResourceMetadataData.class); + return fetchByCategoryOrSubCategoryName(subCategoryName, NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource, inTransaction, ResourceMetadataData.class, resourceType); } - return fetchByMainCategory(subcategories.left().value(), inTransaction); + if(subcategories != null){ + return fetchByMainCategory(subcategories.left().value(), inTransaction, resourceType); + } + return fetchByResourceType(NodeTypeEnum.Resource, filters.get(FilterKeyEnum.RESOURCE_TYPE), ResourceMetadataData.class, inTransaction); } - private <T> Either<List<T>, StorageOperationStatus> fetchByMainCategory(List<ImmutablePair<SubCategoryData, GraphEdge>> subcategories, boolean inTransaction) { + @SuppressWarnings("unchecked") + private <T, S extends ComponentMetadataData> Either<List<T>, StorageOperationStatus> fetchByResourceType(NodeTypeEnum nodeType, String resourceType, + Class<S> clazz, boolean inTransaction) { + List<T> components = null; + TitanOperationStatus status; + Wrapper<StorageOperationStatus> statusWrapper = new Wrapper<>(); + Either<List<T>, StorageOperationStatus> result; + try { + Map<String, Object> props = new HashMap<>(); + props.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), resourceType); + props.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true); + Either<List<S>, TitanOperationStatus> getResources = titanGenericDao.getByCriteria(nodeType, props, clazz); + if (getResources.isRight()) { + status = getResources.right().value(); + if(status != TitanOperationStatus.NOT_FOUND){ + statusWrapper.setInnerElement(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + }else{ + components = new ArrayList<>(); + } + }else{ + components = getResources.left().value().stream(). + map(c->(T)convertComponentMetadataDataToComponent(c)).collect(Collectors.toList()); + } + if(!statusWrapper.isEmpty()){ + result = Either.right(statusWrapper.getInnerElement()); + }else{ + result = Either.left(components); + } + return result; + } finally { + if (!inTransaction) { + titanGenericDao.commit(); + } + } + } + + private <T> Either<List<T>, StorageOperationStatus> fetchByMainCategory(List<ImmutablePair<SubCategoryData, GraphEdge>> subcategories, boolean inTransaction, ResourceTypeEnum resourceType) { List<T> components = new ArrayList<>(); for (ImmutablePair<SubCategoryData, GraphEdge> subCategory : subcategories) { Either<List<T>, StorageOperationStatus> fetched = fetchByCategoryOrSubCategoryUid((String) subCategory.getLeft().getUniqueId(), NodeTypeEnum.ResourceSubcategory, GraphEdgeLabels.SUB_CATEGORY.getProperty(), NodeTypeEnum.Resource, - inTransaction, ResourceMetadataData.class); + inTransaction, ResourceMetadataData.class, resourceType); if (fetched.isRight()) { // return fetched; continue; @@ -1906,6 +1837,52 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp return getComponentCatalogData(NodeTypeEnum.Resource, propertiesToMatch, Resource.class, ResourceMetadataData.class, inTransaction); } + @Override + public Either<List<Resource>, StorageOperationStatus> getAllDerivedResources(Resource resource) { + try { + Either<List<ImmutablePair<ResourceMetadataData, GraphEdge>>, TitanOperationStatus> childrenNodes = getDerivingChildren(resource); + return childrenNodes.either((childrenPairs) -> convertToResources(PairUtils.leftSequence(childrenPairs)), + (status) -> Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status))); + } finally { + titanGenericDao.commit(); + } + } + + @Override + public Either<List<Resource>, StorageOperationStatus> getRootResources() { + Map<String, Object> rootToscaResource = new HashMap<>(); + rootToscaResource.put(GraphPropertiesDictionary.TOSCA_RESOURCE_NAME.getProperty(), Resource.ROOT_RESOURCE); + return getResourceListByCriteria(rootToscaResource, false); + } + + @Override + public Either<List<Resource>, StorageOperationStatus> getVFResources() { + Map<String, Object> rootToscaResource = new HashMap<>(); + rootToscaResource.put(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty(), ResourceTypeEnum.VF); + return getResourceListByCriteria(rootToscaResource, false); + } + + @Override + public Either<List<Resource>, StorageOperationStatus> getAll() { + Either<List<Resource>, StorageOperationStatus> resourceListByCriteria = getResourceListByCriteria(new HashMap<>(), false); + if (resourceListByCriteria.isRight() && resourceListByCriteria.right().value() == StorageOperationStatus.NOT_FOUND) { + return Either.left(Collections.emptyList()); + } + return resourceListByCriteria; + } + + + private Either<List<ImmutablePair<ResourceMetadataData, GraphEdge>>, TitanOperationStatus> getDerivingChildren(Resource resource) { + return titanGenericDao.getParentNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resource.getUniqueId(), GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource, ResourceMetadataData.class); + } + + private Either<List<Resource>, StorageOperationStatus> convertToResources(List<ResourceMetadataData> resourcesMetaData) { + List<Either<Resource, StorageOperationStatus>> resources = resourcesMetaData.stream() + .map(resourceMetaData -> this.getResource(resourceMetaData.getMetadataDataDefinition().getUniqueId())) + .collect(Collectors.toList()); + return Either.sequenceLeft(fj.data.List.iterableList(resources)).bimap(fj.data.List::toJavaList, Function.identity()); + } + protected TitanOperationStatus findResourcesPathRecursively(String resourceId, List<ResourceMetadataData> resourcesPathList) { Either<ResourceMetadataData, TitanOperationStatus> nodeRes = this.titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, ResourceMetadataData.class); @@ -2106,7 +2083,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp } long endFetchAllFromCache = System.currentTimeMillis(); - log.debug("Fetch all catalog resources metadata from cache took " + (endFetchAllFromCache - startFetchAllFromCache) + " ms"); + log.debug("Fetch all catalog resources metadata from cache took {} ms", (endFetchAllFromCache - startFetchAllFromCache)); long startFetchFromGraph = System.currentTimeMillis(); log.debug("The number of resources needed to be fetch as light component is {}", notCertifiedHighest.size()); @@ -2115,13 +2092,13 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp log.trace("Fetch catalog resource non cached {} {}", uniqueId, data.getMetadataDataDefinition().getName()); Either<Resource, StorageOperationStatus> component = getLightComponent(uniqueId, inTransaction); if (component.isRight()) { - log.debug("Failed to get Service for id = " + data.getUniqueId() + " error : " + component.right().value() + " skip resource"); + log.debug("Failed to get Service for id = {} error : {} skip resource", data.getUniqueId(), component.right().value()); } else { result.add(component.left().value()); } } long endFetchFromGraph = System.currentTimeMillis(); - log.debug("Fetch catalog resources from graph took " + (endFetchFromGraph - startFetchFromGraph) + " ms"); + log.debug("Fetch catalog resources from graph took {} ms", (endFetchFromGraph - startFetchFromGraph)); return Either.left(result); @@ -2141,7 +2118,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp return getResourceCatalogDataLatestCertifiedAndNonCertified(inTransaction, propertiesToMatch); } - private Either<List<Resource>, StorageOperationStatus> getResourceCatalogDataLatestCertifiedAndNonCertified(boolean inTransaction, Map<String, Object> otherToMatch) { + public Either<List<Resource>, StorageOperationStatus> getResourceCatalogDataLatestCertifiedAndNonCertified(boolean inTransaction, Map<String, Object> otherToMatch) { Map<String, Object> propertiesToMatch = new HashMap<>(); if (otherToMatch != null) { @@ -2169,7 +2146,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp for (ResourceMetadataData data : listOfHighest) { Either<Resource, StorageOperationStatus> component = getLightComponent(data.getMetadataDataDefinition().getUniqueId(), inTransaction); if (component.isRight()) { - log.debug("Failed to get Service for id = " + data.getUniqueId() + " error : " + component.right().value() + " skip resource"); + log.debug("Failed to get Service for id = {} error : {} skip resource", data.getUniqueId(), component.right().value()); } else { result.add(component.left().value()); } @@ -2193,7 +2170,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp if (resource.isLeft()) { resources.add(resource.left().value()); } else { - log.debug("Failed to fetch resource for name = " + data.getMetadataDataDefinition().getName() + " and id = " + data.getUniqueId()); + log.debug("Failed to fetch resource for name = {} and id = {}", data.getUniqueId(), data.getMetadataDataDefinition().getName()); } } return Either.left(resources); @@ -2253,16 +2230,11 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp } List<ResourceMetadataData> dataList = byCriteria.left().value(); if (dataList != null && !dataList.isEmpty()) { - // if (dataList.size() > 1) { - // log.debug("More that one instance of resource for name =" + - // nameValue + " and version = " + version); - // return Either.right(StorageOperationStatus.GENERAL_ERROR); - // } for (ResourceMetadataData resourceData : dataList) { // ResourceMetadataData resourceData = dataList.get(0); Either<Resource, StorageOperationStatus> resource = getResource(resourceData.getMetadataDataDefinition().getUniqueId(), inTransaction); if (resource.isRight()) { - log.debug("Failed to fetch resource for name = " + resourceData.getMetadataDataDefinition().getName() + " and id = " + resourceData.getUniqueId()); + log.debug("Failed to fetch resource for name = {} and id = {}", resourceData.getMetadataDataDefinition().getName(), resourceData.getUniqueId()); return Either.right(resource.right().value()); } resourcesList.add(resource.left().value()); @@ -2287,7 +2259,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp } List<Resource> resourcesList = byNamesAndVersion.left().value(); if (resourcesList.size() > 1) { - log.debug("More that one instance of resource for name =" + name + " and version = " + version); + log.debug("More that one instance of resource for name = {} and version = {}", name, version); return Either.right(StorageOperationStatus.GENERAL_ERROR); } return Either.left(resourcesList.get(0)); @@ -2345,7 +2317,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp try { - log.debug("In updateResource. received resource = " + (resource == null ? null : resource.toString())); + log.debug("In updateResource. received resource = {}", (resource == null ? null : resource.toString())); if (resource == null) { log.error("Resource object is null"); result = Either.right(StorageOperationStatus.BAD_REQUEST); @@ -2355,7 +2327,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp ResourceMetadataData resourceData = new ResourceMetadataData(); resourceData.getMetadataDataDefinition().setUniqueId(resource.getUniqueId()); resourceData.getMetadataDataDefinition().setHighestVersion(resource.isHighestVersion()); - log.debug("After converting resource to ResourceData. ResourceData = " + resourceData); + log.debug("After converting resource to ResourceData. ResourceData = {}", resourceData); if (resourceData.getUniqueId() == null) { log.error("Resource id is missing in the request."); @@ -2365,14 +2337,14 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp Either<ResourceMetadataData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(resourceData, ResourceMetadataData.class); if (updateNode.isRight()) { - log.error("Failed to update resource " + resource.getUniqueId() + ". status is " + updateNode.right().value()); + log.error("Failed to update resource {}. status is {}", resource.getUniqueId(), updateNode.right().value()); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value())); return result; } Either<Resource, StorageOperationStatus> updatedResource = getResource(resource.getUniqueId(), true); if (updatedResource.isRight()) { - log.error("Resource id is missing in the request. status is " + updatedResource.right().value()); + log.error("Resource id is missing in the request. status is {}", updatedResource.right().value()); result = Either.right(StorageOperationStatus.BAD_REQUEST); return result; } @@ -2382,7 +2354,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp if (log.isDebugEnabled()) { String json = prettyJson.toJson(result.left().value()); - log.debug("Resource retrieved after update is " + json); + log.debug("Resource retrieved after update is {}", json); } return result; @@ -2430,7 +2402,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp for (ResourceMetadataData resourceData : resourceDataList) { Either<Resource, StorageOperationStatus> resource = getResource(resourceData.getMetadataDataDefinition().getUniqueId()); if (resource.isRight()) { - log.debug("Failed to fetch resource for id = " + resourceData.getUniqueId() + " error is " + resource.right().value()); + log.debug("Failed to fetch resource for id = {} error is {}", resourceData.getUniqueId(), resource.right().value()); return Either.right(resource.right().value()); } result.add(resource.left().value()); @@ -2539,20 +2511,21 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp } other.setVersion(version); other.setUniqueId(null); - + List<InputDefinition> inputs = other.getInputs(); Map<String, List<ComponentInstanceProperty>> inputsPropMap = new HashMap<String, List<ComponentInstanceProperty>>(); - - if (inputs != null) { - for (InputDefinition input : inputs) { - - Either<List<ComponentInstanceProperty>, TitanOperationStatus> inputPropStatus = inputOperation.getComponentInstancePropertiesByInputId(input.getUniqueId()); - if (inputPropStatus.isLeft()) { - if (inputPropStatus.left().value() != null) + + if(inputs != null){ + for(InputDefinition input: inputs){ + + Either<List<ComponentInstanceProperty>, TitanOperationStatus> inputPropStatus = inputOperation.getComponentInstancePropertiesByInputId(input.getUniqueId()); + if(inputPropStatus.isLeft()){ + if(inputPropStatus.left().value() != null) inputsPropMap.put(input.getName(), inputPropStatus.left().value()); - + } - + + } } @@ -2607,15 +2580,10 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp result = this.getResource(resource.getUniqueId(), true); if (result.isRight()) { - log.error("Cannot get full service from the graph. status is " + result.right().value()); + log.error("Cannot get full service from the graph. status is {}", result.right().value()); return Either.right(result.right().value()); } - if (log.isDebugEnabled()) { - String json = prettyJson.toJson(result.left().value()); - // log.debug("Resource retrieved is {}", json); - } - return result; } finally { if (false == inTransaction) { @@ -2713,13 +2681,13 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp SubCategoryDefinition currSubcategory = currentCategory.getSubcategories().get(0); SubCategoryDefinition newSubcategory = newCategory.getSubcategories().get(0); if (newSubcategory.getName() != null && false == newSubcategory.getName().equals(currSubcategory.getName())) { - log.debug("Going to update the category of the resource from " + currentCategory + " to " + newCategory); + log.debug("Going to update the category of the resource from {} to {}", currentCategory, newCategory); categoryWasChanged = true; } } if (categoryWasChanged) { status = moveCategoryEdge((Resource) component, (ResourceMetadataData) componentData, newCategory); - log.debug("Going to update the category of the resource from " + currentCategory + " to " + newCategory + ". status is " + status); + log.debug("Going to update the category of the resource from {} to {}. status is {}", currentCategory, newCategory, status); } return status; } @@ -2810,7 +2778,12 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp List<ResourceMetadataData> resourceMetadataDataList = null; Either<List<ResourceMetadataData>, TitanOperationStatus> byCsar = titanGenericDao.getByCriteria(NodeTypeEnum.Resource, props, ResourceMetadataData.class); if (byCsar.isRight()) { - if (TitanOperationStatus.NOT_FOUND.equals(byCsar.right().value())) { + 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(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true); props.put(GraphPropertiesDictionary.SYSTEM_NAME.getProperty(), systemName); @@ -2820,7 +2793,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp 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()); + 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(); @@ -2850,7 +2823,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp } 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()); + 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) { @@ -2889,7 +2862,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp return Either.left(byCsar.left().value()); } - private Either<Resource, StorageOperationStatus> getResource(String uniqueId, ComponentParametersView componentParametersView, boolean inTransaction) { + public Either<Resource, StorageOperationStatus> getResource(String uniqueId, ComponentParametersView componentParametersView, boolean inTransaction) { Resource resource = null; try { @@ -2971,7 +2944,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp if (false == componentParametersView.isIgnoreRequirements()) { StorageOperationStatus setRequirementsStatus = setResourceRequirementsFromGraph(uniqueId, resource, true); if (setRequirementsStatus != StorageOperationStatus.OK) { - log.error("Failed to set requirement of resource " + uniqueId + ". status is " + setRequirementsStatus); + log.error("Failed to set requirement of resource {}. status is {}", uniqueId, setRequirementsStatus); return Either.right(setRequirementsStatus); } } @@ -2979,7 +2952,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp if (false == componentParametersView.isIgnoreInputs()) { status = setComponentInputsFromGraph(uniqueId, resource, true); if (status != TitanOperationStatus.OK) { - log.error("Failed to set inputs of resource " + uniqueId + ". status is " + status); + log.error("Failed to set inputs of resource {}. status is {}", uniqueId, status); return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); } @@ -3008,7 +2981,7 @@ public class ResourceOperation extends ComponentOperation implements IResourceOp } if (false == componentParametersView.isIgnoreComponentInstancesProperties()) { - status = setComponentInstancesPropertiesFromGraph(uniqueId, resource); + status = setComponentInstancesPropertiesFromGraph(resource); if (status != TitanOperationStatus.OK) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ServiceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ServiceOperation.java index 18229f9245..e503c787b5 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ServiceOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ServiceOperation.java @@ -20,17 +20,9 @@ package org.openecomp.sdc.be.model.operations.impl; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -import javax.annotation.Resource; - +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.TitanVertex; +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; @@ -43,18 +35,7 @@ import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.model.AdditionalInformationDefinition; -import org.openecomp.sdc.be.model.ArtifactDefinition; -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.ComponentParametersView; -import org.openecomp.sdc.be.model.DistributionStatusEnum; -import org.openecomp.sdc.be.model.InputDefinition; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.Service; -import org.openecomp.sdc.be.model.ServiceMetadataDefinition; -import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.operations.api.IArtifactOperation; import org.openecomp.sdc.be.model.operations.api.IElementOperation; @@ -69,11 +50,19 @@ import org.openecomp.sdc.common.util.ValidationUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.thinkaurelius.titan.core.TitanGraph; - -import fj.data.Either; +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Predicate; +import java.util.stream.Collectors; @org.springframework.stereotype.Component("service-operation") +@Deprecated public class ServiceOperation extends ComponentOperation implements IServiceOperation { private static Logger log = LoggerFactory.getLogger(ServiceOperation.class.getName()); @@ -110,7 +99,7 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper if (findUser.isRight()) { TitanOperationStatus status = findUser.right().value(); - log.error("Cannot find user " + userId + " in the graph. status is " + status); + log.error("Cannot find user {} in the graph. status is {}",userId,status); return sendError(status, StorageOperationStatus.USER_NOT_FOUND); } @@ -121,7 +110,7 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper findUser = findUser(updaterUserId); if (findUser.isRight()) { TitanOperationStatus status = findUser.right().value(); - log.error("Cannot find user " + userId + " in the graph. status is " + status); + log.error("Cannot find user {} in the graph. status is {}",userId, status); return sendError(status, StorageOperationStatus.USER_NOT_FOUND); } else { updaterUserData = findUser.left().value(); @@ -134,17 +123,13 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper String categoryName = categories.get(0).getName(); if (categoryName != null) { - Either<CategoryData, StorageOperationStatus> categoryResult = elementOperation - .getNewCategoryData(categoryName, NodeTypeEnum.ServiceNewCategory, CategoryData.class); + Either<CategoryData, StorageOperationStatus> categoryResult = elementOperation.getNewCategoryData(categoryName, NodeTypeEnum.ServiceNewCategory, CategoryData.class); if (categoryResult.isRight()) { StorageOperationStatus status = categoryResult.right().value(); /* - * TitanOperationStatus titanStatus = null; - * if(ActionStatus.CATEGORY_NOT_FOUND.equals(status)){ - * titanStatus = TitanOperationStatus.NOT_FOUND; }else{ - * titanStatus = TitanOperationStatus.GENERAL_ERROR; } + * TitanOperationStatus titanStatus = null; if(ActionStatus.CATEGORY_NOT_FOUND.equals(status)){ titanStatus = TitanOperationStatus.NOT_FOUND; }else{ titanStatus = TitanOperationStatus.GENERAL_ERROR; } */ - log.error("Cannot find category " + categoryName + " in the graph. status is " + status); + log.error("Cannot find category {} in the graph. status is {}",categoryName,status); return Either.right(status); } @@ -156,20 +141,17 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper return Either.right(storageOperationStatus); } - log.debug("try to create service node on graph for id " + serviceData.getUniqueId()); - Either<ServiceMetadataData, TitanOperationStatus> createNode = titanGenericDao.createNode(serviceData, - ServiceMetadataData.class); + log.debug("try to create service node on graph for id {}",serviceData.getUniqueId()); + Either<ServiceMetadataData, TitanOperationStatus> createNode = titanGenericDao.createNode(serviceData, ServiceMetadataData.class); if (createNode.isRight()) { TitanOperationStatus status = createNode.right().value(); - log.error("Error returned after creating service data node " + serviceData + ". status returned is " - + status); + log.error("Error returned after creating service data node {}. status returned is {}",serviceData,status); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); return result; } - log.debug("create service node created on graph for id " + serviceData.getUniqueId()); + log.debug("create service node created on graph for id {}",serviceData.getUniqueId()); - TitanOperationStatus associateMetadata = associateMetadataToComponent(serviceData, creatorUserData, - updaterUserData, null, null); + TitanOperationStatus associateMetadata = associateMetadataToComponent(serviceData, creatorUserData, updaterUserData, null, null); if (associateMetadata != TitanOperationStatus.OK) { result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(associateMetadata)); return result; @@ -194,23 +176,20 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper allArtifacts.putAll(service.getToscaArtifacts()); } - StorageOperationStatus associateArtifacts = associateArtifactsToComponent(NodeTypeEnum.Service, serviceData, - allArtifacts); + StorageOperationStatus associateArtifacts = associateArtifactsToComponent(NodeTypeEnum.Service, serviceData, allArtifacts); if (associateArtifacts != StorageOperationStatus.OK) { result = Either.right(associateArtifacts); return result; } - TitanOperationStatus associateInputs = associateInputsToComponent(NodeTypeEnum.Service, serviceData, - service.getInputs()); + TitanOperationStatus associateInputs = associateInputsToComponent(NodeTypeEnum.Service, serviceData, service.getInputs()); if (associateInputs != TitanOperationStatus.OK) { result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(associateInputs)); return result; } List<AdditionalInformationDefinition> additionalInformation = service.getAdditionalInformation(); - StorageOperationStatus addAdditionalInformation = addAdditionalInformationToService(uniqueId, - additionalInformation); + StorageOperationStatus addAdditionalInformation = addAdditionalInformationToService(uniqueId, additionalInformation); if (addAdditionalInformation != StorageOperationStatus.OK) { result = Either.right(addAdditionalInformation); return result; @@ -218,13 +197,13 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper result = this.getService(uniqueId, true); if (result.isRight()) { - log.error("Cannot get full service from the graph. status is " + result.right().value()); + log.error("Cannot get full service from the graph. status is {}", result.right().value()); return Either.right(result.right().value()); } if (log.isDebugEnabled()) { String json = prettyJson.toJson(result.left().value()); - log.debug("Service retrieved is " + json); + log.debug("Service retrieved is {}",json); } return result; @@ -242,24 +221,20 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper } } - private TitanOperationStatus associateMetadataCategoryToComponent(ServiceMetadataData serviceData, - CategoryData categoryData) { + private TitanOperationStatus associateMetadataCategoryToComponent(ServiceMetadataData serviceData, CategoryData categoryData) { Either<GraphRelation, TitanOperationStatus> result; if (categoryData != null) { result = titanGenericDao.createRelation(serviceData, categoryData, GraphEdgeLabels.CATEGORY, null); - log.debug("After associating component " + serviceData.getUniqueId() + " to category " + categoryData - + ". Edge type is " + GraphEdgeLabels.CATEGORY); + log.debug("After associating component {} to category {}. Edge type is {}",serviceData.getUniqueId(),categoryData,GraphEdgeLabels.CATEGORY); if (result.isRight()) { - log.error("Faield to associate component " + serviceData.getUniqueId() + " to category " + categoryData - + ". Edge type is " + GraphEdgeLabels.CATEGORY); + log.error("Faield to associate component {} to category {}. Edge type is {}",serviceData.getUniqueId(),categoryData,GraphEdgeLabels.CATEGORY); return result.right().value(); } } return TitanOperationStatus.OK; } - private StorageOperationStatus addAdditionalInformationToService(String resourceUniqueId, - List<AdditionalInformationDefinition> additionalInformation) { + private StorageOperationStatus addAdditionalInformationToService(String resourceUniqueId, List<AdditionalInformationDefinition> additionalInformation) { StorageOperationStatus result = null; @@ -267,13 +242,10 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper result = super.addAdditionalInformation(NodeTypeEnum.Service, resourceUniqueId, null); } else { if (additionalInformation.size() == 1) { - result = super.addAdditionalInformation(NodeTypeEnum.Service, resourceUniqueId, - additionalInformation.get(0)); + result = super.addAdditionalInformation(NodeTypeEnum.Service, resourceUniqueId, additionalInformation.get(0)); } else { result = StorageOperationStatus.BAD_REQUEST; - log.info( - "Cannot create resource with more than one additional information object. The number of received object is " - + additionalInformation.size()); + log.info("Cannot create resource with more than one additional information object. The number of received object is {}", additionalInformation.size()); } } return result; @@ -283,8 +255,7 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper return cloneService(other, version, null, inTransaction); } - public Either<Service, StorageOperationStatus> cloneService(Service other, String version, - LifecycleStateEnum targetLifecycle, boolean inTransaction) { + public Either<Service, StorageOperationStatus> cloneService(Service other, String version, LifecycleStateEnum targetLifecycle, boolean inTransaction) { Either<Service, StorageOperationStatus> result = null; try { @@ -292,28 +263,26 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper other.setVersion(version); other.setUniqueId(null); - Either<Integer, StorageOperationStatus> counterStatus = getComponentInstanceCoutner(origServiceId, - NodeTypeEnum.Service); + Either<Integer, StorageOperationStatus> counterStatus = getComponentInstanceCoutner(origServiceId, NodeTypeEnum.Service); if (counterStatus.isRight()) { StorageOperationStatus status = counterStatus.right().value(); - log.error("failed to get resource instance counter on service {}. status={}", origServiceId, - counterStatus); + log.error("failed to get resource instance counter on service {}. status={}", origServiceId, counterStatus); result = Either.right(status); return result; } Map<String, List<ComponentInstanceInput>> inputsValuesMap = new HashMap<String, List<ComponentInstanceInput>>(); List<InputDefinition> inputs = other.getInputs(); - if(inputs != null){ - for(InputDefinition input: inputs){ - - Either<List<ComponentInstanceInput>, TitanOperationStatus> inputStatus = inputOperation.getComponentInstanceInputsByInputId(input.getUniqueId()); - - if(inputStatus.isLeft()){ - if(inputStatus.left().value() != null) - inputsValuesMap.put(input.getName(), inputStatus.left().value()); - } + if (inputs != null) { + for (InputDefinition input : inputs) { + + Either<List<ComponentInstanceInput>, TitanOperationStatus> inputStatus = inputOperation + .getComponentInstanceInputsByInputId(input.getUniqueId()); + + if (inputStatus.isLeft() && inputStatus.left().value() != null) { + inputsValuesMap.put(input.getName(), inputStatus.left().value()); + } } - } + } Either<Service, StorageOperationStatus> createServiceMD = createService(other, true); @@ -333,19 +302,17 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper return result; } - Either<Integer, StorageOperationStatus> setResourceInstanceCounter = setComponentInstanceCounter( - service.getUniqueId(), NodeTypeEnum.Service, counterStatus.left().value(), true); + Either<Integer, StorageOperationStatus> setResourceInstanceCounter = setComponentInstanceCounter(service.getUniqueId(), NodeTypeEnum.Service, counterStatus.left().value(), true); if (setResourceInstanceCounter.isRight()) { StorageOperationStatus status = setResourceInstanceCounter.right().value(); - log.error("failed to set resource instance counter on service {}. status={}", service.getUniqueId(), - setResourceInstanceCounter); + log.error("failed to set resource instance counter on service {}. status={}", service.getUniqueId(), setResourceInstanceCounter); result = Either.right(status); return result; } result = this.getService(service.getUniqueId(), true); if (result.isRight()) { - log.error("Cannot get full service from the graph. status is " + result.right().value()); + log.error("Cannot get full service from the graph. status is {}", result.right().value()); return Either.right(result.right().value()); } @@ -369,22 +336,18 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper } private ServiceMetadataData getServiceMetaDataFromService(Service service) { - ServiceMetadataData serviceData = new ServiceMetadataData( - (ServiceMetadataDataDefinition) service.getComponentMetadataDefinition().getMetadataDataDefinition()); + ServiceMetadataData serviceData = new ServiceMetadataData((ServiceMetadataDataDefinition) service.getComponentMetadataDefinition().getMetadataDataDefinition()); if (service.getNormalizedName() == null || service.getNormalizedName().isEmpty()) { - serviceData.getMetadataDataDefinition() - .setNormalizedName(ValidationUtils.normaliseComponentName(service.getName())); + serviceData.getMetadataDataDefinition().setNormalizedName(ValidationUtils.normaliseComponentName(service.getName())); } if (service.getSystemName() == null || service.getSystemName().isEmpty()) { - serviceData.getMetadataDataDefinition() - .setSystemName(ValidationUtils.convertToSystemName(service.getName())); + serviceData.getMetadataDataDefinition().setSystemName(ValidationUtils.convertToSystemName(service.getName())); } return serviceData; } - private Either<Service, StorageOperationStatus> sendError(TitanOperationStatus status, - StorageOperationStatus statusIfNotFound) { + private Either<Service, StorageOperationStatus> sendError(TitanOperationStatus status, StorageOperationStatus statusIfNotFound) { Either<Service, StorageOperationStatus> result; if (status == TitanOperationStatus.NOT_FOUND) { result = Either.right(statusIfNotFound); @@ -406,128 +369,8 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper ComponentParametersView componentParametersView = new ComponentParametersView(); return getService(uniqueId, componentParametersView, inTransaction); } - // public Either<Service, StorageOperationStatus> getService(String - // uniqueId, boolean inTransaction) { - // - // Service service = null; - // Either<Service, StorageOperationStatus> result = null; - // try { - // - // NodeTypeEnum serviceNodeType = NodeTypeEnum.Service; - // NodeTypeEnum compInstNodeType = NodeTypeEnum.Resource; - // - // Either<ServiceMetadataData, StorageOperationStatus> getComponentByLabel = - // getComponentByLabelAndId(uniqueId, serviceNodeType, - // ServiceMetadataData.class); - // if (getComponentByLabel.isRight()) { - // result = Either.right(getComponentByLabel.right().value()); - // return result; - // } - // ServiceMetadataData serviceData = getComponentByLabel.left().value(); - // service = convertServiceDataToService(serviceData); - // - // TitanOperationStatus status = setComponentCreatorFromGraph(service, - // uniqueId, serviceNodeType); - // if (status != TitanOperationStatus.OK) { - // result = - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // return result; - // } - // - // status = setComponentLastModifierFromGraph(service, uniqueId, - // serviceNodeType); - // if (status != TitanOperationStatus.OK) { - // result = - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // return result; - // - // } - // status = setComponentCategoriesFromGraph(service); - // if (status != TitanOperationStatus.OK) { - // result = - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // return result; - // - // } - // - // // status = setServicePropertiesFromGraph(uniqueId, resource, vertex); - // // if (status != TitanOperationStatus.OK) { - // // return - // Either.right(TitanStatusConverter.convertTitanStatusToStorageStatus(status)); - // // } - // - // StorageOperationStatus storageStatus = setArtifactFromGraph(uniqueId, - // service, serviceNodeType, artifactOperation); - // if (storageStatus != StorageOperationStatus.OK) { - // result = Either.right(storageStatus); - // return result; - // } - // - // status = setComponentInstancesFromGraph(uniqueId, service, - // serviceNodeType, compInstNodeType); - // if (status != TitanOperationStatus.OK) { - // result = - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // return result; - // - // } - // - // status = setComponentInstancesPropertiesFromGraph(uniqueId, service); - // if (status != TitanOperationStatus.OK) { - // result = - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // return result; - // } - // - // status = setCapabilitiesFromGraph(uniqueId, service, - // NodeTypeEnum.Service); - // if (status != TitanOperationStatus.OK) { - // result = - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // return result; - // } - // - // status = setRequirementsFromGraph( uniqueId, service, - // NodeTypeEnum.Service); - // if (status != TitanOperationStatus.OK) { - // result = - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // return result; - // } - // - // status = setAllVersions(service); - // if (status != TitanOperationStatus.OK) { - // return - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // } - // - // status = setServiceAdditionalInformationFromGraph(uniqueId, service); - // if (status != TitanOperationStatus.OK) { - // return - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // } - // - // status = setGroupsFromGraph(uniqueId, service, NodeTypeEnum.Resource); - // if (status != TitanOperationStatus.OK) { - // return - // Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - // } - // - // result = Either.left(service); - // return result; - // } finally { - // if (false == inTransaction) { - // if (result == null || result.isRight()) { - // titanGenericDao.rollback(); - // } else { - // titanGenericDao.commit(); - // } - // } - // } - // } - public Either<Service, StorageOperationStatus> getService(String uniqueId, - ComponentParametersView componentParametersView, boolean inTransaction) { + public Either<Service, StorageOperationStatus> getService(String uniqueId, ComponentParametersView componentParametersView, boolean inTransaction) { Service service = null; Either<Service, StorageOperationStatus> result = null; @@ -536,8 +379,7 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper NodeTypeEnum serviceNodeType = NodeTypeEnum.Service; NodeTypeEnum compInstNodeType = NodeTypeEnum.Resource; - Either<ServiceMetadataData, StorageOperationStatus> getComponentByLabel = getComponentByLabelAndId(uniqueId, - serviceNodeType, ServiceMetadataData.class); + Either<ServiceMetadataData, StorageOperationStatus> getComponentByLabel = getComponentByLabelAndId(uniqueId, serviceNodeType, ServiceMetadataData.class); if (getComponentByLabel.isRight()) { result = Either.right(getComponentByLabel.right().value()); return result; @@ -546,12 +388,10 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper // Try to fetch resource from the cache. The resource will be // fetched only if the time on the cache equals to // the time on the graph. - Either<Service, ActionStatus> componentFromCacheIfUpToDate = this.getComponentFromCacheIfUpToDate(uniqueId, - serviceData, componentParametersView, Service.class, ComponentTypeEnum.SERVICE); + Either<Service, ActionStatus> componentFromCacheIfUpToDate = this.getComponentFromCacheIfUpToDate(uniqueId, serviceData, componentParametersView, Service.class, ComponentTypeEnum.SERVICE); if (componentFromCacheIfUpToDate.isLeft()) { Service cachedService = componentFromCacheIfUpToDate.left().value(); - log.debug("Service {} with uid {} was fetched from cache.", cachedService.getName(), - cachedService.getUniqueId()); + log.debug("Service {} with uid {} was fetched from cache.", cachedService.getName(), cachedService.getUniqueId()); return Either.left(cachedService); } @@ -580,25 +420,15 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper } } - // status = setServicePropertiesFromGraph(uniqueId, resource, - // vertex); - // if (status != TitanOperationStatus.OK) { - // return - // Either.right(TitanStatusConverter.convertTitanStatusToStorageStatus(status)); - // } - if (false == componentParametersView.isIgnoreArtifacts()) { - StorageOperationStatus storageStatus = setArtifactFromGraph(uniqueId, service, serviceNodeType, - artifactOperation); + StorageOperationStatus storageStatus = setArtifactFromGraph(uniqueId, service, serviceNodeType, artifactOperation); if (storageStatus != StorageOperationStatus.OK) { result = Either.right(storageStatus); return result; } } - if (false == componentParametersView.isIgnoreComponentInstances() - || false == componentParametersView.isIgnoreComponentInstancesProperties() - || false == componentParametersView.isIgnoreCapabilities() + if (false == componentParametersView.isIgnoreComponentInstances() || false == componentParametersView.isIgnoreComponentInstancesProperties() || false == componentParametersView.isIgnoreCapabilities() || false == componentParametersView.isIgnoreRequirements()) { status = setComponentInstancesFromGraph(uniqueId, service, serviceNodeType, compInstNodeType); if (status != TitanOperationStatus.OK) { @@ -608,7 +438,7 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper } } if (false == componentParametersView.isIgnoreComponentInstancesProperties()) { - status = setComponentInstancesPropertiesFromGraph(uniqueId, service); + status = setComponentInstancesPropertiesFromGraph(service); if (status != TitanOperationStatus.OK) { result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); return result; @@ -650,7 +480,7 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper if (false == componentParametersView.isIgnoreInputs()) { status = setComponentInputsFromGraph(uniqueId, service, true); if (status != TitanOperationStatus.OK) { - log.error("Failed to set inputs of resource " + uniqueId + ". status is " + status); + log.error("Failed to set inputs of resource {}. status is {}",uniqueId,status); return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); } @@ -795,19 +625,17 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper TitanOperationStatus setComponentCategoriesFromGraph(Component service) { String uniqueId = service.getUniqueId(); - Either<List<ImmutablePair<CategoryData, GraphEdge>>, TitanOperationStatus> parentNode = titanGenericDao - .getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Service), uniqueId, - GraphEdgeLabels.CATEGORY, NodeTypeEnum.ServiceNewCategory, CategoryData.class); + Either<List<ImmutablePair<CategoryData, GraphEdge>>, TitanOperationStatus> parentNode = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Service), uniqueId, GraphEdgeLabels.CATEGORY, + NodeTypeEnum.ServiceNewCategory, CategoryData.class); if (parentNode.isRight()) { return parentNode.right().value(); } List<ImmutablePair<CategoryData, GraphEdge>> listValue = parentNode.left().value(); if (log.isDebugEnabled()) - log.debug("Result after looking for category nodes pointed by service {}. status is {}", uniqueId, - listValue); + log.debug("Result after looking for category nodes pointed by service {}. status is {}", uniqueId, listValue); if (listValue.size() > 1) { - log.error("Multiple edges foud between resource " + uniqueId + " to category nodes."); + log.error("Multiple edges foud between resource {} to category nodes.",uniqueId); } ImmutablePair<CategoryData, GraphEdge> value = listValue.get(0); if (log.isDebugEnabled()) @@ -836,59 +664,52 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper Either<TitanGraph, TitanOperationStatus> graphResult = titanGenericDao.getGraph(); if (graphResult.isRight()) { - result = Either - .right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value())); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value())); return result; } - Either<ServiceMetadataData, TitanOperationStatus> serviceNode = titanGenericDao.getNode( - UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Service), serviceId, ServiceMetadataData.class); + Either<ServiceMetadataData, TitanOperationStatus> serviceNode = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Service), serviceId, ServiceMetadataData.class); if (serviceNode.isRight()) { TitanOperationStatus status = serviceNode.right().value(); - log.error("Failed to find service " + serviceId + ". status is " + status); + log.error("Failed to find service {}. status is {}",serviceId,status); return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); } Either<Service, StorageOperationStatus> serviceRes = getService(serviceId, true); if (serviceRes.isRight()) { StorageOperationStatus status = serviceRes.right().value(); - log.error("Failed to find sevice " + serviceId + ".status is " + status); + log.error("Failed to find sevice {}.status is {}",serviceId,status); result = Either.right(status); return result; } Service service = serviceRes.left().value(); - Either<List<ComponentInstance>, StorageOperationStatus> deleteAllResourceInstancesRes = componentInstanceOperation - .deleteAllComponentInstances(serviceId, NodeTypeEnum.Service, true); - log.debug("After deleting resource instances under service " + serviceId + ".Result is " - + deleteAllResourceInstancesRes); + Either<List<ComponentInstance>, StorageOperationStatus> deleteAllResourceInstancesRes = componentInstanceOperation.deleteAllComponentInstances(serviceId, NodeTypeEnum.Service, true); + log.debug("After deleting resource instances under service {}.Result is {}",serviceId,deleteAllResourceInstancesRes); if (deleteAllResourceInstancesRes.isRight()) { StorageOperationStatus status = deleteAllResourceInstancesRes.right().value(); if (status != StorageOperationStatus.NOT_FOUND) { - log.error( - "Failed to delete resource instances under service " + serviceId + " .status is " + status); + log.error("Failed to delete resource instances under service {} .status is ",serviceId,status); result = Either.right(status); return result; } } - StorageOperationStatus removeArtifactsFromResource = removeArtifactsFromComponent(service, - NodeTypeEnum.Service); - log.debug("After deleting artifacts nodes in the graph. status is " + removeArtifactsFromResource); + StorageOperationStatus removeArtifactsFromResource = removeArtifactsFromComponent(service, NodeTypeEnum.Service); + log.debug("After deleting artifacts nodes in the graph. status is {}",removeArtifactsFromResource); if (!removeArtifactsFromResource.equals(StorageOperationStatus.OK)) { result = Either.right(removeArtifactsFromResource); return result; } StorageOperationStatus removeInputsFromResource = removeInputsFromComponent(NodeTypeEnum.Service, service); - log.debug("After deleting requirements nodes in the graph. status is " + removeInputsFromResource); + log.debug("After deleting requirements nodes in the graph. status is {}",removeInputsFromResource); if (removeInputsFromResource != StorageOperationStatus.OK) { result = Either.right(removeInputsFromResource); return result; } - Either<List<ImmutablePair<PropertyData, GraphEdge>>, TitanOperationStatus> deleteChildrenNodesRes = titanGenericDao - .deleteChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Service), serviceId, - GraphEdgeLabels.PROPERTY, NodeTypeEnum.Property, PropertyData.class); + Either<List<ImmutablePair<PropertyData, GraphEdge>>, TitanOperationStatus> deleteChildrenNodesRes = titanGenericDao.deleteChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Service), serviceId, GraphEdgeLabels.PROPERTY, + NodeTypeEnum.Property, PropertyData.class); if (deleteChildrenNodesRes.isRight()) { TitanOperationStatus status = deleteChildrenNodesRes.right().value(); @@ -898,27 +719,24 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper } } - StorageOperationStatus removeAdditionalInformationFromService = super.deleteAdditionalInformation( - NodeTypeEnum.Service, serviceId); - log.debug("After deleting additional information node in the graph. status is " - + removeAdditionalInformationFromService); + StorageOperationStatus removeAdditionalInformationFromService = super.deleteAdditionalInformation(NodeTypeEnum.Service, serviceId); + log.debug("After deleting additional information node in the graph. status is {}",removeAdditionalInformationFromService); if (!removeAdditionalInformationFromService.equals(StorageOperationStatus.OK)) { result = Either.right(removeAdditionalInformationFromService); return result; } StorageOperationStatus removeGroupsFromService = super.deleteGroups(NodeTypeEnum.Service, serviceId); - log.debug("After deleting group nodes in the graph. status is " + removeGroupsFromService); + log.debug("After deleting group nodes in the graph. status is {}",removeGroupsFromService); if (!removeGroupsFromService.equals(StorageOperationStatus.OK)) { result = Either.right(removeGroupsFromService); return result; } - Either<ServiceMetadataData, TitanOperationStatus> deleteServiceNodeRes = titanGenericDao - .deleteNode(serviceNode.left().value(), ServiceMetadataData.class); + Either<ServiceMetadataData, TitanOperationStatus> deleteServiceNodeRes = titanGenericDao.deleteNode(serviceNode.left().value(), ServiceMetadataData.class); if (deleteServiceNodeRes.isRight()) { TitanOperationStatus status = deleteServiceNodeRes.right().value(); - log.error("Failed to delete service node " + serviceId + ". status is " + status); + log.error("Failed to delete service node {}. status is {}",serviceId, status); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); return result; } @@ -946,8 +764,7 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper } private Service convertServiceDataToService(ServiceMetadataData serviceData) { - ServiceMetadataDefinition serviceMetadataDefinition = new ServiceMetadataDefinition( - (ServiceMetadataDataDefinition) serviceData.getMetadataDataDefinition()); + ServiceMetadataDefinition serviceMetadataDefinition = new ServiceMetadataDefinition((ServiceMetadataDataDefinition) serviceData.getMetadataDataDefinition()); Service service = new Service(serviceMetadataDefinition); @@ -964,12 +781,11 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper return Either.left(clazz.cast(component.left().value())); } + @Override @SuppressWarnings("unchecked") - public Either<List<Service>, StorageOperationStatus> getFollowed(String userId, - Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, boolean inTransaction) { + public Either<List<Service>, StorageOperationStatus> getFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, Set<LifecycleStateEnum> lastStateStates, boolean inTransaction) { - return (Either<List<Service>, StorageOperationStatus>) (Either<?, StorageOperationStatus>) getFollowedComponent( - userId, lifecycleStates, lastStateStates, inTransaction, titanGenericDao, NodeTypeEnum.Service); + return (Either<List<Service>, StorageOperationStatus>) (Either<?, StorageOperationStatus>) getFollowedComponent(userId, lifecycleStates, lastStateStates, inTransaction, titanGenericDao, NodeTypeEnum.Service); } @SuppressWarnings("unchecked") @@ -978,24 +794,14 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper return (Either<T, StorageOperationStatus>) getService(id, inTransaction); } - // @Override - // public <T> Either<T, StorageOperationStatus> getComponent_tx(String id, - // boolean inTransaction) { - // return (Either<T, StorageOperationStatus>) getService_tx(id, - // inTransaction); - // } - @Override - public Either<Set<Service>, StorageOperationStatus> getCatalogData(Map<String, Object> propertiesToMatch, - boolean inTransaction) { - return getComponentCatalogData(NodeTypeEnum.Service, propertiesToMatch, Service.class, - ServiceMetadataData.class, inTransaction); + public Either<Set<Service>, StorageOperationStatus> getCatalogData(Map<String, Object> propertiesToMatch, boolean inTransaction) { + return getComponentCatalogData(NodeTypeEnum.Service, propertiesToMatch, Service.class, ServiceMetadataData.class, inTransaction); } @Override public Either<Service, StorageOperationStatus> updateService(Service service, boolean inTransaction) { - Either<Service, StorageOperationStatus> result = updateComponent(service, inTransaction, titanGenericDao, - Service.class, NodeTypeEnum.Service); + Either<Service, StorageOperationStatus> result = updateComponent(service, inTransaction, titanGenericDao, Service.class, NodeTypeEnum.Service); return result; } @@ -1008,8 +814,7 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper @SuppressWarnings("unchecked") @Override public Either<Component, StorageOperationStatus> deleteComponent(String id, boolean inTransaction) { - return (Either<Component, StorageOperationStatus>) (Either<?, StorageOperationStatus>) deleteService(id, - inTransaction); + return (Either<Component, StorageOperationStatus>) (Either<?, StorageOperationStatus>) deleteService(id, inTransaction); } @Override @@ -1023,8 +828,7 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper } @Override - public <T> Either<List<T>, StorageOperationStatus> getFilteredComponents(Map<FilterKeyEnum, String> filters, - boolean inTransaction) { + public <T> Either<List<T>, StorageOperationStatus> getFilteredComponents(Map<FilterKeyEnum, String> filters, boolean inTransaction) { Either<List<T>, StorageOperationStatus> components = null; String categoryName = filters.get(FilterKeyEnum.CATEGORY); @@ -1036,13 +840,10 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper } if (categoryName != null) { // primary filter - components = fetchByCategoryOrSubCategoryName(categoryName, NodeTypeEnum.ServiceNewCategory, - GraphEdgeLabels.CATEGORY.getProperty(), NodeTypeEnum.Service, inTransaction, - ServiceMetadataData.class); + components = fetchByCategoryOrSubCategoryName(categoryName, NodeTypeEnum.ServiceNewCategory, GraphEdgeLabels.CATEGORY.getProperty(), NodeTypeEnum.Service, inTransaction, ServiceMetadataData.class, null); if (components.isLeft() && distEnum != null) {// secondary filter Predicate<T> statusFilter = p -> ((Service) p).getDistributionStatus().equals(distEnum); - return Either - .left(components.left().value().stream().filter(statusFilter).collect(Collectors.toList())); + return Either.left(components.left().value().stream().filter(statusFilter).collect(Collectors.toList())); } filters.remove(FilterKeyEnum.DISTRIBUTION_STATUS); return components; @@ -1054,69 +855,56 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper return components; } - private <T> Either<List<T>, StorageOperationStatus> fetchByDistributionStatus(String status, - boolean inTransaction) { + private <T> Either<List<T>, StorageOperationStatus> fetchByDistributionStatus(String status, boolean inTransaction) { Map<String, Object> props = new HashMap<String, Object>(); props.put(GraphPropertiesDictionary.DISTRIBUTION_STATUS.getProperty(), status); props.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true); - return (Either<List<T>, StorageOperationStatus>) (Either<?, StorageOperationStatus>) getServiceListByCriteria( - props, inTransaction); + return (Either<List<T>, StorageOperationStatus>) (Either<?, StorageOperationStatus>) getServiceListByCriteria(props, inTransaction); } @SuppressWarnings("unchecked") @Override - public Either<List<Service>, StorageOperationStatus> getTesterFollowed(String userId, - Set<LifecycleStateEnum> lifecycleStates, boolean inTransaction) { - return (Either<List<Service>, StorageOperationStatus>) (Either<?, StorageOperationStatus>) getTesterFollowedComponent( - userId, lifecycleStates, inTransaction, NodeTypeEnum.Service); + public Either<List<Service>, StorageOperationStatus> getTesterFollowed(String userId, Set<LifecycleStateEnum> lifecycleStates, boolean inTransaction) { + return (Either<List<Service>, StorageOperationStatus>) (Either<?, StorageOperationStatus>) getTesterFollowedComponent(userId, lifecycleStates, inTransaction, NodeTypeEnum.Service); } - public Either<Service, StorageOperationStatus> updateDestributionStatus(Service service, User user, - DistributionStatusEnum distributionStatus) { + @Override + public Either<Service, StorageOperationStatus> updateDestributionStatus(Service service, User user, DistributionStatusEnum distributionStatus) { String userId = user.getUserId(); Either<UserData, TitanOperationStatus> findUser = findUser(userId); if (findUser.isRight()) { TitanOperationStatus status = findUser.right().value(); - log.error("Cannot find user " + userId + " in the graph. status is " + status); + log.error("Cannot find user {} in the graph. status is {}", userId, status); return sendError(status, StorageOperationStatus.USER_NOT_FOUND); } UserData userData = findUser.left().value(); - Either<ServiceMetadataData, TitanOperationStatus> serviceMetadataDataRequeset = titanGenericDao.getNode( - UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Service), service.getUniqueId(), - ServiceMetadataData.class); + Either<ServiceMetadataData, TitanOperationStatus> serviceMetadataDataRequeset = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Service), service.getUniqueId(), ServiceMetadataData.class); if (serviceMetadataDataRequeset.isRight()) { TitanOperationStatus status = serviceMetadataDataRequeset.right().value(); - log.error("Cannot find service " + service.getUniqueId() + " in the graph. status is " + status); + log.error("Cannot find service {} in the graph. status is {}",service.getUniqueId(),status); return sendError(status, StorageOperationStatus.NOT_FOUND); } ServiceMetadataData serviceMetadataData = serviceMetadataDataRequeset.left().value(); StorageOperationStatus result = StorageOperationStatus.OK; - Either<GraphRelation, TitanOperationStatus> deleteIncomingRelation = deleteLastDistributionModifierRelation( - service); - if (deleteIncomingRelation.isRight() - && deleteIncomingRelation.right().value() != TitanOperationStatus.NOT_FOUND) { - log.error("Failed to delete user from component " + service.getUniqueId() + ". Edge type is " - + GraphEdgeLabels.LAST_DISTRIBUTION_STATE_MODIFAIER); + Either<GraphRelation, TitanOperationStatus> deleteIncomingRelation = deleteLastDistributionModifierRelation(service); + if (deleteIncomingRelation.isRight() && deleteIncomingRelation.right().value() != TitanOperationStatus.NOT_FOUND) { + log.error("Failed to delete user from component {}. Edge type is {}",service.getUniqueId(),GraphEdgeLabels.LAST_DISTRIBUTION_STATE_MODIFAIER); result = DaoStatusConverter.convertTitanStatusToStorageStatus(deleteIncomingRelation.right().value()); return Either.right(result); } - Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(userData, - serviceMetadataData, GraphEdgeLabels.LAST_DISTRIBUTION_STATE_MODIFAIER, null); - log.debug("After associating user " + userData + " to component " + serviceMetadataData.getUniqueId() - + ". Edge type is " + GraphEdgeLabels.LAST_DISTRIBUTION_STATE_MODIFAIER); + Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(userData, serviceMetadataData, GraphEdgeLabels.LAST_DISTRIBUTION_STATE_MODIFAIER, null); + log.debug("After associating user {} to component {}. Edge type is {}",userData,serviceMetadataData.getUniqueId(),GraphEdgeLabels.LAST_DISTRIBUTION_STATE_MODIFAIER); if (createRelation.isRight()) { - log.error("Failed to associate user " + userData + " to component " + serviceMetadataData.getUniqueId() - + ". Edge type is " + GraphEdgeLabels.LAST_DISTRIBUTION_STATE_MODIFAIER); + log.error("Failed to associate user {} to component {}. Edge type is {}",userData,serviceMetadataData.getUniqueId(),GraphEdgeLabels.LAST_DISTRIBUTION_STATE_MODIFAIER); result = DaoStatusConverter.convertTitanStatusToStorageStatus(createRelation.right().value()); return Either.right(result); } service.setDistributionStatus(distributionStatus); - Either<Service, StorageOperationStatus> updateResponse = updateComponent(service, true, titanGenericDao, - Service.class, NodeTypeEnum.Service); + Either<Service, StorageOperationStatus> updateResponse = updateComponent(service, true, titanGenericDao, Service.class, NodeTypeEnum.Service); return updateResponse; @@ -1125,17 +913,14 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper private Either<GraphRelation, TitanOperationStatus> deleteLastDistributionModifierRelation(Service service) { GraphRelation lastDistributionStateModifaierRelation = new GraphRelation(); lastDistributionStateModifaierRelation.setType(GraphEdgeLabels.LAST_DISTRIBUTION_STATE_MODIFAIER.getProperty()); - RelationEndPoint relationEndPoint = new RelationEndPoint(NodeTypeEnum.Service, - UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Service), service.getUniqueId()); + RelationEndPoint relationEndPoint = new RelationEndPoint(NodeTypeEnum.Service, UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Service), service.getUniqueId()); lastDistributionStateModifaierRelation.setTo(relationEndPoint); - Either<GraphRelation, TitanOperationStatus> deleteIncomingRelation = titanGenericDao - .deleteIncomingRelation(lastDistributionStateModifaierRelation); + Either<GraphRelation, TitanOperationStatus> deleteIncomingRelation = titanGenericDao.deleteIncomingRelation(lastDistributionStateModifaierRelation); return deleteIncomingRelation; } @Override - public Either<Set<Service>, StorageOperationStatus> getCertifiedServicesWithDistStatus( - Map<String, Object> propertiesToMatch, Set<DistributionStatusEnum> distStatus, boolean inTransaction) { + public Either<Set<Service>, StorageOperationStatus> getCertifiedServicesWithDistStatus(Map<String, Object> propertiesToMatch, Set<DistributionStatusEnum> distStatus, boolean inTransaction) { log.debug("Start getCertifiedServicesWithDistStatus."); Set<Service> servicesSet = new HashSet<Service>(); if (distStatus != null && !distStatus.isEmpty()) { @@ -1143,8 +928,7 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper Map<String, Object> props = new HashMap<>(); props.putAll(propertiesToMatch); props.put(GraphPropertiesDictionary.DISTRIBUTION_STATUS.getProperty(), status.name()); - Either<Set<Service>, StorageOperationStatus> services = retrieveCertifiedServicesWithStatus( - inTransaction, servicesSet, props); + Either<Set<Service>, StorageOperationStatus> services = retrieveCertifiedServicesWithStatus(inTransaction, props); if (services.isRight()) { return services; } else { @@ -1153,14 +937,12 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper } return Either.left(servicesSet); } else { - return retrieveCertifiedServicesWithStatus(inTransaction, servicesSet, propertiesToMatch); + return retrieveCertifiedServicesWithStatus(inTransaction, propertiesToMatch); } } - private Either<Set<Service>, StorageOperationStatus> retrieveCertifiedServicesWithStatus(boolean inTransaction, - Set<Service> servicesSet, Map<String, Object> props) { - Either<List<ServiceMetadataData>, TitanOperationStatus> criteriaRes = titanGenericDao - .getByCriteria(NodeTypeEnum.Service, props, ServiceMetadataData.class); + private Either<Set<Service>, StorageOperationStatus> retrieveCertifiedServicesWithStatus(boolean inTransaction, Map<String, Object> props) { + Either<List<ServiceMetadataData>, TitanOperationStatus> criteriaRes = titanGenericDao.getByCriteria(NodeTypeEnum.Service, props, ServiceMetadataData.class); return retrieveComponentsFromNodes(criteriaRes, inTransaction); } @@ -1170,41 +952,19 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper try { /* - * Map<String, Object> propertiesToMatch = new HashMap<>(); - * propertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty - * (), LifecycleStateEnum.CERTIFIED.name()); - * Either<List<ServiceMetadataData>, TitanOperationStatus> - * lastVersionNodes = getLastVersion(NodeTypeEnum.Service, - * propertiesToMatch, ServiceMetadataData.class); if - * (lastVersionNodes.isRight() && lastVersionNodes.right().value() - * != TitanOperationStatus.NOT_FOUND) { return - * Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus - * (lastVersionNodes.right().value())); } List<ServiceMetadataData> - * notCertifiedHighest = (lastVersionNodes.isLeft() ? - * lastVersionNodes.left().value() : new + * Map<String, Object> propertiesToMatch = new HashMap<>(); propertiesToMatch.put(GraphPropertiesDictionary.STATE.getProperty (), LifecycleStateEnum.CERTIFIED.name()); Either<List<ServiceMetadataData>, TitanOperationStatus> + * lastVersionNodes = getLastVersion(NodeTypeEnum.Service, propertiesToMatch, ServiceMetadataData.class); if (lastVersionNodes.isRight() && lastVersionNodes.right().value() != TitanOperationStatus.NOT_FOUND) { return + * Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus (lastVersionNodes.right().value())); } List<ServiceMetadataData> notCertifiedHighest = (lastVersionNodes.isLeft() ? lastVersionNodes.left().value() : new * ArrayList<ServiceMetadataData>()); * - * propertiesToMatch.put(GraphPropertiesDictionary. - * IS_HIGHEST_VERSION.getProperty(), true); - * Either<List<ServiceMetadataData>, TitanOperationStatus> - * componentsNodes = - * titanGenericDao.getByCriteria(NodeTypeEnum.Service, - * propertiesToMatch, ServiceMetadataData.class); if - * (componentsNodes.isRight() && componentsNodes.right().value() != - * TitanOperationStatus.NOT_FOUND) { return - * Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus - * (componentsNodes.right().value())); } List<ServiceMetadataData> - * certifiedHighest = (componentsNodes.isLeft() ? - * componentsNodes.left().value() : new - * ArrayList<ServiceMetadataData>()); + * propertiesToMatch.put(GraphPropertiesDictionary. IS_HIGHEST_VERSION.getProperty(), true); Either<List<ServiceMetadataData>, TitanOperationStatus> componentsNodes = titanGenericDao.getByCriteria(NodeTypeEnum.Service, propertiesToMatch, + * ServiceMetadataData.class); if (componentsNodes.isRight() && componentsNodes.right().value() != TitanOperationStatus.NOT_FOUND) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus + * (componentsNodes.right().value())); } List<ServiceMetadataData> certifiedHighest = (componentsNodes.isLeft() ? componentsNodes.left().value() : new ArrayList<ServiceMetadataData>()); */ - Either<List<ServiceMetadataData>, TitanOperationStatus> listOfHighestComponents = this - .getListOfHighestComponents(NodeTypeEnum.Service, ServiceMetadataData.class); - if (listOfHighestComponents.isRight() - && listOfHighestComponents.right().value() != TitanOperationStatus.NOT_FOUND) { - return Either.right( - DaoStatusConverter.convertTitanStatusToStorageStatus(listOfHighestComponents.right().value())); + Either<List<ServiceMetadataData>, TitanOperationStatus> listOfHighestComponents = this.getListOfHighestComponents(NodeTypeEnum.Service, ServiceMetadataData.class); + if (listOfHighestComponents.isRight() && listOfHighestComponents.right().value() != TitanOperationStatus.NOT_FOUND) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(listOfHighestComponents.right().value())); } List<ServiceMetadataData> notCertifiedHighest = listOfHighestComponents.left().value(); @@ -1216,41 +976,29 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper // fetch from cache long startFetchAllFromCache = System.currentTimeMillis(); - Map<String, Long> components = notCertifiedHighest.stream() - .collect(Collectors.toMap(p -> p.getMetadataDataDefinition().getUniqueId(), - p -> p.getMetadataDataDefinition().getLastUpdateDate())); + Map<String, Long> components = notCertifiedHighest.stream().collect(Collectors.toMap(p -> p.getMetadataDataDefinition().getUniqueId(), p -> p.getMetadataDataDefinition().getLastUpdateDate())); - Either<ImmutablePair<List<Component>, Set<String>>, ActionStatus> componentsFromCacheForCatalog = this - .getComponentsFromCacheForCatalog(components, ComponentTypeEnum.SERVICE); + Either<ImmutablePair<List<Component>, Set<String>>, ActionStatus> componentsFromCacheForCatalog = this.getComponentsFromCacheForCatalog(components, ComponentTypeEnum.SERVICE); if (componentsFromCacheForCatalog.isLeft()) { - ImmutablePair<List<Component>, Set<String>> immutablePair = componentsFromCacheForCatalog.left() - .value(); + ImmutablePair<List<Component>, Set<String>> immutablePair = componentsFromCacheForCatalog.left().value(); List<Component> list = immutablePair.getLeft(); if (list != null) { for (Component component : list) { result.add((Service) component); } - List<String> addedUids = list.stream() - .map(p -> p.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId()) - .collect(Collectors.toList()); - notCertifiedHighest = notCertifiedHighest.stream() - .filter(p -> false == addedUids.contains(p.getMetadataDataDefinition().getUniqueId())) - .collect(Collectors.toList()); + List<String> addedUids = list.stream().map(p -> p.getComponentMetadataDefinition().getMetadataDataDefinition().getUniqueId()).collect(Collectors.toList()); + notCertifiedHighest = notCertifiedHighest.stream().filter(p -> false == addedUids.contains(p.getMetadataDataDefinition().getUniqueId())).collect(Collectors.toList()); } } long endFetchAllFromCache = System.currentTimeMillis(); - log.debug("Fetch all catalog services metadata from cache took {} ms", - (endFetchAllFromCache - startFetchAllFromCache)); + log.debug("Fetch all catalog services metadata from cache took {} ms", (endFetchAllFromCache - startFetchAllFromCache)); log.debug("The number of services added to catalog from cache is {}", result.size()); - log.debug("The number of services needed to be fetch as light component is {}", - notCertifiedHighest.size()); + log.debug("The number of services needed to be fetch as light component is {}", notCertifiedHighest.size()); for (ServiceMetadataData data : notCertifiedHighest) { - Either<Service, StorageOperationStatus> component = getLightComponent( - data.getMetadataDataDefinition().getUniqueId(), inTransaction); + Either<Service, StorageOperationStatus> component = getLightComponent(data.getMetadataDataDefinition().getUniqueId(), inTransaction); if (component.isRight()) { - log.debug("Failed to get Service for id = {}, error : {}. Skip service", data.getUniqueId(), - component.right().value()); + log.debug("Failed to get Service for id = {}, error : {}. Skip service", data.getUniqueId(), component.right().value()); } else { result.add(component.left().value()); } @@ -1261,19 +1009,17 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper if (false == inTransaction) { titanGenericDao.commit(); } - log.debug("Fetch all catalog services took " + (System.currentTimeMillis() - start) + " ms"); + log.debug("Fetch all catalog services took {} ms",(System.currentTimeMillis() - start)); } } - public Either<List<Service>, StorageOperationStatus> getServiceCatalogDataLatestCertifiedAndNotCertified( - boolean inTransaction) { + public Either<List<Service>, StorageOperationStatus> getServiceCatalogDataLatestCertifiedAndNotCertified(boolean inTransaction) { Map<String, Object> properties = new HashMap<>(); properties.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true); List<Service> result = new ArrayList<>(); - Either<List<ServiceMetadataData>, TitanOperationStatus> lastVersionNodes = titanGenericDao - .getByCriteria(NodeTypeEnum.Service, properties, ServiceMetadataData.class); + Either<List<ServiceMetadataData>, TitanOperationStatus> lastVersionNodes = titanGenericDao.getByCriteria(NodeTypeEnum.Service, properties, ServiceMetadataData.class); if (lastVersionNodes.isRight() && lastVersionNodes.right().value() != TitanOperationStatus.NOT_FOUND) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(lastVersionNodes.right().value())); @@ -1288,11 +1034,9 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper } for (ServiceMetadataData data : latestServices) { - Either<Service, StorageOperationStatus> component = getLightComponent( - data.getMetadataDataDefinition().getUniqueId(), inTransaction); + Either<Service, StorageOperationStatus> component = getLightComponent(data.getMetadataDataDefinition().getUniqueId(), inTransaction); if (component.isRight()) { - log.debug("Failed to get Service for id = " + data.getUniqueId() + " error : " - + component.right().value() + " skip resource"); + log.debug("Failed to get Service for id = {} error : {} skip resource",data.getUniqueId(),component.right().value()); } else { result.add(component.left().value()); } @@ -1302,25 +1046,21 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper } - private Either<List<Service>, StorageOperationStatus> getServiceListByCriteria(Map<String, Object> props, - boolean inTransaction) { + private Either<List<Service>, StorageOperationStatus> getServiceListByCriteria(Map<String, Object> props, boolean inTransaction) { props.put(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Service.getName()); - Either<List<ServiceMetadataData>, TitanOperationStatus> byCriteria = titanGenericDao - .getByCriteria(NodeTypeEnum.Service, props, ServiceMetadataData.class); + Either<List<ServiceMetadataData>, TitanOperationStatus> byCriteria = titanGenericDao.getByCriteria(NodeTypeEnum.Service, props, ServiceMetadataData.class); if (byCriteria.isRight()) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(byCriteria.right().value())); } - List<Service> services = new ArrayList<Service>(); + List<Service> services = new ArrayList<>(); List<ServiceMetadataData> servicesDataList = byCriteria.left().value(); for (ServiceMetadataData data : servicesDataList) { - Either<Service, StorageOperationStatus> service = getService(data.getMetadataDataDefinition().getUniqueId(), - inTransaction); + Either<Service, StorageOperationStatus> service = getService(data.getMetadataDataDefinition().getUniqueId(), inTransaction); if (service.isLeft()) { services.add(service.left().value()); } else { - log.debug("Failed to fetch resource for name = " + data.getMetadataDataDefinition().getName() - + " and id = " + data.getUniqueId()); + log.debug("Failed to fetch resource for name = {} and id = {}",data.getMetadataDataDefinition().getName(),data.getUniqueId()); } } return Either.left(services); @@ -1334,8 +1074,7 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper return getLatestServiceByUuid(uuid, true, inTransaction); } - private Either<List<Service>, StorageOperationStatus> getLatestServiceByUuid(String uuid, boolean isLatest, - boolean inTransaction) { + private Either<List<Service>, StorageOperationStatus> getLatestServiceByUuid(String uuid, boolean isLatest, boolean inTransaction) { Map<String, Object> props = new HashMap<String, Object>(); if (isLatest) { @@ -1346,17 +1085,23 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper return getServiceListByCriteria(props, inTransaction); } - public Either<List<Service>, StorageOperationStatus> getServiceListBySystemName(String systemName, - boolean inTransaction) { + @Override + public Either<List<Service>, StorageOperationStatus> getAll() { + Either<List<Service>, StorageOperationStatus> serviceListByCriteria = getServiceListByCriteria(new HashMap<>(), false); + if (serviceListByCriteria.isRight() && serviceListByCriteria.right().value() == StorageOperationStatus.NOT_FOUND) { + return Either.left(Collections.emptyList()); + } + return serviceListByCriteria; + } + + public Either<List<Service>, StorageOperationStatus> getServiceListBySystemName(String systemName, boolean inTransaction) { Map<String, Object> props = new HashMap<String, Object>(); props.put(GraphPropertiesDictionary.SYSTEM_NAME.getProperty(), systemName); return getServiceListByCriteria(props, inTransaction); } - public Either<Service, StorageOperationStatus> getServiceByNameAndVersion(String name, String version, - Map<String, Object> additionalParams, boolean inTransaction) { - return getByNamesAndVersion(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), - ValidationUtils.normaliseComponentName(name), version, additionalParams, inTransaction); + public Either<Service, StorageOperationStatus> getServiceByNameAndVersion(String name, String version, Map<String, Object> additionalParams, boolean inTransaction) { + return getByNamesAndVersion(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), ValidationUtils.normaliseComponentName(name), version, additionalParams, inTransaction); } @Override @@ -1364,8 +1109,7 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper return getServiceByNameAndVersion(name, version, null, false); } - protected Either<Service, StorageOperationStatus> getByNamesAndVersion(String nameKey, String nameValue, - String version, Map<String, Object> additionalParams, boolean inTransaction) { + protected Either<Service, StorageOperationStatus> getByNamesAndVersion(String nameKey, String nameValue, String version, Map<String, Object> additionalParams, boolean inTransaction) { Map<String, Object> props = new HashMap<String, Object>(); props.put(nameKey, nameValue); props.put(GraphPropertiesDictionary.VERSION.getProperty(), version); @@ -1374,8 +1118,7 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper props.putAll(additionalParams); } - Either<List<ServiceMetadataData>, TitanOperationStatus> byCriteria = titanGenericDao - .getByCriteria(NodeTypeEnum.Service, props, ServiceMetadataData.class); + Either<List<ServiceMetadataData>, TitanOperationStatus> byCriteria = titanGenericDao.getByCriteria(NodeTypeEnum.Service, props, ServiceMetadataData.class); if (byCriteria.isRight()) { return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(byCriteria.right().value())); @@ -1383,40 +1126,33 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper List<ServiceMetadataData> dataList = byCriteria.left().value(); if (dataList != null && !dataList.isEmpty()) { if (dataList.size() > 1) { - log.debug("More that one instance of resource for name =" + nameValue + " and version = " + version); + log.debug("More that one instance of resource for name ={} and version = {}",nameValue,version); return Either.right(StorageOperationStatus.GENERAL_ERROR); } ServiceMetadataData serviceData = dataList.get(0); - Either<Service, StorageOperationStatus> service = getService( - serviceData.getMetadataDataDefinition().getUniqueId(), inTransaction); + Either<Service, StorageOperationStatus> service = getService(serviceData.getMetadataDataDefinition().getUniqueId(), inTransaction); if (service.isRight()) { - log.debug("Failed to fetch resource for name = " + serviceData.getMetadataDataDefinition().getName() - + " and id = " + serviceData.getMetadataDataDefinition().getUniqueId()); + log.debug("Failed to fetch resource for name = {} and id = {}",serviceData.getMetadataDataDefinition().getName(),serviceData.getMetadataDataDefinition().getUniqueId()); } return service; } return Either.right(StorageOperationStatus.NOT_FOUND); } - protected <T> Either<T, StorageOperationStatus> getComponentByNameAndVersion(String name, String version, - Map<String, Object> additionalParams, boolean inTransaction) { - return (Either<T, StorageOperationStatus>) getServiceByNameAndVersion(name, version, additionalParams, - inTransaction); + protected <T> Either<T, StorageOperationStatus> getComponentByNameAndVersion(String name, String version, Map<String, Object> additionalParams, boolean inTransaction) { + return (Either<T, StorageOperationStatus>) getServiceByNameAndVersion(name, version, additionalParams, inTransaction); } @Override - public Either<Service, StorageOperationStatus> getServiceBySystemNameAndVersion(String name, String version, - boolean inTransaction) { - return getByNamesAndVersion(GraphPropertiesDictionary.SYSTEM_NAME.getProperty(), name, version, null, - inTransaction); + public Either<Service, StorageOperationStatus> getServiceBySystemNameAndVersion(String name, String version, boolean inTransaction) { + return getByNamesAndVersion(GraphPropertiesDictionary.SYSTEM_NAME.getProperty(), name, version, null, inTransaction); } private TitanOperationStatus setServiceAdditionalInformationFromGraph(String uniqueId, Service service) { List<AdditionalInformationDefinition> additionalInformation = new ArrayList<>(); - Either<AdditionalInformationDefinition, TitanOperationStatus> either = additionalInformationOperation - .getAllAdditionalInformationParameters(NodeTypeEnum.Service, uniqueId, true); + Either<AdditionalInformationDefinition, TitanOperationStatus> either = additionalInformationOperation.getAllAdditionalInformationParameters(NodeTypeEnum.Service, uniqueId, true); if (either.isRight()) { TitanOperationStatus status = either.right().value(); @@ -1436,8 +1172,7 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper } private TitanOperationStatus setAllVersions(Service service) { - Either<Map<String, String>, TitanOperationStatus> res = getVersionList(NodeTypeEnum.Service, - service.getVersion(), service, ServiceMetadataData.class); + Either<Map<String, String>, TitanOperationStatus> res = getVersionList(NodeTypeEnum.Service, service.getVersion(), service, ServiceMetadataData.class); if (res.isRight()) { return res.right().value(); } @@ -1445,8 +1180,7 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper return TitanOperationStatus.OK; } - public Either<List<ArtifactDefinition>, StorageOperationStatus> getAdditionalArtifacts(String resourceId, - boolean recursively, boolean inTransaction) { + public Either<List<ArtifactDefinition>, StorageOperationStatus> getAdditionalArtifacts(String resourceId, boolean recursively, boolean inTransaction) { List<ArtifactDefinition> artifacts = new ArrayList<>(); return Either.left(artifacts); } @@ -1466,40 +1200,33 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper @SuppressWarnings("unchecked") @Override - public <T> Either<T, StorageOperationStatus> cloneComponent(T other, String version, - LifecycleStateEnum targetLifecycle, boolean inTransaction) { - return (Either<T, StorageOperationStatus>) cloneService((Service) other, version, targetLifecycle, - inTransaction); + public <T> Either<T, StorageOperationStatus> cloneComponent(T other, String version, LifecycleStateEnum targetLifecycle, boolean inTransaction) { + return (Either<T, StorageOperationStatus>) cloneService((Service) other, version, targetLifecycle, inTransaction); } @Override - public Either<Integer, StorageOperationStatus> increaseAndGetComponentInstanceCounter(String componentId, - boolean inTransaction) { + public Either<Integer, StorageOperationStatus> increaseAndGetComponentInstanceCounter(String componentId, boolean inTransaction) { return increaseAndGetComponentInstanceCounter(componentId, NodeTypeEnum.Service, inTransaction); } @Override - protected StorageOperationStatus validateCategories(Component currentComponent, Component component, - ComponentMetadataData componentData, NodeTypeEnum type) { + protected StorageOperationStatus validateCategories(Component currentComponent, Component component, ComponentMetadataData componentData, NodeTypeEnum type) { List<CategoryDefinition> newcategories = component.getCategories(); CategoryDefinition newCat = newcategories.get(0); CategoryDefinition currentCategory = currentComponent.getCategories().get(0); StorageOperationStatus status = StorageOperationStatus.OK; if (newCat != null && newCat.getName() != null && false == newCat.getName().equals(currentCategory.getName())) { - log.debug( - "Going to update the category of the resource from " + currentCategory + " to " + newCat.getName()); + log.debug("Going to update the category of the resource from {} to {}",currentCategory,newCat.getName()); status = moveCategoryEdge(component, componentData, newCat, type); - log.debug("Going to update the category of the resource from " + currentCategory + " to " + newCat.getName() - + ". status is " + status); + log.debug("Going to update the category of the resource from {} to {}. status is {}",currentCategory,newCat.getName(),status); } return status; } @Override - protected <T extends Component> StorageOperationStatus updateDerived(Component component, - Component currentComponent, ComponentMetadataData componentData, Class<T> clazz) { + protected <T extends Component> StorageOperationStatus updateDerived(Component component, Component currentComponent, ComponentMetadataData componentData, Class<T> clazz) { log.debug("Derived class isn't supported for resource"); return null; } @@ -1525,8 +1252,7 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper } @Override - public Either<Component, StorageOperationStatus> markComponentToDelete(Component componentToDelete, - boolean inTransaction) { + public Either<Component, StorageOperationStatus> markComponentToDelete(Component componentToDelete, boolean inTransaction) { return internalMarkComponentToDelete(componentToDelete, inTransaction); } @@ -1542,8 +1268,7 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper @SuppressWarnings("unchecked") @Override - public <T> Either<T, StorageOperationStatus> getComponent(String id, - ComponentParametersView componentParametersView, boolean inTransaction) { + public <T> Either<T, StorageOperationStatus> getComponent(String id, ComponentParametersView componentParametersView, boolean inTransaction) { Either<Service, StorageOperationStatus> component = getService(id, componentParametersView, inTransaction); if (component.isRight()) { @@ -1552,15 +1277,13 @@ public class ServiceOperation extends ComponentOperation implements IServiceOper return (Either<T, StorageOperationStatus>) component; } - public Either<Service, StorageOperationStatus> updateService(Service service, boolean inTransaction, - ComponentParametersView filterResultView) { - return (Either<Service, StorageOperationStatus>) updateComponentFilterResult(service, inTransaction, - titanGenericDao, service.getClass(), NodeTypeEnum.Service, filterResultView); + public Either<Service, StorageOperationStatus> updateService(Service service, boolean inTransaction, ComponentParametersView filterResultView) { + return (Either<Service, StorageOperationStatus>) updateComponentFilterResult(service, inTransaction, titanGenericDao, service.getClass(), NodeTypeEnum.Service, filterResultView); } @Override - protected <T> Either<T, StorageOperationStatus> updateComponentFilterResult(T component, boolean inTransaction, - ComponentParametersView filterResultView) { + protected <T> Either<T, StorageOperationStatus> updateComponentFilterResult(T component, boolean inTransaction, ComponentParametersView filterResultView) { return (Either<T, StorageOperationStatus>) updateService((Service) component, inTransaction, filterResultView); } + } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ToscaDefinitionPathCalculatorImpl.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ToscaDefinitionPathCalculatorImpl.java new file mode 100644 index 0000000000..01a730a052 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ToscaDefinitionPathCalculatorImpl.java @@ -0,0 +1,27 @@ +package org.openecomp.sdc.be.model.operations.impl; + +import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; +import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.operations.api.ToscaDefinitionPathCalculator; +import org.springframework.stereotype.Component; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +@Component("tosca-path-calculator") +public class ToscaDefinitionPathCalculatorImpl implements ToscaDefinitionPathCalculator { + + @Override + public List<String> calculateToscaDefinitionPath(ComponentInstance componentInstance, GraphEdge edge) { + String ownerId = getCapReqOwner(edge); + String instanceId = componentInstance.getUniqueId(); + return ownerId.equals(instanceId) ? Collections.singletonList(instanceId) : Arrays.asList(instanceId, ownerId); + } + + private String getCapReqOwner(GraphEdge edge) { + String ownerIdKey = GraphEdgePropertiesDictionary.OWNER_ID.getProperty(); + return (String)edge.getProperties().get(ownerIdKey); + } +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UniqueIdBuilder.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UniqueIdBuilder.java index c4bcf6d907..eb5d8f6797 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UniqueIdBuilder.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UniqueIdBuilder.java @@ -24,22 +24,24 @@ import java.util.HashMap; import java.util.Map; import java.util.UUID; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.resources.data.ResourceCategoryData; import org.openecomp.sdc.be.resources.data.ServiceCategoryData; import org.openecomp.sdc.be.resources.data.TagData; import org.openecomp.sdc.be.resources.data.UserData; +import org.openecomp.sdc.common.util.ValidationUtils; public class UniqueIdBuilder { private static String DOT = "."; private static final String HEAT_PARAM_PREFIX = "heat_"; - + public static String buildPropertyUniqueId(String resourceId, String propertyName) { return resourceId + DOT + propertyName; } - + public static String buildHeatParameterUniqueId(String resourceId, String propertyName) { return resourceId + DOT + HEAT_PARAM_PREFIX + propertyName; } @@ -103,7 +105,9 @@ public class UniqueIdBuilder { public static String buildAttributeUid(String resourceId, String attName) { return NodeTypeEnum.Attribute.getName() + DOT + resourceId + DOT + attName; } - + public static String buildArtifactUid(String parentId, String label) { + return parentId + DOT + label; + } public static String buildRequirementUid(String resourceId, String reqName) { return resourceId + DOT + reqName; } @@ -125,9 +129,8 @@ public class UniqueIdBuilder { public static String buildPropertyValueUniqueId(String parentId, String paramName) { return NodeTypeEnum.PropertyValue.getName() + DOT + parentId + DOT + paramName; } - - public static String buildArtifactByInterfaceUniqueId(String resourceId, String interfaceName, String operation, - String artifactLabel) { + + public static String buildArtifactByInterfaceUniqueId(String resourceId, String interfaceName, String operation, String artifactLabel) { return resourceId + DOT + interfaceName + DOT + operation + DOT + artifactLabel; } @@ -141,8 +144,7 @@ public class UniqueIdBuilder { // return resourceId + DOT + interfaceName + DOT +operation + DOT + // artifactLabel; // } - public static String buildArtifactByInterfaceUniqueIdAndRsrcId(String resourceId, String interfaceName, - String operation, String artifactLabel) { + public static String buildArtifactByInterfaceUniqueIdAndRsrcId(String resourceId, String interfaceName, String operation, String artifactLabel) { return resourceId + DOT + interfaceName + DOT + operation + DOT + artifactLabel; } @@ -183,6 +185,9 @@ public class UniqueIdBuilder { public static String buildCategoryUid(String categoryName, NodeTypeEnum type) { return type.getName() + DOT + categoryName; } + public static String buildComponentCategoryUid(String categoryName, VertexTypeEnum type) { + return type.getName() + DOT + ValidationUtils.normalizeCategoryName4Uniqueness(categoryName); + } public static String buildSubCategoryUid(String categoryUid, String subCategoryName) { return categoryUid + DOT + subCategoryName; @@ -195,6 +200,10 @@ public class UniqueIdBuilder { public static String buildResourceInstancePropertyValueUid(String resourceInstanceUniqueId, Integer index) { return resourceInstanceUniqueId + DOT + "property" + DOT + index; } + + public static String buildComponentPropertyUniqueId(String resourceId, String propertyName) { + return NodeTypeEnum.Property.getName() + DOT + resourceId + DOT + propertyName; + } public static String buildResourceInstanceAttributeValueUid(String resourceInstanceUniqueId, Integer index) { return resourceInstanceUniqueId + DOT + "attribute" + DOT + index; @@ -236,7 +245,7 @@ public class UniqueIdBuilder { return groupUniqueId + DOT + "property" + DOT + index; } - + public static String buildUserFunctionalMenuUid(String userId) { return userId + DOT + "functionalmenu"; diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperation.java index 85bb56f39f..7c45f8f384 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperation.java @@ -20,11 +20,8 @@ package org.openecomp.sdc.be.model.operations.impl; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import com.thinkaurelius.titan.core.TitanVertex; +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.tinkerpop.gremlin.structure.Direction; import org.apache.tinkerpop.gremlin.structure.Edge; @@ -47,20 +44,24 @@ import org.openecomp.sdc.common.datastructure.Wrapper; import org.openecomp.sdc.common.util.MethodActivationStatusEnum; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; -import com.thinkaurelius.titan.core.TitanVertex; - -import fj.data.Either; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; @Component("user-operation") public class UserAdminOperation implements IUserAdminOperation { - @javax.annotation.Resource private TitanGenericDao titanGenericDao; - public UserAdminOperation() { + public UserAdminOperation(@Qualifier("titan-generic-dao") TitanGenericDao titanGenericDao) { super(); + this.titanGenericDao = titanGenericDao; + } private static Logger log = LoggerFactory.getLogger(UserAdminOperation.class.getName()); @@ -132,8 +133,7 @@ public class UserAdminOperation implements IUserAdminOperation { } } - private void validateUserExists(Wrapper<Either<User, ActionStatus>> resultWrapper, Wrapper<UserData> userWrapper, - String id) { + private void validateUserExists(Wrapper<Either<User, ActionStatus>> resultWrapper, Wrapper<UserData> userWrapper, String id) { Either<User, ActionStatus> result; if (id == null) { log.info("User userId is empty"); @@ -142,19 +142,10 @@ public class UserAdminOperation implements IUserAdminOperation { return; } id = id.toLowerCase(); - Either<UserData, TitanOperationStatus> either = titanGenericDao - .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), id, UserData.class); + Either<UserData, TitanOperationStatus> either = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), id, UserData.class); if (either.isRight()) { - if (either.right().value() == TitanOperationStatus.NOT_FOUND) { - log.debug("User with userId {} not found", id); - result = Either.right(ActionStatus.USER_NOT_FOUND); - resultWrapper.setInnerElement(result); - } else { - log.debug("Problem get User with userId {}. Reason - {}", id, either.right().value().name()); - result = Either.right(ActionStatus.GENERAL_ERROR); - resultWrapper.setInnerElement(result); - } + resultWrapper.setInnerElement(getUserNotFoundError(id, either.right().value())); } else { userWrapper.setInnerElement(either.left().value()); } @@ -168,10 +159,10 @@ public class UserAdminOperation implements IUserAdminOperation { UserData userData = convertToUserData(user); result = titanGenericDao.createNode(userData, UserData.class); if (result.isRight()) { - log.debug("Problem while saving User {}. Reason - {}", userData.toString(), result.right().value().name()); + log.debug("Problem while saving User {}. Reason - {}",userData.toString(),result.right().value().name()); return Either.right(StorageOperationStatus.GENERAL_ERROR); } - log.debug("User {} saved successfully", userData.toString()); + log.debug("User {} saved successfully",userData.toString()); return Either.left(convertToUser(result.left().value())); } finally { @@ -194,10 +185,10 @@ public class UserAdminOperation implements IUserAdminOperation { UserData userData = convertToUserData(user); result = titanGenericDao.updateNode(userData, UserData.class); if (result.isRight()) { - log.debug("Problem while updating User {}. Reason - {}", userData.toString(), result.right().value().name()); + log.debug("Problem while updating User {}. Reason - {}",userData.toString(),result.right().value().name()); return Either.right(StorageOperationStatus.GENERAL_ERROR); } - log.debug("User {} updated successfully", userData.toString()); + log.debug("User {} updated successfully",userData.toString()); return Either.left(convertToUser(result.left().value())); } finally { @@ -229,10 +220,9 @@ public class UserAdminOperation implements IUserAdminOperation { @Override public Either<User, ActionStatus> deleteUserData(String id) { Either<User, ActionStatus> result; - Either<UserData, TitanOperationStatus> eitherGet = titanGenericDao - .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), id, UserData.class); + Either<UserData, TitanOperationStatus> eitherGet = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), id, UserData.class); if (eitherGet.isRight()) { - log.debug("Problem while retriving user with userId {}", id); + log.debug("Problem while retriving user with userId {}",id); if (eitherGet.right().value() == TitanOperationStatus.NOT_FOUND) { result = Either.right(ActionStatus.USER_NOT_FOUND); } else { @@ -264,11 +254,11 @@ public class UserAdminOperation implements IUserAdminOperation { private void deleteUser(Wrapper<Either<User, ActionStatus>> resultWrapper, UserData userData) { Either<UserData, TitanOperationStatus> eitherDelete = titanGenericDao.deleteNode(userData, UserData.class); if (eitherDelete.isRight()) { - log.debug("Problem while deleting User {}. Reason - {}", userData.toString(), eitherDelete.right().value().name()); + log.debug("Problem while deleting User {}. Reason - {}",userData.toString(),eitherDelete.right().value().name()); Either<User, ActionStatus> result = Either.right(ActionStatus.GENERAL_ERROR); resultWrapper.setInnerElement(result); } else { - log.debug("User {} deleted successfully", userData.toString()); + log.debug("User {} deleted successfully",userData.toString()); Either<User, ActionStatus> result = Either.left(convertToUser(eitherDelete.left().value())); resultWrapper.setInnerElement(result); } @@ -277,10 +267,9 @@ public class UserAdminOperation implements IUserAdminOperation { private void validateUserHasNoConnections(Wrapper<Either<User, ActionStatus>> resultWrapper, UserData userData) { if (resultWrapper.isEmpty()) { - Either<List<Edge>, TitanOperationStatus> edgesForNode = titanGenericDao.getEdgesForNode(userData, - Direction.BOTH); + Either<List<Edge>, TitanOperationStatus> edgesForNode = titanGenericDao.getEdgesForNode(userData, Direction.BOTH); if (edgesForNode.isRight()) { - log.debug("Problem while deleting User {}. Reason - {}", userData.toString(), edgesForNode.right().value().name()); + log.debug("Problem while deleting User {}. Reason - {}",userData.toString(),edgesForNode.right().value().name()); Either<User, ActionStatus> result = Either.right(ActionStatus.GENERAL_ERROR); resultWrapper.setInnerElement(result); } else { @@ -293,35 +282,31 @@ public class UserAdminOperation implements IUserAdminOperation { } } - public Either<List<Edge>, StorageOperationStatus> getUserPandingTasksList(User user, - Map<String, Object> properties) { + public Either<List<Edge>, StorageOperationStatus> getUserPandingTasksList(User user, Map<String, Object> properties) { UserData userData = convertToUserData(user); - Either<TitanVertex, TitanOperationStatus> vertexUser = titanGenericDao - .getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), user.getUserId()); + Either<TitanVertex, TitanOperationStatus> vertexUser = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), user.getUserId()); if (vertexUser.isRight()) { - log.debug("Problem while deleting User {}. Reason - {}", userData.toString(), vertexUser.right().value().name()); + log.debug("Problem while deleting User {}. Reason - {}",userData.toString(),vertexUser.right().value().name()); return Either.right(StorageOperationStatus.GENERAL_ERROR); } List<Edge> pandingTasks = new ArrayList<>(); - Either<List<Edge>, TitanOperationStatus> edges = titanGenericDao - .getOutgoingEdgesByCriteria(vertexUser.left().value(), GraphEdgeLabels.STATE, properties); + Either<List<Edge>, TitanOperationStatus> edges = titanGenericDao.getOutgoingEdgesByCriteria(vertexUser.left().value(), GraphEdgeLabels.STATE, properties); if (edges.isRight() || edges.left().value() == null) { if (edges.right().value() == TitanOperationStatus.NOT_FOUND) { return Either.left(pandingTasks); } else { - log.debug("Problem while deleting User {}", userData.toString(), edges.right().value().name()); + log.debug("Problem while deleting User {}. Reason - ",userData.toString(),edges.right().value().name()); return Either.right(StorageOperationStatus.GENERAL_ERROR); } } for (Edge edge : edges.left().value()) { Vertex componentVertex = edge.inVertex(); - VertexProperty<Object> property = componentVertex - .property(GraphPropertiesDictionary.IS_DELETED.getProperty()); + VertexProperty<Object> property = componentVertex.property(GraphPropertiesDictionary.IS_DELETED.getProperty()); if (!property.isPresent()) { pandingTasks.add(edge); } else { @@ -347,35 +332,64 @@ public class UserAdminOperation implements IUserAdminOperation { propertiesToMatch.put(GraphPropertiesDictionary.USER_STATUS.getProperty(), status); } - Either<List<UserData>, TitanOperationStatus> userNodes = titanGenericDao.getByCriteria(NodeTypeEnum.User, - propertiesToMatch, UserData.class); + Either<List<UserData>, TitanOperationStatus> userNodes = titanGenericDao.getByCriteria(NodeTypeEnum.User, propertiesToMatch, UserData.class); titanGenericDao.commit(); - if (userNodes.isRight()) { - // in case of NOT_FOUND from Titan return empty list - if (userNodes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { - return Either.left(result); - } else { - log.error("Problem while getting all users with role {}. Reason - {}", role, userNodes.right().value().name()); - return Either.right(ActionStatus.GENERAL_ERROR); - } - } else { - List<UserData> userDataList = userNodes.left().value(); - if (userDataList != null) { - for (UserData userData : userDataList) { - User user = convertToUser(userData); - result.add(user); - } - return Either.left(result); - } - log.debug("No users were found with role {}", role); - return Either.left(result); - } + return convertToUsers(role, userNodes); } finally { titanGenericDao.commit(); } } + private Either<List<User>, ActionStatus> convertToUsers(String role, Either<List<UserData>, TitanOperationStatus> userNodes) { + + if (userNodes.isRight()) { + // in case of NOT_FOUND from Titan return empty list + if (userNodes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { + return Either.left(Collections.emptyList()); + } else { + log.error("Problem while getting all users with role {}. Reason - {}", role, userNodes.right().value().name()); + return Either.right(ActionStatus.GENERAL_ERROR); + } + } else { + List<UserData> userDataList = userNodes.left().value(); + if (userDataList != null) { + return Either.left(convertToUsers(userDataList)); + } + log.debug("No users were found with role {}", role); + return Either.left(Collections.emptyList()); + } + } + + private List<User> convertToUsers(List<UserData> usersData) { + List<User> result = new ArrayList<>(); + for (UserData userData : usersData) { + User user = convertToUser(userData); + result.add(user); + } + return result; + } + + @Override + public Either<List<User>, ActionStatus> getAllUsers() { + try { + Either<List<UserData>, TitanOperationStatus> userNodes = titanGenericDao.getAll(NodeTypeEnum.User, UserData.class); + return convertToUsers("", userNodes); + } finally { + titanGenericDao.commit(); + } + } + + private Either<User, ActionStatus> getUserNotFoundError(String uid, TitanOperationStatus status) { + if (status == TitanOperationStatus.NOT_FOUND) { + log.debug("User with userId {} not found", uid); + return Either.right(ActionStatus.USER_NOT_FOUND); + } else { + log.debug("Problem get User with userId {}. Reason - {}", uid, status.name()); + return Either.right(ActionStatus.GENERAL_ERROR); + } + } + protected User convertToUser(UserData userData) { User user = new User(); user.setUserId(userData.getUserId()); @@ -403,6 +417,7 @@ public class UserAdminOperation implements IUserAdminOperation { return userData; } + @Override public Either<ImmutablePair<User, FunctionalMenuInfo>, ActionStatus> getUserDataWithFunctionalMenu(String userId) { Either<User, ActionStatus> userData = getUserData(userId, true, true); @@ -424,8 +439,7 @@ public class UserAdminOperation implements IUserAdminOperation { functionalMenuInfo.setFunctionalMenu(userFunctionalMenuData.getFunctionalMenu()); } - ImmutablePair<User, FunctionalMenuInfo> result = new ImmutablePair<User, FunctionalMenuInfo>(user, - functionalMenuInfo); + ImmutablePair<User, FunctionalMenuInfo> result = new ImmutablePair<User, FunctionalMenuInfo>(user, functionalMenuInfo); return Either.left(result); } @@ -441,8 +455,7 @@ public class UserAdminOperation implements IUserAdminOperation { userId = userId.toLowerCase(); String uid = UniqueIdBuilder.buildUserFunctionalMenuUid(userId); - Either<UserFunctionalMenuData, TitanOperationStatus> either = titanGenericDao.getNode( - UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.UserFunctionalMenu), uid, UserFunctionalMenuData.class); + Either<UserFunctionalMenuData, TitanOperationStatus> either = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.UserFunctionalMenu), uid, UserFunctionalMenuData.class); return either; } @@ -457,8 +470,7 @@ public class UserAdminOperation implements IUserAdminOperation { String uid = UniqueIdBuilder.buildUserFunctionalMenuUid(userId); UserFunctionalMenuData functionalMenuData = new UserFunctionalMenuData(newFunctionalMenu, uid); - Either<UserFunctionalMenuData, TitanOperationStatus> createNode = titanGenericDao - .createNode(functionalMenuData, UserFunctionalMenuData.class); + Either<UserFunctionalMenuData, TitanOperationStatus> createNode = titanGenericDao.createNode(functionalMenuData, UserFunctionalMenuData.class); if (createNode.isRight()) { return Either.right(createNode.right().value()); @@ -473,8 +485,7 @@ public class UserAdminOperation implements IUserAdminOperation { } else { UserFunctionalMenuData userFunctionalMenuData = functionalMenu.left().value(); userFunctionalMenuData.setFunctionalMenu(newFunctionalMenu); - Either<UserFunctionalMenuData, TitanOperationStatus> updateNode = titanGenericDao - .updateNode(userFunctionalMenuData, UserFunctionalMenuData.class); + Either<UserFunctionalMenuData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(userFunctionalMenuData, UserFunctionalMenuData.class); if (updateNode.isRight()) { return Either.right(updateNode.right().value()); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/migration/MigrationErrorInformer.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/migration/MigrationErrorInformer.java new file mode 100644 index 0000000000..952c0672cc --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/migration/MigrationErrorInformer.java @@ -0,0 +1,39 @@ +package org.openecomp.sdc.be.model.operations.migration; + +import org.apache.commons.lang3.StringUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * to be moved with all operations to the migration project + */ +@Deprecated +public class MigrationErrorInformer { + + private static Logger log = LoggerFactory.getLogger(MigrationErrorInformer.class); + private static Set<String> malformedVFs = new HashSet<>(); + + public static void addMalformedVF(String vfId) { + malformedVFs.add(vfId); + } + + public static void logIfServiceUsingMalformedVfs(Component service) { + List<ComponentInstance> componentInstances = service.getComponentInstances(); + if (componentInstances != null && !componentInstances.isEmpty() && !malformedVFs.isEmpty()) { + Set<String> serviceInstances = componentInstances.stream().map(ComponentInstance::getComponentUid).collect(Collectors.toSet()); + serviceInstances.retainAll(malformedVFs); + if (!serviceInstances.isEmpty()) { + log.error(String.format("Service %s is using malformed VFs: %s", service.getUniqueId(), StringUtils.join(serviceInstances, ','))); + } + } + } + + +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/utils/ComponentValidationUtils.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/utils/ComponentValidationUtils.java index fd6563ac4f..fe5d79a266 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/utils/ComponentValidationUtils.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/utils/ComponentValidationUtils.java @@ -20,11 +20,12 @@ package org.openecomp.sdc.be.model.operations.utils; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; -import org.openecomp.sdc.be.model.operations.api.IComponentOperation; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.IResourceOperation; import org.openecomp.sdc.be.model.operations.api.IServiceOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; @@ -56,52 +57,26 @@ public class ComponentValidationUtils { return true; } - public static boolean canWorkOnResource(String resourceId, IResourceOperation resourceOperation, - String userId) { - Either<Resource, StorageOperationStatus> getResourceResult = resourceOperation.getLightComponent(resourceId, - false); - - if (getResourceResult.isRight()) { - log.debug("Failed to retrive resource, resource id {}", resourceId); - return false; - } - Resource resource = getResourceResult.left().value(); - - return canWorkOnResource(resource, userId); - - } - - public static boolean canWorkOnService(String serviceId, IServiceOperation serviceOperation, String userId) { - Either<Service, StorageOperationStatus> getResourceResult = serviceOperation.getLightComponent(serviceId, - false); - - if (getResourceResult.isRight()) { - log.debug("Failed to retrieve service, service id {}", serviceId); - return false; - } - Service service = getResourceResult.left().value(); - - return canWorkOnComponent(service, userId); - - } - - public static boolean canWorkOnComponent(String componentId, IComponentOperation componentOperation, - String userId) { - Either<Component, StorageOperationStatus> getResourceResult = componentOperation.getLightComponent(componentId, - false); + public static boolean canWorkOnComponent(String componentId, ToscaOperationFacade toscaOperationFacade, String userId) { + + Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseMetadata); if (getResourceResult.isRight()) { log.debug("Failed to retrieve component, component id {}", componentId); return false; } - Component service = getResourceResult.left().value(); + Component component = getResourceResult.left().value(); - return canWorkOnComponent(service, userId); + return canWorkOnComponent(component, userId); } - + public static boolean canWorkOnComponent(Component component, String userId) { + return canWorkOnComponent(component.getLifecycleState(), component.getLastUpdaterUserId(), userId); + } + + private static boolean canWorkOnComponent(LifecycleStateEnum lifecycleState, String lastUpdaterUserId, String userId) { // verify resource is checked-out - if (component.getLifecycleState() != LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) { + if (lifecycleState != LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) { log.debug("resource is not checked-out"); return false; } @@ -113,7 +88,7 @@ public class ComponentValidationUtils { } // verify resource last update user is the current user - if (!userId.equals(component.getLastUpdaterUserId())) { + if (!userId.equals(lastUpdaterUserId)) { log.debug("resource last updater userId is not {}", userId); return false; } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/utils/GraphDeleteUtil.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/utils/GraphDeleteUtil.java index 1d78252de2..1671b2d98b 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/utils/GraphDeleteUtil.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/utils/GraphDeleteUtil.java @@ -58,41 +58,16 @@ public class GraphDeleteUtil { Map<String, Object> properties = null; if (log.isDebugEnabled()) { properties = getProperties(incomingVertex); - log.debug("Going to delete vertex {}", properties); + log.debug("Going to delete vertex {}",properties); } incomingVertex.remove(); if (log.isDebugEnabled()) { - log.debug("After deleting vertex {}", properties); + log.debug("After deleting vertex {}",properties); } } } - // - // if (edgesCreatorIterable != null) { - // for (Edge edge : edgesCreatorIterable) { - // - // Vertex incomingVertex = edge.getVertex(Direction.IN); - // Iterable<Edge> outEdges = incomingVertex.getEdges(Direction.OUT); - // if (outEdges != null) { - // if (outEdges.iterator().hasNext()) { - // return TitanOperationStatus.CANNOT_DELETE_NON_LEAF_NODE; - // } else { - // Map<String, Object> properties = null; - // if (log.isDebugEnabled()) { - // properties = ElementHelper.getProperties(incomingVertex); - // log.debug("Going to delete vertex {}", properties); - // } - // incomingVertex.remove(); - // if (log.isDebugEnabled()) { - // log.debug("After deleting vertex {}", properties); - // } - // } - // } - // - // } - // } - return TitanOperationStatus.OK; } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaPropertyType.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaPropertyType.java index 2bbb84dd20..079d64a60e 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaPropertyType.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaPropertyType.java @@ -58,34 +58,27 @@ public enum ToscaPropertyType { STRING("string", StringValidator.getInstance(), StringConvertor.getInstance(), ToscaStringConvertor.getInstance()), - BOOLEAN("boolean", BooleanValidator.getInstance(), ToscaBooleanConverter.getInstance(), - BooleanConverter.getInstance()), + BOOLEAN("boolean", BooleanValidator.getInstance(), ToscaBooleanConverter.getInstance(), BooleanConverter.getInstance()), FLOAT("float", FloatValidator.getInstance(), ToscaFloatConverter.getInstance(), FloatConverter.getInstance()), INTEGER("integer", IntegerValidator.getInstance(), DefaultConverter.getInstance(), IntegerConverter.getInstance()), - SCALAR_UNIT_SIZE("scalar-unit.size", StringValidator.getInstance(), DefaultConverter.getInstance(), - ToscaValueDefaultConverter.getInstance()), + SCALAR_UNIT_SIZE("scalar-unit.size", StringValidator.getInstance(), DefaultConverter.getInstance(), ToscaValueDefaultConverter.getInstance()), - SCALAR_UNIT_TIME("scalar-unit.time", StringValidator.getInstance(), DefaultConverter.getInstance(), - ToscaValueDefaultConverter.getInstance()), + SCALAR_UNIT_TIME("scalar-unit.time", StringValidator.getInstance(), DefaultConverter.getInstance(), ToscaValueDefaultConverter.getInstance()), - SCALAR_UNIT_FREQUENCY("scalar-unit.frequency", StringValidator.getInstance(), DefaultConverter.getInstance(), - ToscaValueDefaultConverter.getInstance()), + SCALAR_UNIT_FREQUENCY("scalar-unit.frequency", StringValidator.getInstance(), DefaultConverter.getInstance(), ToscaValueDefaultConverter.getInstance()), - RANGE("range", StringValidator.getInstance(), DefaultConverter.getInstance(), - ToscaValueDefaultConverter.getInstance()), + RANGE("range", StringValidator.getInstance(), DefaultConverter.getInstance(), ToscaValueDefaultConverter.getInstance()), - TIMESTAMP("timestamp", StringValidator.getInstance(), DefaultConverter.getInstance(), - ToscaValueDefaultConverter.getInstance()), + TIMESTAMP("timestamp", StringValidator.getInstance(), DefaultConverter.getInstance(), ToscaValueDefaultConverter.getInstance()), MAP("map", MapValidator.getInstance(), MapConverter.getInstance(), ToscaMapValueConverter.getInstance()), LIST("list", ListValidator.getInstance(), ListConverter.getInstance(), ToscaListValueConverter.getInstance()), - VERSION("version", StringValidator.getInstance(), DefaultConverter.getInstance(), - ToscaValueDefaultConverter.getInstance()), + VERSION("version", StringValidator.getInstance(), DefaultConverter.getInstance(), ToscaValueDefaultConverter.getInstance()), KEY("key", KeyValidator.getInstance(), StringConvertor.getInstance(), ToscaValueDefaultConverter.getInstance()), @@ -100,16 +93,14 @@ public enum ToscaPropertyType { private ToscaValueConverter valueConverter; private boolean isAbstract = false; - ToscaPropertyType(String type, PropertyTypeValidator validator, PropertyValueConverter converter, - ToscaValueConverter valueConverter) { + ToscaPropertyType(String type, PropertyTypeValidator validator, PropertyValueConverter converter, ToscaValueConverter valueConverter) { this.type = type; this.validator = validator; this.converter = converter; this.valueConverter = valueConverter; } - ToscaPropertyType(String type, PropertyTypeValidator validator, PropertyValueConverter converter, - ToscaValueConverter valueConverter, boolean isAbstract) { + ToscaPropertyType(String type, PropertyTypeValidator validator, PropertyValueConverter converter, ToscaValueConverter valueConverter, boolean isAbstract) { this(type, validator, converter, valueConverter); this.isAbstract = isAbstract; } @@ -179,6 +170,17 @@ public enum ToscaPropertyType { return isPrimitiveToscaType != null && isPrimitiveToscaType.isAbstract() == false; } + + public static boolean isPrimitiveType(String dataTypeName) { + + if (ToscaPropertyType.MAP.getType().equals(dataTypeName) || ToscaPropertyType.LIST.getType().equals(dataTypeName)){ + return false; + } + if(isScalarType(dataTypeName)){ + return true; + } + return false; + } public static ToscaPropertyType getTypeIfScalar(String dataTypeName) { diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatBooleanConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatBooleanConverter.java index 147b2e9c52..52fa9bfa81 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatBooleanConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatBooleanConverter.java @@ -39,7 +39,7 @@ public class HeatBooleanConverter implements PropertyValueConverter { @Override public String convert(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { - if (value == null) { + if (value == null || value.isEmpty()) { return null; } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatCommaDelimitedListConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatCommaDelimitedListConverter.java index a0834791ff..30c21c8c1c 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatCommaDelimitedListConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatCommaDelimitedListConverter.java @@ -39,11 +39,13 @@ public class HeatCommaDelimitedListConverter implements PropertyValueConverter { @Override public String convert(String original, String innerType, Map<String, DataTypeDefinition> dataTypes) { - String coverted = ValidationUtils.removeNoneUtf8Chars(original); - coverted = ValidationUtils.removeHtmlTagsOnly(coverted); - coverted = ValidationUtils.normaliseWhitespace(coverted); - coverted = ValidationUtils.stripOctets(coverted); - + String coverted = null; + if(original != null){ + coverted = ValidationUtils.removeNoneUtf8Chars(original); + coverted = ValidationUtils.removeHtmlTagsOnly(coverted); + coverted = ValidationUtils.normaliseWhitespace(coverted); + coverted = ValidationUtils.stripOctets(coverted); + } return coverted; } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatNumberConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatNumberConverter.java index 90781be367..8798b544bc 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatNumberConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatNumberConverter.java @@ -40,7 +40,7 @@ public class HeatNumberConverter implements PropertyValueConverter { @Override public String convert(String original, String innerType, Map<String, DataTypeDefinition> dataTypes) { - if (original == null) { + if (original == null || original.isEmpty()) { return null; } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatStringConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatStringConverter.java index 475db1db7c..c8fac11b3a 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatStringConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/HeatStringConverter.java @@ -39,12 +39,14 @@ public class HeatStringConverter implements PropertyValueConverter { @Override public String convert(String original, String innerType, Map<String, DataTypeDefinition> dataTypes) { - String coverted = ValidationUtils.removeNoneUtf8Chars(original); - coverted = ValidationUtils.normaliseWhitespace(coverted); - coverted = ValidationUtils.stripOctets(coverted); - coverted = ValidationUtils.removeHtmlTagsOnly(coverted); - coverted = coverted.replaceAll("\"", "").replaceAll("\'", ""); - + String coverted = null; + if(original != null){ + coverted = ValidationUtils.removeNoneUtf8Chars(original); + coverted = ValidationUtils.normaliseWhitespace(coverted); + coverted = ValidationUtils.stripOctets(coverted); + coverted = ValidationUtils.removeHtmlTagsOnly(coverted); + coverted = coverted.replaceAll("\"", "").replaceAll("\'", ""); + } return coverted; } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/IntegerConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/IntegerConverter.java index 076e5aceef..30fbf69b80 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/IntegerConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/IntegerConverter.java @@ -38,6 +38,9 @@ public class IntegerConverter implements ToscaValueConverter { @Override public Object convertToToscaValue(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { + if ( value == null || value.isEmpty() ){ + return null; + } return Integer.parseInt(value); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ListConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ListConverter.java index 8265cc2690..4f6de9b80c 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ListConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ListConverter.java @@ -112,6 +112,8 @@ public class ListConverter implements PropertyValueConverter { ArrayList<String> newList = new ArrayList<String>(); JsonArray jo = (JsonArray) jsonParser.parse(value); + if(ToscaPropertyType.JSON == innerToscaType) + return Either.left(value); int size = jo.size(); for (int i = 0; i < size; i++) { JsonElement currentValue = jo.get(i); @@ -166,7 +168,7 @@ public class ListConverter implements PropertyValueConverter { } } catch (JsonParseException e) { - log.debug("Failed to parse json : {}. {}", value, e); + log.debug("Failed to parse json : {}", value, e); BeEcompErrorManager.getInstance().logBeInvalidJsonInput("List Converter"); return Either.right(false); } @@ -199,7 +201,7 @@ public class ListConverter implements PropertyValueConverter { ImmutablePair<JsonElement, Boolean> validateAndUpdate = dataTypeValidatorConverter .validateAndUpdate(element, dataTypeDefinition, allDataTypes); if (validateAndUpdate.right.booleanValue() == false) { - log.debug("Cannot parse value {} from type {} in list position {}", currentValue, innerType, i); + log.debug("Cannot parse value {} from type {} in list position {}",currentValue,innerType,i); return Either.right(false); } JsonElement newValue = validateAndUpdate.left; diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/MapConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/MapConverter.java index 921c6d0d41..30b895f0d2 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/MapConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/MapConverter.java @@ -181,7 +181,7 @@ public class MapConverter implements PropertyValueConverter { log.debug("inner Tosca Type unknown : {}", innerToscaType); } } catch (JsonParseException e) { - log.debug("Failed to parse json : {}. {}", value, e); + log.debug("Failed to parse json : {}", value, e); BeEcompErrorManager.getInstance().logBeInvalidJsonInput("Map Converter"); return Either.right(false); } @@ -227,7 +227,7 @@ public class MapConverter implements PropertyValueConverter { ImmutablePair<JsonElement, Boolean> validateAndUpdate = dataTypeValidatorConverter .validateAndUpdate(element, dataTypeDefinition, allDataTypes); if (validateAndUpdate.right.booleanValue() == false) { - log.debug("Cannot parse value {} from type {} of key {}", currentValue, innerType, currentKey); + log.debug("Cannot parse value {} from type {} of key {}",currentValue,innerType,currentKey); return Either.right(false); } JsonElement newValue = validateAndUpdate.left; diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaListValueConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaListValueConverter.java index 043446e783..d8198dac6b 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaListValueConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaListValueConverter.java @@ -109,13 +109,14 @@ public class ToscaListValueConverter extends ToscaValueBaseConverter implements asJsonArray.forEach(e -> { Object convertedValue = null; if (isScalarF) { - log.debug("try to convert scalar value {}", e.getAsString()); - if (e.getAsString() == null) { + String jsonAsString = e.toString(); + log.debug("try to convert scalar value {}", jsonAsString); + if ( jsonAsString == null) { convertedValue = null; } else { - JsonElement singleElement = jsonParser.parse(e.getAsString()); + JsonElement singleElement = jsonParser.parse(jsonAsString); if (singleElement.isJsonPrimitive()) { - convertedValue = innerConverterFinal.convertToToscaValue(e.getAsString(), innerType, + convertedValue = innerConverterFinal.convertToToscaValue(jsonAsString, innerType, dataTypes); } else { convertedValue = handleComplexJsonValue(singleElement); @@ -128,16 +129,14 @@ public class ToscaListValueConverter extends ToscaValueBaseConverter implements DataTypeDefinition dataTypeDefinition = dataTypes.get(innerType); Map<String, PropertyDefinition> allProperties = getAllProperties(dataTypeDefinition); Map<String, Object> toscaObjectPresentation = new HashMap<>(); - // log.debug("try to convert datatype value {}", - // e.getAsString()); - + for (Entry<String, JsonElement> entry : entrySet) { String propName = entry.getKey(); JsonElement elementValue = entry.getValue(); PropertyDefinition propertyDefinition = allProperties.get(propName); if (propertyDefinition == null) { - log.debug("The property {} was not found under data type {}", propName, dataTypeDefinition.getName()); + log.debug("The property {} was not found under data type {}",propName,dataTypeDefinition.getName()); continue; // return null; } @@ -173,7 +172,7 @@ public class ToscaListValueConverter extends ToscaValueBaseConverter implements } catch ( JsonParseException e) { - log.debug("Failed to parse json : {}. {}", value, e); + log.debug("Failed to parse json : {}", value, e); BeEcompErrorManager.getInstance().logBeInvalidJsonInput("List Converter"); return null; } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaMapValueConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaMapValueConverter.java index 601d8f0fc8..80b8779e1e 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaMapValueConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaMapValueConverter.java @@ -21,7 +21,9 @@ package org.openecomp.sdc.be.model.tosca.converters; import java.io.StringReader; +import java.util.ArrayList; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; @@ -33,6 +35,7 @@ import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; @@ -63,6 +66,7 @@ public class ToscaMapValueConverter extends ToscaValueBaseConverter implements T ToscaPropertyType innerToscaType = ToscaPropertyType.isValidType(innerType); ToscaValueConverter innerConverter = null; boolean isScalar = true; + List<PropertyDefinition> allPropertiesRecursive = new ArrayList<>(); if (innerToscaType != null) { innerConverter = innerToscaType.getValueConverter(); } else { @@ -74,9 +78,14 @@ public class ToscaMapValueConverter extends ToscaValueBaseConverter implements T innerConverter = toscaPropertyType.getValueConverter(); } else { isScalar = false; + allPropertiesRecursive.addAll(dataTypeDefinition.getProperties()); + DataTypeDefinition derivedFrom = dataTypeDefinition.getDerivedFrom(); + while ( !derivedFrom.getName().equals("tosca.datatypes.Root") ){ + allPropertiesRecursive.addAll(derivedFrom.getProperties()); + derivedFrom = derivedFrom.getDerivedFrom(); + } } } else { - // TODO handle getinput log.debug("inner Tosca Type is null"); return value; } @@ -105,21 +114,47 @@ public class ToscaMapValueConverter extends ToscaValueBaseConverter implements T final boolean isScalarF = isScalar; final ToscaValueConverter innerConverterFinal = innerConverter; entrySet.forEach(e -> { - log.debug("try convert element {}", e.getValue()); - Object convertedValue = convertDataTypeToToscaMap(innerType, dataTypes, innerConverterFinal, isScalarF, - e.getValue()); - toscaMap.put(e.getKey(), convertedValue); + convertEntry(innerType, dataTypes, allPropertiesRecursive, toscaMap, isScalarF, innerConverterFinal, e); }); return toscaMap; } catch (JsonParseException e) { - log.debug("Failed to parse json : {}. {}", value, e); + log.debug("Failed to parse json : {}", value, e); BeEcompErrorManager.getInstance().logBeInvalidJsonInput("List Converter"); return null; } } - public Object convertDataTypeToToscaMap(String innerType, Map<String, DataTypeDefinition> dataTypes, - ToscaValueConverter innerConverter, final boolean isScalarF, JsonElement entryValue) { + private void convertEntry(String innerType, Map<String, DataTypeDefinition> dataTypes, List<PropertyDefinition> allPropertiesRecursive, Map<String, Object> toscaMap, final boolean isScalarF, final ToscaValueConverter innerConverterFinal, + Entry<String, JsonElement> e) { + log.debug("try convert element {}", e.getValue()); + boolean scalar = false; + String propType = null; + ToscaValueConverter innerConverterProp = innerConverterFinal; + if ( isScalarF ){ + scalar = isScalarF; + propType = innerType; + }else{ + for ( PropertyDefinition pd : allPropertiesRecursive ){ + if ( pd.getName().equals(e.getKey()) ){ + propType = pd.getType(); + DataTypeDefinition pdDataType = dataTypes.get(propType); + ToscaPropertyType toscaPropType = isScalarType(pdDataType); + if ( toscaPropType == null ){ + scalar = false; + }else{ + scalar = true; + propType = toscaPropType.getType(); + innerConverterProp = toscaPropType.getValueConverter(); + } + break; + } + } + } + Object convertedValue = convertDataTypeToToscaObject(propType, dataTypes, innerConverterProp, scalar, e.getValue()); + toscaMap.put(e.getKey(), convertedValue); + } + + public Object convertDataTypeToToscaObject(String innerType, Map<String, DataTypeDefinition> dataTypes, ToscaValueConverter innerConverter, final boolean isScalarF, JsonElement entryValue) { Object convertedValue = null; if (isScalarF && entryValue.isJsonPrimitive()) { log.debug("try convert scalar value {}", entryValue.getAsString()); @@ -129,25 +164,52 @@ public class ToscaMapValueConverter extends ToscaValueBaseConverter implements T convertedValue = innerConverter.convertToToscaValue(entryValue.getAsString(), innerType, dataTypes); } } else { - JsonObject asJsonObjectIn = entryValue.getAsJsonObject(); - Set<Entry<String, JsonElement>> entrySetIn = asJsonObjectIn.entrySet(); - - DataTypeDefinition dataTypeDefinition = dataTypes.get(innerType); - Map<String, PropertyDefinition> allProperties = getAllProperties(dataTypeDefinition); - Map<String, Object> toscaObjectPresentation = new HashMap<>(); - - for (Entry<String, JsonElement> entry : entrySetIn) { - String propName = entry.getKey(); - - JsonElement elementValue = entry.getValue(); - Object convValue; - if (isScalarF == false) { - PropertyDefinition propertyDefinition = allProperties.get(propName); - if (propertyDefinition == null && isScalarF) { - log.debug("The property {} was not found under data type {}", propName, dataTypeDefinition.getName()); - continue; - } + if ( entryValue.isJsonPrimitive() ){ + return handleComplexJsonValue(entryValue); + } + + // Tal G ticket 228696523 created / DE272734 / Bug 154492 Fix + if(entryValue instanceof JsonArray) { + ArrayList<Object> toscaObjectPresentationArray = new ArrayList<>(); + JsonArray jsonArray = entryValue.getAsJsonArray(); + + for (JsonElement jsonElement : jsonArray) { + Object convertedDataTypeToToscaMap = convertDataTypeToToscaMap(innerType, dataTypes, isScalarF, jsonElement); + toscaObjectPresentationArray.add(convertedDataTypeToToscaMap); + } + convertedValue = toscaObjectPresentationArray; + } else { + convertedValue = convertDataTypeToToscaMap(innerType, dataTypes, isScalarF, entryValue); + } + } + return convertedValue; + } + private Object convertDataTypeToToscaMap(String innerType, Map<String, DataTypeDefinition> dataTypes, + final boolean isScalarF, JsonElement entryValue) { + Object convertedValue; + JsonObject asJsonObjectIn = entryValue.getAsJsonObject(); + Set<Entry<String, JsonElement>> entrySetIn = asJsonObjectIn.entrySet(); + + DataTypeDefinition dataTypeDefinition = dataTypes.get(innerType); + Map<String, PropertyDefinition> allProperties = getAllProperties(dataTypeDefinition); + Map<String, Object> toscaObjectPresentation = new HashMap<>(); + + for (Entry<String, JsonElement> entry : entrySetIn) { + String propName = entry.getKey(); + + JsonElement elementValue = entry.getValue(); + Object convValue; + if (isScalarF == false) { + PropertyDefinition propertyDefinition = allProperties.get(propName); + if (propertyDefinition == null) { + log.trace("The property {} was not found under data type . Parse as map", propName); + if (elementValue.isJsonPrimitive()) { + convValue = elementValue.getAsString(); + } else { + convValue = handleComplexJsonValue(elementValue); + } + } else { String type = propertyDefinition.getType(); ToscaPropertyType propertyType = ToscaPropertyType.isValidType(type); if (propertyType != null) { @@ -165,19 +227,21 @@ public class ToscaMapValueConverter extends ToscaValueBaseConverter implements T } } } else { - convValue = convertToToscaValue(elementValue.getAsString(), type, dataTypes); + convValue = convertToToscaValue(elementValue.toString(), type, dataTypes); } + } + } else { + if (elementValue.isJsonPrimitive()) { + convValue = json2JavaPrimitive(elementValue.getAsJsonPrimitive()); } else { - if (elementValue.isJsonPrimitive()) { - convValue = json2JavaPrimitive(elementValue.getAsJsonPrimitive()); - } else { - convValue = handleComplexJsonValue(elementValue); - } + convValue = handleComplexJsonValue(elementValue); } + } + if(!isEmptyObjectValue(convValue)){ toscaObjectPresentation.put(propName, convValue); } - convertedValue = toscaObjectPresentation; } + convertedValue = toscaObjectPresentation; return convertedValue; } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueBaseConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueBaseConverter.java index e886327481..7e2f8766ba 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueBaseConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/converters/ToscaValueBaseConverter.java @@ -86,7 +86,7 @@ public class ToscaValueBaseConverter { Object jsonValue = null; Map<String, Object> value = new HashMap<String, Object>(); - if ( elementValue.isJsonObject() ){ + if (elementValue.isJsonObject()) { JsonObject jsonOb = elementValue.getAsJsonObject(); Set<Entry<String, JsonElement>> entrySet = jsonOb.entrySet(); Iterator<Entry<String, JsonElement>> iteratorEntry = entrySet.iterator(); @@ -106,14 +106,18 @@ public class ToscaValueBaseConverter { } } jsonValue = value; - }else{ - if ( elementValue.isJsonArray() ){ + } else { + if (elementValue.isJsonArray()) { jsonValue = handleJsonArray(elementValue); - }else{ - log.debug("not supported json type {} ",elementValue); + } else { + if (elementValue.isJsonPrimitive()) { + jsonValue = json2JavaPrimitive(elementValue.getAsJsonPrimitive()); + } else { + log.debug("not supported json type {} ", elementValue); + } } } - + return jsonValue; } @@ -150,4 +154,24 @@ public class ToscaValueBaseConverter { throw new IllegalStateException(); } } + + /** + * checks is received Object empty or equals null or not It is relevant only + * if received Object is instance of String, Map or List class. + * + * @param convertedValue + * @return + */ + static public boolean isEmptyObjectValue(Object convertedValue) { + if (convertedValue == null) { + return true; + } else if (convertedValue instanceof String && ((String) convertedValue).isEmpty()) { + return true; + } else if (convertedValue instanceof Map && ((Map) convertedValue).isEmpty()) { + return true; + } else if (convertedValue instanceof List && ((List) convertedValue).isEmpty()) { + return true; + } + return false; + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/DataTypeValidatorConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/DataTypeValidatorConverter.java index d376a1ec13..3240ccc679 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/DataTypeValidatorConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/DataTypeValidatorConverter.java @@ -88,8 +88,7 @@ public class DataTypeValidatorConverter { return result; } - private ImmutablePair<JsonElement, Boolean> validateAndUpdate(JsonElement jsonElement, - DataTypeDefinition dataTypeDefinition, Map<String, DataTypeDefinition> allDataTypes) { + private ImmutablePair<JsonElement, Boolean> validateAndUpdate(JsonElement jsonElement, DataTypeDefinition dataTypeDefinition, Map<String, DataTypeDefinition> allDataTypes) { Map<String, PropertyDefinition> allProperties = getAllProperties(dataTypeDefinition); @@ -100,14 +99,14 @@ public class DataTypeValidatorConverter { PropertyValueConverter converter = toscaPropertyType.getConverter(); if (jsonElement == null || true == jsonElement.isJsonNull()) { boolean valid = validator.isValid(null, null, allDataTypes); - if (false == valid) { - log.trace("Failed in validation of property {} from type {}", dataTypeDefinition.getName(), dataTypeDefinition.getName()); + if (!valid) { + log.trace("Failed in validation of property {} from type {}", dataTypeDefinition.getName(), dataTypeDefinition.getName()); return falseResult; } return new ImmutablePair<JsonElement, Boolean>(jsonElement, true); } else { - if (true == jsonElement.isJsonPrimitive()) { + if (jsonElement.isJsonPrimitive()) { String value = null; if (jsonElement != null) { if (jsonElement.toString().isEmpty()) { @@ -117,7 +116,7 @@ public class DataTypeValidatorConverter { } } boolean valid = validator.isValid(value, null, null); - if (false == valid) { + if (!valid) { log.trace("Failed in validation of property {} from type {}. Json primitive value is {}", dataTypeDefinition.getName(), dataTypeDefinition.getName(), value); return falseResult; } @@ -127,7 +126,7 @@ public class DataTypeValidatorConverter { try { element = jsonParser.parse(convertedValue); } catch (JsonSyntaxException e) { - log.debug("Failed to parse value {} of property {}. {}", convertedValue, dataTypeDefinition.getName(), e); + log.debug("Failed to parse value {} of property {} {}", convertedValue, dataTypeDefinition.getName(), e); return falseResult; } @@ -164,13 +163,13 @@ public class DataTypeValidatorConverter { PropertyDefinition propertyDefinition = allProperties.get(propName); if (propertyDefinition == null) { - log.debug("The property {} was not found under data type {}", propName, dataTypeDefinition.getName()); + log.debug("The property {} was not found under data type {}" ,propName, dataTypeDefinition.getName()); return falseResult; } String type = propertyDefinition.getType(); boolean isScalarType = ToscaPropertyType.isScalarType(type); - if (true == isScalarType) { + if (isScalarType) { ToscaPropertyType propertyType = ToscaPropertyType.isValidType(type); if (propertyType == null) { log.debug("cannot find the {} under default tosca property types", type); @@ -179,8 +178,7 @@ public class DataTypeValidatorConverter { PropertyTypeValidator validator = propertyType.getValidator(); String innerType = null; if (propertyType == ToscaPropertyType.LIST || propertyType == ToscaPropertyType.MAP) { - if (propertyDefinition.getSchema() != null - && propertyDefinition.getSchema().getProperty() != null) { + if (propertyDefinition.getSchema() != null && propertyDefinition.getSchema().getProperty() != null) { innerType = propertyDefinition.getSchema().getProperty().getType(); if (innerType == null) { log.debug("Property type {} must have inner type in its declaration.", propertyType); @@ -215,7 +213,7 @@ public class DataTypeValidatorConverter { try { element = jsonParser.parse(convertedValue); } catch (JsonSyntaxException e) { - log.debug("Failed to parse value {} of type {}. {}", convertedValue, propertyType, e); + log.debug("Failed to parse value {} of type {}", convertedValue, propertyType, e); return falseResult; } } @@ -226,14 +224,13 @@ public class DataTypeValidatorConverter { DataTypeDefinition typeDefinition = allDataTypes.get(type); if (typeDefinition == null) { - log.debug("The data type {] cannot be found in the given data type list.", type); + log.debug("The data type {} cannot be found in the given data type list.", type); return falseResult; } - ImmutablePair<JsonElement, Boolean> isValid = validateAndUpdate(elementValue, - typeDefinition, allDataTypes); + ImmutablePair<JsonElement, Boolean> isValid = validateAndUpdate(elementValue, typeDefinition, allDataTypes); - if (false == isValid.getRight().booleanValue()) { + if (!isValid.getRight().booleanValue()) { log.debug("Failed in validation of value {} from type {}", (elementValue != null ? elementValue.toString() : null), typeDefinition.getName()); return falseResult; } @@ -254,8 +251,7 @@ public class DataTypeValidatorConverter { } - public ImmutablePair<JsonElement, Boolean> validateAndUpdate(String value, DataTypeDefinition dataTypeDefinition, - Map<String, DataTypeDefinition> allDataTypes) { + public ImmutablePair<JsonElement, Boolean> validateAndUpdate(String value, DataTypeDefinition dataTypeDefinition, Map<String, DataTypeDefinition> allDataTypes) { ImmutablePair<JsonElement, Boolean> result = falseResult; @@ -308,8 +304,7 @@ public class DataTypeValidatorConverter { return value; } - public boolean isValid(String value, DataTypeDefinition dataTypeDefinition, - Map<String, DataTypeDefinition> allDataTypes) { + public boolean isValid(String value, DataTypeDefinition dataTypeDefinition, Map<String, DataTypeDefinition> allDataTypes) { boolean result = false; @@ -321,7 +316,7 @@ public class DataTypeValidatorConverter { try { jsonElement = jsonParser.parse(value); } catch (JsonSyntaxException e) { - log.debug("Failed to parse the value {} from type {}. {}", value, dataTypeDefinition, e); + log.debug("Failed to parse the value {} from type {}", value, dataTypeDefinition, e); return false; } @@ -330,8 +325,7 @@ public class DataTypeValidatorConverter { return result; } - private boolean isValid(JsonElement jsonElement, DataTypeDefinition dataTypeDefinition, - Map<String, DataTypeDefinition> allDataTypes) { + private boolean isValid(JsonElement jsonElement, DataTypeDefinition dataTypeDefinition, Map<String, DataTypeDefinition> allDataTypes) { Map<String, PropertyDefinition> allProperties = getAllProperties(dataTypeDefinition); @@ -342,8 +336,7 @@ public class DataTypeValidatorConverter { if (jsonElement == null || true == jsonElement.isJsonNull()) { boolean valid = validator.isValid(null, null, allDataTypes); if (false == valid) { - log.trace("Failed in validation of property " + dataTypeDefinition.getName() + " from type " - + dataTypeDefinition.getName()); + log.trace("Failed in validation of property {} from type {}", dataTypeDefinition.getName(), dataTypeDefinition.getName()); return false; } @@ -396,7 +389,7 @@ public class DataTypeValidatorConverter { PropertyDefinition propertyDefinition = allProperties.get(propName); if (propertyDefinition == null) { - log.debug("The property {} was not found under data tpye {}", propName, dataTypeDefinition.getName()); + log.debug("The property {} was not found under data type {}", propName, dataTypeDefinition.getName()); return false; } String type = propertyDefinition.getType(); @@ -411,11 +404,10 @@ public class DataTypeValidatorConverter { PropertyTypeValidator validator = propertyType.getValidator(); String innerType = null; if (propertyType == ToscaPropertyType.LIST || propertyType == ToscaPropertyType.MAP) { - if (propertyDefinition.getSchema() != null - && propertyDefinition.getSchema().getProperty() != null) { + if (propertyDefinition.getSchema() != null && propertyDefinition.getSchema().getProperty() != null) { innerType = propertyDefinition.getSchema().getProperty().getType(); if (innerType == null) { - log.debug("Property type {} must have inner type in its decleration.", propertyType); + log.debug("Property type {} must have inner type in its declaration.", propertyType); return false; } } @@ -440,7 +432,7 @@ public class DataTypeValidatorConverter { DataTypeDefinition typeDefinition = allDataTypes.get(type); if (typeDefinition == null) { - log.debug("The data type {} canot be found in the given data type list.", type); + log.debug("The data type {} cannot be found in the given data type list.", type); return false; } @@ -465,35 +457,4 @@ public class DataTypeValidatorConverter { } } - - // public ImmutablePair<String, Boolean> - // validateAndUpdateAndReturnString(String value, DataTypeDefinition - // dataTypeDefinition, Map<String, DataTypeDefinition> allDataTypes) { - // - // ImmutablePair<JsonElement, Boolean> result = falseResult; - // - // if (value == null || value.isEmpty()) { - // return trueStringEmptyResult; - // } - // - // JsonElement jsonElement = null; - // try { - // jsonElement = jsonParser.parse(value); - // } catch (JsonSyntaxException e) { - // return falseStringEmptyResult; - // } - // - // result = validateAndUpdate(jsonElement, dataTypeDefinition, - // allDataTypes); - // - // if (result.right.booleanValue() == false) { - // log.debug("The value {} of property from type {} is invalid", value, dataTypeDefinition.getName()); - // return new ImmutablePair<String, Boolean>(value, false); - // } - // - // String valueFromJsonElement = getValueFromJsonElement(result.left); - // - // return new ImmutablePair<String, Boolean>(valueFromJsonElement, true); - // } - } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/ListValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/ListValidator.java index 92834690b8..177dcb60ea 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/ListValidator.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/ListValidator.java @@ -84,7 +84,7 @@ public class ListValidator implements PropertyTypeValidator { innerValidator = ToscaPropertyType.JSON.getValidator(); break; default: - log.debug("inner Tosca Type is unknown: {}", innerToscaType); + log.debug("inner Tosca Type is unknown. {}", innerToscaType); return false; } @@ -92,12 +92,14 @@ public class ListValidator implements PropertyTypeValidator { log.debug("inner Tosca Type is: {}", innerType); boolean isValid = validateComplexInnerType(value, innerType, allDataTypes); - log.debug("Finish to validate value {} of list with inner type {}. result is: {}", value, innerType, isValid); + log.debug("Finish to validate value {} of list with inner type {}. result is {}",value,innerType,isValid); return isValid; } try { JsonArray jo = (JsonArray) jsonParser.parse(value); + if(ToscaPropertyType.JSON == innerToscaType) + return true; int size = jo.size(); for (int i = 0; i < size; i++) { JsonElement currentValue = jo.get(i); @@ -111,7 +113,7 @@ public class ListValidator implements PropertyTypeValidator { return true; } catch (JsonSyntaxException e) { - log.debug("Failed to parse json : {}. {}", value, e); + log.debug("Failed to parse json : {}", value, e); BeEcompErrorManager.getInstance().logBeInvalidJsonInput("List Validator"); } @@ -144,7 +146,7 @@ public class ListValidator implements PropertyTypeValidator { boolean isValid = dataTypeValidatorConverter.isValid(element, innerDataTypeDefinition, allDataTypes); if (isValid == false) { - log.debug("Cannot parse value {} from type {} in list parameter", currentValue, innerType); + log.debug("Cannot parse value {} from type {} in list parameter",currentValue,innerType); return false; } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/MapValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/MapValidator.java index c8ffc3f4b8..7c86b6da1b 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/MapValidator.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/MapValidator.java @@ -101,7 +101,7 @@ public class MapValidator implements PropertyTypeValidator { innerValidator = ToscaPropertyType.JSON.getValidator(); break; default: - log.debug("inner Tosca Type is unknown: {}", innerToscaType); + log.debug("inner Tosca Type is unknown. {}", innerToscaType); return false; } @@ -109,7 +109,7 @@ public class MapValidator implements PropertyTypeValidator { log.debug("inner Tosca Type is: {}", innerType); boolean isValid = validateComplexInnerType(value, innerType, allDataTypes); - log.debug("Finish to validate value {} of map with inner type {}. Result is {}", value, innerType, isValid); + log.debug("Finish to validate value {} of map with inner type {}. result is {}",value,innerType,isValid); return isValid; } @@ -126,14 +126,14 @@ public class MapValidator implements PropertyTypeValidator { if (!innerValidator.isValid(element, null, allDataTypes) || !keyValidator.isValid(entry.getKey(), null, allDataTypes)) { - log.debug("validation of key : {}, element: {} failed", currentKey, entry.getValue()); + log.debug("validation of key : {}, element : {} failed", currentKey, entry.getValue()); return false; } } return true; } catch (JsonSyntaxException e) { - log.debug("Failed to parse json : {}. {}", value, e); + log.debug("Failed to parse json : {}", value, e); BeEcompErrorManager.getInstance().logBeInvalidJsonInput("Map Validator"); } @@ -162,15 +162,15 @@ public class MapValidator implements PropertyTypeValidator { String element = JsonUtils.toString(currentValue); boolean isValid = dataTypeValidatorConverter.isValid(element, innerDataTypeDefinition, allDataTypes); - if (isValid == false) { - log.debug("Cannot parse value {} from type {} of key {}", currentValue, innerType, currentKey); + if (!isValid) { + log.debug("Cannot parse value {} from type {} of key {}",currentValue,innerType,currentKey); return false; } } } } catch (Exception e) { - log.debug("Cannot parse value {} of map from inner type {}. {}", value, innerType, e); + log.debug("Cannot parse value {} of map from inner type {}", value, innerType, e); return false; } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/PropertyTypeValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/PropertyTypeValidator.java index 35862148f9..f0cf225c0a 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/PropertyTypeValidator.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/PropertyTypeValidator.java @@ -30,16 +30,16 @@ public interface PropertyTypeValidator { boolean isValid(String value, String innerType); /* - * The value format should be validated according to the “Property Type�? : - * “integer�? - valid tag:yaml.org,2002:int , the number base 8,10,18 should + * The value format should be validated according to the "Property Type" : + * "integer" - valid tag:yaml.org,2002:int , the number base 8,10,18 should * be handled ( hint : to validate by calling parseInt( * s,10)/parseInt(s,16)/parseInt(s,8) or just regexp [-+]?[0-9]+ for Base 10 * , [-+]?0[0-7]+ for Base 8 , [-+]?0x[0-9a-fA-F]+ for Base 16 * - * “float�? - valid tag:yaml.org,2002:float , parseFloat() “boolean�? - valid - * tag:yaml.org,2002:bool : can be only “true�? or “false�? ( upper case + * "float" - valid tag:yaml.org,2002:float , parseFloat() "boolean" - valid + * tag:yaml.org,2002:bool : can be only "true" or "false" ( upper case * characters should be converted to lower case : TRUE ->true, True->true - * “string�? - valid tag:yaml.org,2002:str and limited to 100 chars. + * "string" - valid tag:yaml.org,2002:str and limited to 100 chars. * */ diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/StringValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/StringValidator.java index 06994505a9..750941cc0b 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/StringValidator.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/StringValidator.java @@ -31,23 +31,19 @@ import org.slf4j.LoggerFactory; public class StringValidator implements PropertyTypeValidator { - public static final int DEFAULT_STRING_MAXIMUM_LENGTH = 100; + public static final int DEFAULT_STRING_MAXIMUM_LENGTH = 2500; - public static int STRING_MAXIMUM_LENGTH = DEFAULT_STRING_MAXIMUM_LENGTH; + private static int STRING_MAXIMUM_LENGTH = DEFAULT_STRING_MAXIMUM_LENGTH; private static Logger log = LoggerFactory.getLogger(StringValidator.class.getName()); private static StringValidator stringValidator = new StringValidator(); - public static StringValidator getInstance() { - return stringValidator; - } - private StringValidator() { if (ConfigurationManager.getConfigurationManager() != null) { ToscaValidatorsConfig toscaValidators = ConfigurationManager.getConfigurationManager().getConfiguration() .getToscaValidators(); - log.debug("toscaValidators={}", toscaValidators); + log.debug("toscaValidators= {}", toscaValidators); if (toscaValidators != null) { Integer stringMaxLength = toscaValidators.getStringMaxLength(); if (stringMaxLength != null) { @@ -57,6 +53,10 @@ public class StringValidator implements PropertyTypeValidator { } } + public static StringValidator getInstance() { + return stringValidator; + } + @Override public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) { @@ -65,14 +65,14 @@ public class StringValidator implements PropertyTypeValidator { } if (value.length() > STRING_MAXIMUM_LENGTH) { - log.debug("parameter String length {} is higher the configured({})", value.length(), STRING_MAXIMUM_LENGTH); + log.debug("parameter String length {} is higher than configured({})", value.length(), STRING_MAXIMUM_LENGTH); return false; } String coverted = ValidationUtils.removeNoneUtf8Chars(value); boolean isValid = ValidationUtils.validateIsAscii(coverted); - if (false == isValid) { - log.debug("parameter String value {} is not ascii string.", (value != null ? value.substring(0, Math.min(value.length(), 20)) : null)); + if (false == isValid && log.isDebugEnabled()) { + log.debug("parameter String value {} is not an ascii string.", value.substring(0, Math.min(value.length(), 20))); } return isValid; diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiCategories.java b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiCategories.java new file mode 100644 index 0000000000..75ad6c3794 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiCategories.java @@ -0,0 +1,31 @@ +package org.openecomp.sdc.be.ui.model; + +import java.util.List; + +import org.openecomp.sdc.be.model.category.CategoryDefinition; + +public class UiCategories { + + private List<CategoryDefinition> resourceCategories; + private List<CategoryDefinition> serviceCategories; + private List<CategoryDefinition> productCategories; + + public List<CategoryDefinition> getResourceCategories() { + return resourceCategories; + } + public void setResourceCategories(List<CategoryDefinition> resourceCategories) { + this.resourceCategories = resourceCategories; + } + public List<CategoryDefinition> getServiceCategories() { + return serviceCategories; + } + public void setServiceCategories(List<CategoryDefinition> serviceCategories) { + this.serviceCategories = serviceCategories; + } + public List<CategoryDefinition> getProductCategories() { + return productCategories; + } + public void setProductCategories(List<CategoryDefinition> productCategories) { + this.productCategories = productCategories; + } +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiComponentDataTransfer.java b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiComponentDataTransfer.java new file mode 100644 index 0000000000..6eb7b841ab --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiComponentDataTransfer.java @@ -0,0 +1,255 @@ +package org.openecomp.sdc.be.ui.model; + +import java.util.List; +import java.util.Map; + +import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.AdditionalInformationDefinition; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.AttributeDefinition; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstanceAttribute; +import org.openecomp.sdc.be.model.ComponentInstanceInput; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.InterfaceDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; +import org.openecomp.sdc.be.model.RequirementDefinition; +import org.openecomp.sdc.be.model.category.CategoryDefinition; + +public class UiComponentDataTransfer { + + + + + private Map<String, ArtifactDefinition> artifacts; + private Map<String, ArtifactDefinition> deploymentArtifacts; + private Map<String, ArtifactDefinition> toscaArtifacts; + + private List<CategoryDefinition> categories; + + // User + private String creatorUserId; + private String creatorFullName; + private String lastUpdaterUserId; + private String lastUpdaterFullName; + + protected ComponentTypeEnum componentType; + + private List<ComponentInstance> componentInstances; + + private List<RequirementCapabilityRelDef> componentInstancesRelations; + + private Map<String, List<ComponentInstanceInput>> componentInstancesInputs; + + private Map<String, List<ComponentInstanceProperty>> componentInstancesProperties; + + private Map<String, List<ComponentInstanceAttribute>> componentInstancesAttributes; + + private Map<String, List<CapabilityDefinition>> capabilities; + + private Map<String, List<RequirementDefinition>> requirements; + + private List<InputDefinition> inputs; + + private List<GroupDefinition> groups; + + protected List<AdditionalInformationDefinition> additionalInformation; + + + + public Map<String, ArtifactDefinition> getArtifacts() { + return artifacts; + } + + + public void setArtifacts(Map<String, ArtifactDefinition> artifacts) { + this.artifacts = artifacts; + } + + + public Map<String, ArtifactDefinition> getDeploymentArtifacts() { + return deploymentArtifacts; + } + + + public void setDeploymentArtifacts(Map<String, ArtifactDefinition> deploymentArtifacts) { + this.deploymentArtifacts = deploymentArtifacts; + } + + + public Map<String, ArtifactDefinition> getToscaArtifacts() { + return toscaArtifacts; + } + + + public void setToscaArtifacts(Map<String, ArtifactDefinition> toscaArtifacts) { + this.toscaArtifacts = toscaArtifacts; + } + + + public List<CategoryDefinition> getCategories() { + return categories; + } + + + public void setCategories(List<CategoryDefinition> categories) { + this.categories = categories; + } + + + 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 ComponentTypeEnum getComponentType() { + return componentType; + } + + + public void setComponentType(ComponentTypeEnum componentType) { + this.componentType = componentType; + } + + + public List<ComponentInstance> getComponentInstances() { + return componentInstances; + } + + + public void setComponentInstances(List<ComponentInstance> componentInstances) { + this.componentInstances = componentInstances; + } + + + public List<RequirementCapabilityRelDef> getComponentInstancesRelations() { + return componentInstancesRelations; + } + + + public void setComponentInstancesRelations(List<RequirementCapabilityRelDef> componentInstancesRelations) { + this.componentInstancesRelations = componentInstancesRelations; + } + + + public Map<String, List<ComponentInstanceInput>> getComponentInstancesInputs() { + return componentInstancesInputs; + } + + + public void setComponentInstancesInputs(Map<String, List<ComponentInstanceInput>> componentInstancesInputs) { + this.componentInstancesInputs = componentInstancesInputs; + } + + + public Map<String, List<ComponentInstanceProperty>> getComponentInstancesProperties() { + return componentInstancesProperties; + } + + + public void setComponentInstancesProperties(Map<String, List<ComponentInstanceProperty>> componentInstancesProperties) { + this.componentInstancesProperties = componentInstancesProperties; + } + + + public Map<String, List<ComponentInstanceAttribute>> getComponentInstancesAttributes() { + return componentInstancesAttributes; + } + + + public void setComponentInstancesAttributes( + Map<String, List<ComponentInstanceAttribute>> componentInstancesAttributes) { + this.componentInstancesAttributes = componentInstancesAttributes; + } + + + public Map<String, List<CapabilityDefinition>> getCapabilities() { + return capabilities; + } + + + public void setCapabilities(Map<String, List<CapabilityDefinition>> capabilities) { + this.capabilities = capabilities; + } + + + public Map<String, List<RequirementDefinition>> getRequirements() { + return requirements; + } + + + public void setRequirements(Map<String, List<RequirementDefinition>> requirements) { + this.requirements = requirements; + } + + + public List<InputDefinition> getInputs() { + return inputs; + } + + + public void setInputs(List<InputDefinition> inputs) { + this.inputs = inputs; + } + + + public List<GroupDefinition> getGroups() { + return groups; + } + + + public void setGroups(List<GroupDefinition> groups) { + this.groups = groups; + } + + + public List<AdditionalInformationDefinition> getAdditionalInformation() { + return additionalInformation; + } + + + public void setAdditionalInformation(List<AdditionalInformationDefinition> additionalInformation) { + this.additionalInformation = additionalInformation; + } + +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiComponentMetadata.java b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiComponentMetadata.java new file mode 100644 index 0000000000..f0679d31de --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiComponentMetadata.java @@ -0,0 +1,318 @@ +package org.openecomp.sdc.be.ui.model; + +import java.util.List; +import java.util.Map; + +import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.category.CategoryDefinition; + +public abstract class UiComponentMetadata { + + private String uniqueId; + + private String name; // archiveName + + private String version; // archiveVersion + + private Boolean isHighestVersion; + + private Long creationDate; + + private Long lastUpdateDate; + + private String description; + + private String lifecycleState; + + private List<String> tags; + + private String icon; + + private String UUID; + + private String normalizedName; + + private String systemName; + + private String contactId; + + private Map<String, String> allVersions; + + private Boolean isDeleted; + + private String projectCode; + + private String csarUUID; + + private String csarVersion; + + private String importedToscaChecksum; + + private String invariantUUID; + + private ComponentTypeEnum componentType; + + private List<CategoryDefinition> categories; + + private String creatorUserId; + + private String creatorFullName; + + private String lastUpdaterUserId; + + private String lastUpdaterFullName; + + + public UiComponentMetadata (List<CategoryDefinition> categories, ComponentMetadataDataDefinition metadata) { + + this.uniqueId = metadata.getUniqueId(); + this.name = metadata.getName(); // archiveName + this.version = metadata.getVersion(); + this.isHighestVersion = metadata.isHighestVersion(); + this.creationDate = metadata.getCreationDate(); + this.lastUpdateDate = metadata.getLastUpdateDate(); + this.description = metadata.getDescription(); + this.lifecycleState = metadata.getState(); + this.tags = metadata.getTags(); + this.icon = metadata.getIcon(); + this.UUID = metadata.getUUID(); + this.normalizedName = metadata.getNormalizedName(); + this.systemName = metadata.getSystemName(); + this.contactId = metadata.getContactId(); + this.allVersions = metadata.getAllVersions(); + this.projectCode = metadata.getProjectCode(); + this.csarUUID = metadata.getCsarUUID(); + this.csarVersion = metadata.getCsarVersion(); + this.importedToscaChecksum = metadata.getImportedToscaChecksum(); + this.invariantUUID = metadata.getInvariantUUID(); + this.componentType = metadata.getComponentType(); + this.categories = categories; + this.creatorUserId = metadata.getCreatorUserId(); + this.creatorFullName = metadata.getCreatorFullName(); + this.lastUpdaterFullName = metadata.getLastUpdaterFullName(); + this.lastUpdaterUserId = metadata.getLastUpdaterUserId(); + + } + + + + public List<CategoryDefinition> getCategories() { + return categories; + } + + public void setCategories(List<CategoryDefinition> categories) { + this.categories = categories; + } + + + public String getUniqueId() { + return uniqueId; + } + + public void setUniqueId(String uniqueId) { + this.uniqueId = uniqueId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public Boolean getIsHighestVersion() { + return isHighestVersion; + } + + public void setIsHighestVersion(Boolean isHighestVersion) { + this.isHighestVersion = isHighestVersion; + } + + public Long getCreationDate() { + return creationDate; + } + + public void setCreationDate(Long creationDate) { + this.creationDate = creationDate; + } + + public Long getLastUpdateDate() { + return lastUpdateDate; + } + + public void setLastUpdateDate(Long lastUpdateDate) { + this.lastUpdateDate = lastUpdateDate; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getLifecycleState() { + return lifecycleState; + } + + public void setLifecycleState(String state) { + this.lifecycleState = state; + } + + public List<String> getTags() { + return tags; + } + + public void setTags(List<String> tags) { + this.tags = tags; + } + + public String getIcon() { + return icon; + } + + public void setIcon(String icon) { + this.icon = icon; + } + + public String getUUID() { + return UUID; + } + + public void setUUID(String uUID) { + UUID = uUID; + } + + public String getNormalizedName() { + return normalizedName; + } + + public void setNormalizedName(String normalizedName) { + this.normalizedName = normalizedName; + } + + public String getSystemName() { + return systemName; + } + + public void setSystemName(String systemName) { + this.systemName = systemName; + } + + public String getContactId() { + return contactId; + } + + public void setContactId(String contactId) { + this.contactId = contactId; + } + + public Map<String, String> getAllVersions() { + return allVersions; + } + + public void setAllVersions(Map<String, String> allVersions) { + this.allVersions = allVersions; + } + + public Boolean getIsDeleted() { + return isDeleted; + } + + public void setIsDeleted(Boolean isDeleted) { + this.isDeleted = isDeleted; + } + + public String getProjectCode() { + return projectCode; + } + + public void setProjectCode(String projectCode) { + this.projectCode = projectCode; + } + + public String getCsarUUID() { + return csarUUID; + } + + public void setCsarUUID(String csarUUID) { + this.csarUUID = csarUUID; + } + + public String getCsarVersion() { + return csarVersion; + } + + public void setCsarVersion(String csarVersion) { + this.csarVersion = csarVersion; + } + + public String getImportedToscaChecksum() { + return importedToscaChecksum; + } + + public void setImportedToscaChecksum(String importedToscaChecksum) { + this.importedToscaChecksum = importedToscaChecksum; + } + + public String getInvariantUUID() { + return invariantUUID; + } + + public void setInvariantUUID(String invariantUUID) { + this.invariantUUID = invariantUUID; + } + + public ComponentTypeEnum getComponentType() { + return componentType; + } + + public void setComponentType(ComponentTypeEnum componentType) { + this.componentType = componentType; + } + + 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; + } + +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceDataTransfer.java b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceDataTransfer.java new file mode 100644 index 0000000000..c56daa4fc9 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceDataTransfer.java @@ -0,0 +1,93 @@ +package org.openecomp.sdc.be.ui.model; + +import java.util.List; +import java.util.Map; + +import org.openecomp.sdc.be.model.AdditionalInformationDefinition; +import org.openecomp.sdc.be.model.AttributeDefinition; +import org.openecomp.sdc.be.model.InterfaceDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; + +public class UiResourceDataTransfer extends UiComponentDataTransfer{ + + private UiResourceMetadata metadata; + + private List<String> derivedFrom; + + private List<String> derivedList; + + private List<PropertyDefinition> properties; + + private List<AttributeDefinition> attributes; + + private Map<String, InterfaceDefinition> interfaces; + + private List<String> defaultCapabilities; + + private List<AdditionalInformationDefinition> additionalInformation; + + public List<AdditionalInformationDefinition> getAdditionalInformation() { + return additionalInformation; + } + + public void setAdditionalInformation(List<AdditionalInformationDefinition> additionalInformation) { + this.additionalInformation = additionalInformation; + } + + public UiResourceMetadata getMetadata() { + return metadata; + } + + public void setMetadata(UiResourceMetadata metadata) { + this.metadata = metadata; + } + + public List<String> getDerivedFrom() { + return derivedFrom; + } + + public void setDerivedFrom(List<String> derivedFrom) { + this.derivedFrom = derivedFrom; + } + + public List<String> getDerivedList() { + return derivedList; + } + + public void setDerivedList(List<String> derivedList) { + this.derivedList = derivedList; + } + + public List<PropertyDefinition> getProperties() { + return properties; + } + + public void setProperties(List<PropertyDefinition> properties) { + this.properties = properties; + } + + public List<AttributeDefinition> getAttributes() { + return attributes; + } + + public void setAttributes(List<AttributeDefinition> attributes) { + this.attributes = attributes; + } + + public Map<String, InterfaceDefinition> getInterfaces() { + return interfaces; + } + + public void setInterfaces(Map<String, InterfaceDefinition> interfaces) { + this.interfaces = interfaces; + } + + public List<String> getDefaultCapabilities() { + return defaultCapabilities; + } + + public void setDefaultCapabilities(List<String> defaultCapabilities) { + this.defaultCapabilities = defaultCapabilities; + } + +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceMetadata.java b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceMetadata.java new file mode 100644 index 0000000000..19c7246462 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceMetadata.java @@ -0,0 +1,101 @@ +package org.openecomp.sdc.be.ui.model; + +import java.util.List; +import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.category.CategoryDefinition; + +public class UiResourceMetadata extends UiComponentMetadata { + + private String vendorName; + private String vendorRelease; + private ResourceTypeEnum resourceType = ResourceTypeEnum.VFC; + private Boolean isAbstract; + private String cost; + private String licenseType; + private String toscaResourceName; + private List<String> derivedFrom; + + public UiResourceMetadata(List<CategoryDefinition> categories, List<String> derivedFrom, ResourceMetadataDataDefinition metadata) { + super(categories, metadata); + this.vendorName = metadata.getVendorName(); + this.vendorRelease = metadata.getVendorRelease(); + this.resourceType = metadata.getResourceType(); + this.cost = metadata.getCost(); + this.licenseType = metadata.getLicenseType(); + this.toscaResourceName = metadata.getToscaResourceName(); + this.derivedFrom = derivedFrom; + } + + public List<String> getDerivedFrom() { + return derivedFrom; + } + + + public void setDerivedFrom(List<String> derivedFrom) { + this.derivedFrom = derivedFrom; + } + + + public String getVendorName() { + return vendorName; + } + + public void setVendorName(String vendorName) { + this.vendorName = vendorName; + } + + public String getVendorRelease() { + return vendorRelease; + } + + public void setVendorRelease(String vendorRelease) { + this.vendorRelease = vendorRelease; + } + + public ResourceTypeEnum getResourceType() { + return resourceType; + } + + public void setResourceType(ResourceTypeEnum resourceType) { + this.resourceType = resourceType; + } + + public Boolean getIsAbstract() { + return isAbstract; + } + + public void setIsAbstract(Boolean isAbstract) { + this.isAbstract = isAbstract; + } + + public String getCost() { + return cost; + } + + public void setCost(String cost) { + this.cost = cost; + } + + public String getLicenseType() { + return licenseType; + } + + public void setLicenseType(String licenseType) { + this.licenseType = licenseType; + } + + public String getToscaResourceName() { + return toscaResourceName; + } + + public void setToscaResourceName(String toscaResourceName) { + this.toscaResourceName = toscaResourceName; + } + + + +} + + + diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceDataTransfer.java b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceDataTransfer.java new file mode 100644 index 0000000000..73bb772a51 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceDataTransfer.java @@ -0,0 +1,29 @@ +package org.openecomp.sdc.be.ui.model; + +import java.util.Map; + +import org.openecomp.sdc.be.model.ArtifactDefinition; + +public class UiServiceDataTransfer extends UiComponentDataTransfer { + + + private Map<String, ArtifactDefinition> serviceApiArtifacts; + + private UiServiceMetadata metadata; + + public UiServiceMetadata getMetadata() { + return metadata; + } + + public void setMetadata(UiServiceMetadata metadata) { + this.metadata = metadata; + } + + public Map<String, ArtifactDefinition> getServiceApiArtifacts() { + return serviceApiArtifacts; + } + + public void setServiceApiArtifacts(Map<String, ArtifactDefinition> serviceApiArtifacts) { + this.serviceApiArtifacts = serviceApiArtifacts; + } +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceMetadata.java b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceMetadata.java new file mode 100644 index 0000000000..b68704eeea --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceMetadata.java @@ -0,0 +1,55 @@ +package org.openecomp.sdc.be.ui.model; + +import java.util.List; + +import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition; +import org.openecomp.sdc.be.model.category.CategoryDefinition; + +public class UiServiceMetadata extends UiComponentMetadata { + + private String distributionStatus; + private Boolean ecompGeneratedNaming; + private String namingPolicy; + private UiServiceMetadata metadata; + + + public UiServiceMetadata getMetadata() { + return metadata; + } + + public void setMetadata(UiServiceMetadata metadata) { + this.metadata = metadata; + } + + public UiServiceMetadata(List<CategoryDefinition> categories, ServiceMetadataDataDefinition metadata) { + super(categories, metadata); + this.distributionStatus = metadata.getDistributionStatus(); + this.ecompGeneratedNaming = metadata.isEcompGeneratedNaming(); + this.namingPolicy = metadata.getNamingPolicy(); + } + + public String getDistributionStatus() { + return distributionStatus; + } + + public void setDistributionStatus(String distributionStatus) { + this.distributionStatus = distributionStatus; + } + + public Boolean getEcompGeneratedNaming() { + return ecompGeneratedNaming; + } + + public void setEcompGeneratedNaming(Boolean ecompGeneratedNaming) { + this.ecompGeneratedNaming = ecompGeneratedNaming; + } + + public String getNamingPolicy() { + return namingPolicy; + } + + public void setNamingPolicy(String namingPolicy) { + this.namingPolicy = namingPolicy; + } + +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/unittests/utils/FactoryUtils.java b/catalog-model/src/main/java/org/openecomp/sdc/be/unittests/utils/FactoryUtils.java index f95a89db62..1d692fd638 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/unittests/utils/FactoryUtils.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/unittests/utils/FactoryUtils.java @@ -25,9 +25,11 @@ import java.util.List; import java.util.UUID; import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; +import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.model.CapabilityDefinition; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.ComponentInstanceProperty; @@ -39,6 +41,7 @@ import org.openecomp.sdc.be.resources.data.CapabilityInstData; import org.openecomp.sdc.be.resources.data.PropertyData; import org.openecomp.sdc.be.resources.data.PropertyValueData; import org.openecomp.sdc.be.resources.data.RequirementData; +import org.openecomp.sdc.be.resources.data.ResourceMetadataData; public final class FactoryUtils { private FactoryUtils() { @@ -61,6 +64,15 @@ public final class FactoryUtils { resource.setUniqueId(uniqueId); return resource; } + + public static ResourceMetadataData createResourceByType(String resourceType) { + ResourceMetadataData resource = new ResourceMetadataData(); + String uniqueId = UUID.randomUUID().toString(); + resource.getMetadataDataDefinition().setHighestVersion(true); + resource.getMetadataDataDefinition().setUniqueId(uniqueId); + ((ResourceMetadataDataDefinition)resource.getMetadataDataDefinition()).setResourceType(ResourceTypeEnum.getTypeIgnoreCase(resourceType)); + return resource; + } public static void addComponentInstanceToVF(Resource vf, ComponentInstance resourceInstance) { List<ComponentInstance> componentsInstances = vf.getComponentInstances() != null ? vf.getComponentInstances() |