diff options
author | ys9693 <ys9693@att.com> | 2020-01-19 13:50:02 +0200 |
---|---|---|
committer | Ofir Sonsino <ofir.sonsino@intl.att.com> | 2020-01-22 12:33:31 +0000 |
commit | 16a9fce0e104a38371a9e5a567ec611ae3fc7f33 (patch) | |
tree | 03a2aff3060ddb5bc26a90115805a04becbaffc9 /catalog-model/src/main/java | |
parent | aa83a2da4f911c3ac89318b8e9e8403b072942e1 (diff) |
Catalog alignment
Issue-ID: SDC-2724
Signed-off-by: ys9693 <ys9693@att.com>
Change-Id: I52b4aacb58cbd432ca0e1ff7ff1f7dd52099c6fe
Diffstat (limited to 'catalog-model/src/main/java')
81 files changed, 2062 insertions, 1772 deletions
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 42e66c01df..6afce6f138 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 @@ -35,6 +35,16 @@ public class ArtifactDefinition extends ArtifactDataDefinition { */ private byte[] payloadData; + private Boolean isHeatParamUpdated = false; + + public Boolean getHeatParamUpdated() { + return isHeatParamUpdated; + } + + public void setHeatParamUpdated(Boolean heatParamUpdated) { + isHeatParamUpdated = heatParamUpdated; + } + public ArtifactDefinition() { } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/CatalogUpdateTimestamp.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/CatalogUpdateTimestamp.java new file mode 100644 index 0000000000..5e353099c3 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/CatalogUpdateTimestamp.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2020 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.IOException; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; + + +public class CatalogUpdateTimestamp { + + + + @JsonProperty("previousUpdateTime") + private long previousUpdateTime; + @JsonProperty("currentUpdateTime") + private long currentUpdateTime; + + public CatalogUpdateTimestamp() { + } + public CatalogUpdateTimestamp(long previousUpdateTime, long currentUpdateTime) { + this.previousUpdateTime = previousUpdateTime; + this.currentUpdateTime = currentUpdateTime; + } + + public CatalogUpdateTimestamp(CatalogUpdateTimestamp catalogUpdateTimestamp) { + this.previousUpdateTime = catalogUpdateTimestamp.getPreviousUpdateTime(); + this.currentUpdateTime = catalogUpdateTimestamp.getCurrentUpdateTime(); + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof CatalogUpdateTimestamp){ + return (this.getCurrentUpdateTime() == ((CatalogUpdateTimestamp) obj).getCurrentUpdateTime() + && this.getPreviousUpdateTime() == ((CatalogUpdateTimestamp) obj).getPreviousUpdateTime()) + || super.equals(obj); + } + return false; + } + + + public long getCurrentUpdateTime() { + return currentUpdateTime; + } + + + public long getPreviousUpdateTime() { + return previousUpdateTime; + } + + + public void setPreviousUpdateTime(long previousUpdateTime) { + this.previousUpdateTime = previousUpdateTime; + } + + public void setCurrentUpdateTime(long currentUpdateTime) { + this.currentUpdateTime = currentUpdateTime; + } + + @Override + public int hashCode() { + return super.hashCode(); + } + + @Override + public String toString() { + return "CatalogUpdateTimestamp [currentUpdateTime = " + currentUpdateTime + ", previousUpdateTime = " + previousUpdateTime + "]"; + } + + public static CatalogUpdateTimestamp buildFromHttpResponse(String responseBody) throws IOException { + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.enable(SerializationFeature.INDENT_OUTPUT); + TypeReference<CatalogUpdateTimestamp> typeRef = new TypeReference<CatalogUpdateTimestamp>() {}; + return objectMapper.readValue(responseBody, typeRef); + } + public static CatalogUpdateTimestamp buildDummyCatalogUpdateTimestamp() { + long currentTimeMillis = System.currentTimeMillis(); + return new CatalogUpdateTimestamp(0L, currentTimeMillis); + } + +} 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 0a77ecd471..c60330f191 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 @@ -39,17 +39,19 @@ import java.util.stream.Collectors; import org.apache.commons.collections.MapUtils; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.utils.MapUtil; -import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition; import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PolicyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType; -import org.openecomp.sdc.be.datatypes.elements.PropertiesOwner; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertiesOwner; + import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.category.SubCategoryDefinition; import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElementTypeEnum; import org.openecomp.sdc.common.api.ArtifactTypeEnum; +import org.openecomp.sdc.common.log.api.ILogConfiguration; import static java.util.stream.Collectors.toMap; @@ -332,6 +334,14 @@ public abstract class Component implements PropertiesOwner { return allArtifacts; } + Optional<ArtifactDefinition> getArtifact(String id) { + HashMap<String, ArtifactDefinition> allArtifacts = new HashMap<>(); + allArtifacts.putAll(Optional.ofNullable(this.artifacts).orElse(emptyMap())); + allArtifacts.putAll(Optional.ofNullable(this.deploymentArtifacts).orElse(emptyMap())); + allArtifacts.putAll(Optional.ofNullable(this.toscaArtifacts).orElse(emptyMap())); + return Optional.ofNullable(allArtifacts.get(id)); + } + public List<CategoryDefinition> getCategories() { return categories; } @@ -430,10 +440,38 @@ public abstract class Component implements PropertiesOwner { return componentInstancesProperties == null ? emptyMap() : componentInstancesProperties; } + public Map<String, List<ComponentInstanceProperty>> safeGetUiComponentInstancesProperties() { + return componentInstancesProperties == null ? emptyMap() : findUiComponentInstancesProperties(); + } + + private Map<String,List<ComponentInstanceProperty>> findUiComponentInstancesProperties() { + List<String> instancesFromUi = componentInstances.stream() + .filter(i->!i.isCreatedFromCsar()) + .map(ComponentInstance::getUniqueId) + .collect(Collectors.toList()); + return componentInstancesProperties.entrySet().stream() + .filter(e -> instancesFromUi.contains(e.getKey())) + .collect(Collectors.toMap(e->e.getKey(), e->e.getValue())); + } + public Map<String, List<ComponentInstanceInput>> safeGetComponentInstancesInputs() { return componentInstancesInputs == null ? emptyMap() : componentInstancesInputs; } + public Map<String, List<ComponentInstanceInput>> safeGetUiComponentInstancesInputs() { + return componentInstancesInputs == null ? emptyMap() : findUiComponentInstancesInputs(); + } + + private Map<String,List<ComponentInstanceInput>> findUiComponentInstancesInputs() { + List<String> instancesFromUi = componentInstances.stream() + .filter(i->!i.isCreatedFromCsar()) + .map(ComponentInstance::getUniqueId) + .collect(Collectors.toList()); + return componentInstancesInputs.entrySet().stream() + .filter(e -> instancesFromUi.contains(e.getKey())) + .collect(Collectors.toMap(e->e.getKey(), e->e.getValue())); + } + public List<ComponentInstanceProperty> safeGetComponentInstanceProperties(String cmptInstacneId) { return this.safeGetComponentInstanceEntity(cmptInstacneId, this.componentInstancesProperties); } @@ -1030,4 +1068,16 @@ public abstract class Component implements PropertiesOwner { public void setVspArchived(Boolean vspArchived) { componentMetadataDefinition.getMetadataDataDefinition().setVspArchived(vspArchived); } + //supportability log method return map of component metadata teddy.h + public Map<String,String> getComponentMetadataForSupportLog(){ + Map<String,String>componentMetadata=new HashMap<>(); + componentMetadata.put(ILogConfiguration.MDC_SUPPORTABLITY_COMPONENT_NAME,this.getName()); + componentMetadata.put(ILogConfiguration.MDC_SUPPORTABLITY_COMPONENT_VERSION,this.getVersion()); + componentMetadata.put(ILogConfiguration.MDC_SUPPORTABLITY_COMPONENT_UUID,this.getUUID()); + componentMetadata.put(ILogConfiguration.MDC_SUPPORTABLITY_CSAR_UUID,this.getCsarUUID()); + componentMetadata.put(ILogConfiguration.MDC_SUPPORTABLITY_CSAR_VERSION,this.getCsarVersion()); + return componentMetadata; + } + + } 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 a7903b3f30..a660c0da6d 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,17 +20,14 @@ package org.openecomp.sdc.be.model; -import lombok.Getter; -import lombok.Setter; import org.apache.commons.lang3.tuple.Pair; +import java.util.HashMap; import java.util.List; import java.util.Map; import static org.apache.commons.collections.MapUtils.isNotEmpty; -@Getter -@Setter public class ComponentInstInputsMap { private Map<String, List<ComponentInstancePropInput>> componentInstanceInputsMap; @@ -70,4 +67,63 @@ public class ComponentInstInputsMap { Map.Entry<String, List<ComponentInstancePropInput>> singleEntry = propertiesMap.entrySet().iterator().next(); return Pair.of(singleEntry.getKey(), singleEntry.getValue()); } + + public Map<String, List<ComponentInstancePropInput>> getComponentInstanceInputsMap() { + return componentInstanceInputsMap == null ? new HashMap<>() : componentInstanceInputsMap; + } + + public void setComponentInstanceInputsMap(Map<String, List<ComponentInstancePropInput>> componentInstanceInputsMap) { + this.componentInstanceInputsMap = componentInstanceInputsMap; + } + + public Map<String, List<ComponentInstancePropInput>> getComponentInstanceProperties() { + return componentInstanceProperties == null ? new HashMap<>() : componentInstanceProperties; + } + + public void setComponentInstancePropInput(Map<String, List<ComponentInstancePropInput>> componentInstanceProperties) { + this.componentInstanceProperties = componentInstanceProperties; + } + + public Map<String, List<ComponentInstancePropInput>> getPolicyProperties() { + return policyProperties == null ? new HashMap<>() : policyProperties; + } + + public void setPolicyProperties(Map<String, List<ComponentInstancePropInput>> policyProperties) { + this.policyProperties = policyProperties; + } + + public Map<String, List<ComponentInstancePropInput>> getServiceProperties() { + return serviceProperties; + } + + public void setServiceProperties( + Map<String, List<ComponentInstancePropInput>> serviceProperties) { + this.serviceProperties = serviceProperties; + } + + public Map<String, List<ComponentInstancePropInput>> getGroupProperties() { + return groupProperties == null ? new HashMap<>() : groupProperties; + } + + public void setGroupProperties(Map<String, List<ComponentInstancePropInput>> groupProperties) { + this.groupProperties = groupProperties; + } + + public Map<String, List<ComponentInstancePropInput>> getComponentPropertiesToPolicies() { + return componentPropertiesToPolicies; + } + + public void setComponentPropertiesToPolicies(Map<String, List<ComponentInstancePropInput>> componentPropertiesToPolicies) { + this.componentPropertiesToPolicies = componentPropertiesToPolicies; + } + + public Map<String, List<ComponentInstancePropInput>> getComponentInstancePropertiesToPolicies() { + return componentInstancePropertiesToPolicies; + } + + public void setComponentInstancePropertiesToPolicies(Map<String, List<ComponentInstancePropInput>> componentInstancePropertiesToPolicies) { + this.componentInstancePropertiesToPolicies = componentInstancePropertiesToPolicies; + } + + } 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 fc3eb69656..3eefcc1505 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 @@ -23,7 +23,9 @@ package org.openecomp.sdc.be.model; import org.apache.commons.collections.MapUtils; import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertiesOwner; +import org.openecomp.sdc.be.datatypes.enums.CreatedFrom; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; +import org.openecomp.sdc.common.log.api.ILogConfiguration; import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition; import java.util.Collections; @@ -31,7 +33,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -public class ComponentInstance extends ComponentInstanceDataDefinition implements PropertiesOwner { +public class ComponentInstance extends ComponentInstanceDataDefinition implements PropertiesOwner{ private Map<String, List<CapabilityDefinition>> capabilities; private Map<String, List<RequirementDefinition>> requirements; @@ -146,6 +148,19 @@ public class ComponentInstance extends ComponentInstanceDataDefinition implement this.nodeFilter = nodeFilter; } + //supportability log method return map of component metadata teddy.h + public Map<String,String> getComponentMetadataForSupportLog(){ + Map<String,String>componentMetadata=new HashMap<>(); + componentMetadata.put(ILogConfiguration.MDC_SUPPORTABLITY_COMPONENT_NAME,getName()); + componentMetadata.put(ILogConfiguration.MDC_SUPPORTABLITY_COMPONENT_VERSION,getVersion()); + componentMetadata.put(ILogConfiguration.MDC_SUPPORTABLITY_COMPONENT_UUID, getSourceModelUuid()); + return componentMetadata; + } + + public boolean isCreatedFromCsar(){ + return CreatedFrom.CSAR.equals(this.getCreatedFrom()); + } + public List<InputDefinition> getInputs() { return inputs; } @@ -153,4 +168,5 @@ public class ComponentInstance extends ComponentInstanceDataDefinition implement public void setInputs(List<InputDefinition> inputs) { this.inputs = inputs; } + } 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 459f7a11d1..c318c9f8db 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 @@ -62,6 +62,7 @@ public class ComponentInstanceProperty extends PropertyDefinition implements ICo } public ComponentInstanceProperty(PropertyDataDefinition pd) { super(pd); + getConstraints(); } public ComponentInstanceProperty(PropertyDefinition pd) { 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 78b5814e8e..3826e18853 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,7 +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"), DISTRIBUTED("Distributed"); private String value; 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 bda5a642d4..3a83533f85 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,6 +21,7 @@ package org.openecomp.sdc.be.model; import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonInclude; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.apache.commons.collections.CollectionUtils; @@ -38,6 +39,7 @@ import static java.util.stream.Collectors.*; public class GroupDefinition extends GroupDataDefinition implements PropertiesOwner{ + @JsonInclude private Map<String, List<CapabilityDefinition>> capabilities; public GroupDefinition() { 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 index dbf520ec3c..caebf4a275 100644 --- 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 @@ -25,6 +25,7 @@ import org.apache.commons.lang3.StringUtils; import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.common.api.ArtifactTypeEnum; +import org.openecomp.sdc.common.log.wrappers.Logger; import java.util.*; import java.util.stream.Collectors; @@ -38,6 +39,8 @@ public class GroupInstance extends GroupInstanceDataDefinition { public GroupInstance(GroupInstanceDataDefinition r) { super(r); } + + private static final Logger log = Logger.getLogger(GroupInstance.class); /** * Converts contained list of PropertyDataDefinitions to list of GroupInstanceProperties * @return @@ -103,7 +106,8 @@ public class GroupInstance extends GroupInstanceDataDefinition { */ public void alignArtifactsUuid(Map<String, ArtifactDefinition> deploymentArtifacts) { List<String> artifactIds = getArtifacts(); - if(CollectionUtils.isNotEmpty(artifactIds) && deploymentArtifacts != null){ + log.debug("the artifacts Id's are: {}, and the deployment artifacts Id's are: {}", artifactIds, deploymentArtifacts); + if(CollectionUtils.isNotEmpty(artifactIds) && deploymentArtifacts != null){ removeArtifactsDuplicates(); clearArtifactsUuid(); List<String> artifactUuids = getArtifactsUuid(); @@ -111,6 +115,7 @@ public class GroupInstance extends GroupInstanceDataDefinition { for(String artifactId : artifactIds){ String label = artifactId.substring(artifactId.lastIndexOf('.') + 1); ArtifactDefinition artifact = deploymentArtifacts.get(label); + log.debug("current artifact id: {}, current artifact definition: {}", artifactId, artifact); ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType()); if (artifactType != ArtifactTypeEnum.HEAT_ENV){ addArtifactsIdToCollection(artifactUuids, artifact); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/LifeCycleTransitionEnum.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/LifeCycleTransitionEnum.java index 8aee955c69..2fabef955d 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/LifeCycleTransitionEnum.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/LifeCycleTransitionEnum.java @@ -24,17 +24,13 @@ public enum LifeCycleTransitionEnum { CHECKOUT("checkout"), CHECKIN("checkin"), - CERTIFICATION_REQUEST("certificationRequest"), UNDO_CHECKOUT("undoCheckout"), - CANCEL_CERTIFICATION("cancelCertification"), - START_CERTIFICATION("startCertification"), - FAIL_CERTIFICATION("failCertification"), CERTIFY("certify"), DISTRIBUTE("distribute"); String displayName; - private LifeCycleTransitionEnum(String displayName) { + LifeCycleTransitionEnum(String displayName) { this.displayName = displayName; } @@ -49,21 +45,9 @@ public enum LifeCycleTransitionEnum { if (name.equalsIgnoreCase(LifeCycleTransitionEnum.CHECKIN.getDisplayName())) { return LifeCycleTransitionEnum.CHECKIN; } - if (name.equalsIgnoreCase(LifeCycleTransitionEnum.CERTIFICATION_REQUEST.getDisplayName())) { - return LifeCycleTransitionEnum.CERTIFICATION_REQUEST; - } if (name.equalsIgnoreCase(LifeCycleTransitionEnum.UNDO_CHECKOUT.getDisplayName())) { return LifeCycleTransitionEnum.UNDO_CHECKOUT; } - if (name.equalsIgnoreCase(LifeCycleTransitionEnum.CANCEL_CERTIFICATION.getDisplayName())) { - return LifeCycleTransitionEnum.CANCEL_CERTIFICATION; - } - if (name.equalsIgnoreCase(LifeCycleTransitionEnum.START_CERTIFICATION.getDisplayName())) { - return LifeCycleTransitionEnum.START_CERTIFICATION; - } - if (name.equalsIgnoreCase(LifeCycleTransitionEnum.FAIL_CERTIFICATION.getDisplayName())) { - return LifeCycleTransitionEnum.FAIL_CERTIFICATION; - } if (name.equalsIgnoreCase(LifeCycleTransitionEnum.CERTIFY.getDisplayName())) { return LifeCycleTransitionEnum.CERTIFY; } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/LifecycleStateEnum.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/LifecycleStateEnum.java index 57ceb90af1..8156ea20c9 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/LifecycleStateEnum.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/LifecycleStateEnum.java @@ -22,10 +22,6 @@ package org.openecomp.sdc.be.model; public enum LifecycleStateEnum { - READY_FOR_CERTIFICATION, - - CERTIFICATION_IN_PROGRESS, - CERTIFIED, NOT_CERTIFIED_CHECKIN, diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/NodeTypeInfo.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/NodeTypeInfo.java index 817060e309..1296129859 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/NodeTypeInfo.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/NodeTypeInfo.java @@ -38,6 +38,7 @@ public class NodeTypeInfo { unmarked.derivedFrom = this.derivedFrom; unmarked.isNested = false; unmarked.mappedToscaTemplate = this.mappedToscaTemplate; + unmarked.isSubstitutionMapping = this.isSubstitutionMapping; return unmarked; } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyConstraint.java index ff9a6e5018..3ed1e37c6f 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyConstraint.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/PropertyConstraint.java @@ -20,10 +20,13 @@ package org.openecomp.sdc.be.model; +import com.fasterxml.jackson.annotation.JsonIgnore; 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.exception.ConstraintFunctionalException; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintValueDoNotMatchPropertyTypeException; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintViolationException; +import org.openecomp.sdc.be.model.tosca.constraints.exception.PropertyConstraintException; public interface PropertyConstraint { @@ -33,5 +36,11 @@ public interface PropertyConstraint { void validate(ToscaType toscaType, String propertyTextValue) throws ConstraintViolationException; - String getErrorMessage(ToscaType toscaType, ConstraintFunctionalException exception, String propertyName); + @JsonIgnore + ConstraintType getConstraintType(); + + void validateValueOnUpdate(PropertyConstraint newConstraint) throws PropertyConstraintException; + + String getErrorMessage(ToscaType toscaType, ConstraintFunctionalException exception, String propertyName); + } 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 6d37cc365f..d25cb72d64 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 @@ -20,10 +20,19 @@ package org.openecomp.sdc.be.model; -import org.openecomp.sdc.be.dao.utils.CollectionUtils; +import com.google.common.reflect.TypeToken; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import org.apache.commons.collections.CollectionUtils; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; +import java.lang.reflect.Type; import java.util.List; +import java.util.stream.Collectors; + +import static org.openecomp.sdc.be.dao.utils.CollectionUtils.safeGetList; + public class PropertyDefinition extends PropertyDataDefinition @@ -48,7 +57,7 @@ public class PropertyDefinition extends PropertyDataDefinition private String propertyName; private GroupInstancePropertyValueUpdateBehavior updateBehavior; - private PropertyNames(String propertyName,GroupInstancePropertyValueUpdateBehavior updateBehavior){ + PropertyNames(String propertyName,GroupInstancePropertyValueUpdateBehavior updateBehavior){ this.propertyName = propertyName; this.updateBehavior = updateBehavior; } @@ -62,8 +71,8 @@ public class PropertyDefinition extends PropertyDataDefinition } /** * finds PropertyNames according received string name - * @param name - * @return + * @param name of the property + * @return PropertyNames found by received property name */ public static PropertyNames findName(String name){ for (PropertyNames e : PropertyNames.values()) { @@ -87,7 +96,7 @@ public class PropertyDefinition extends PropertyDataDefinition String levelName; int levelNumber; - private GroupInstancePropertyValueUpdateBehavior(String name, int levelNumber){ + GroupInstancePropertyValueUpdateBehavior(String name, int levelNumber){ this.levelName = name; this.levelNumber = levelNumber; } @@ -109,26 +118,59 @@ public class PropertyDefinition extends PropertyDataDefinition public PropertyDefinition(PropertyDataDefinition p) { super(p); + getConstraints(); } public PropertyDefinition(PropertyDefinition pd) { super(pd); - this.setConstraints(pd.getConstraints()); + setConstraints(pd.getConstraints()); } public List<PropertyConstraint> getConstraints() { + if(CollectionUtils.isEmpty(constraints)){ + constraints = deserializePropertyConstraints(findConstraints()); + } return constraints; } public List<PropertyConstraint> safeGetConstraints() { - return CollectionUtils.safeGetList(constraints); + return safeGetList(constraints); } public void setConstraints(List<PropertyConstraint> constraints) { + setPropertyConstraints(serializePropertyConstraints(constraints)); this.constraints = constraints; } + private List<PropertyConstraint> deserializePropertyConstraints(List<String> constraints) { + if(CollectionUtils.isNotEmpty(constraints)){ + Type constraintType = new TypeToken<PropertyConstraint>() { + }.getType(); + Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyOperation.PropertyConstraintDeserialiser()).create(); + return constraints.stream().map(c -> (PropertyConstraint)gson.fromJson(c, constraintType)).collect(Collectors.toList()); + } + return null; + } + private List<String> serializePropertyConstraints(List<PropertyConstraint> constraints) { + if(CollectionUtils.isNotEmpty(constraints)){ + Type constraintType = new TypeToken<PropertyConstraint>() { + }.getType(); + Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyOperation.PropertyConstraintSerialiser()).create(); + return constraints.stream().map(gson::toJson).collect(Collectors.toList()); + } + return null; + } + + private List<String> findConstraints() { + if(CollectionUtils.isNotEmpty(getPropertyConstraints())){ + return getPropertyConstraints(); + } + if(getSchemaProperty()!= null){ + return getSchemaProperty().getPropertyConstraints(); + } + return null; + } @Override public String toString() { 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 9b2b609fdb..8100f988a2 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 @@ -29,11 +29,12 @@ import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; +import java.util.stream.Collectors; public class Resource extends Component { - private List<String> derivedFrom; private List<String> derivedList; @@ -138,7 +139,6 @@ public class Resource extends Component { public void setCost(String cost) { ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()).setCost(cost); - ; } public String getLicenseType() { @@ -165,43 +165,19 @@ public class Resource extends Component { } @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - - Resource other = (Resource) obj; - if (attributes == null) { - if (other.attributes != null) - return false; - } else if (!attributes.equals(other.attributes)) - return false; - if (defaultCapabilities == null) { - if (other.defaultCapabilities != null) - return false; - } else if (!defaultCapabilities.equals(other.defaultCapabilities)) - return false; - if (derivedFrom == null) { - if (other.derivedFrom != null) - return false; - } else if (!derivedFrom.equals(other.derivedFrom)) - return false; - if (derivedList == null) { - if (other.derivedList != null) - return false; - } else if (!derivedList.equals(other.derivedList)) - return false; - if (properties == null) { - if (other.properties != null) - return false; - } else if (!properties.equals(other.properties)) - return false; - return super.equals(obj); + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + if (!super.equals(o)) return false; + Resource resource = (Resource) o; + return Objects.equals(derivedFrom, resource.derivedFrom) && + Objects.equals(derivedList, resource.derivedList) && + Objects.equals(properties, resource.properties) && + Objects.equals(attributes, resource.attributes) && + Objects.equals(defaultCapabilities, resource.defaultCapabilities); } + @Override public String toString() { return "Resource [derivedFrom=" + derivedFrom + ", properties=" + properties + ", attributes=" + attributes @@ -273,8 +249,7 @@ public class Resource extends Component { } @Override - public boolean shouldGenerateInputs() { - //TODO add complex VFC condition when supported + public boolean shouldGenerateInputs(){ return !(this.getResourceType().isAtomicType()); } @@ -283,13 +258,19 @@ public class Resource extends Component { return this.shouldGenerateInputs() || (derivedFrom != null && derivedFrom.contains(fetchGenericTypeToscaNameFromConfig())); } - public Map<String, List<RequirementCapabilityRelDef>> groupRelationsByInstanceName(Resource resource) { - Map<String, List<RequirementCapabilityRelDef>> relationsByInstanceId = MapUtil.groupListBy(resource.getComponentInstancesRelations(), RequirementCapabilityRelDef::getFromNode); - return MapUtil.convertMapKeys(relationsByInstanceId, (instId) -> getInstanceNameFromInstanceId(resource, instId)); + public Map<String, List<RequirementCapabilityRelDef>> groupRelationsFromCsarByInstanceName(Resource resource) { + List<RequirementCapabilityRelDef> componentInstanceRelationsFromCsar = resource.getComponentInstancesRelations().stream().filter(r->!r.isOriginUI()).collect(Collectors.toList()); + Map<String, List<RequirementCapabilityRelDef>> relationsByInstanceId = MapUtil.groupListBy(componentInstanceRelationsFromCsar, RequirementCapabilityRelDef::getFromNode); + return MapUtil.convertMapKeys(relationsByInstanceId, instId -> getInstanceInvariantNameFromInstanceId(resource, instId)); } private String getInstanceNameFromInstanceId(Resource resource, String instId) { Optional<ComponentInstance> componentInstanceById = resource.getComponentInstanceById(instId); return componentInstanceById.isPresent() ? componentInstanceById.get().getName() : null; } + + private String getInstanceInvariantNameFromInstanceId(Resource resource, String instId) { + Optional<ComponentInstance> componentInstanceById = resource.getComponentInstanceById(instId); + return componentInstanceById.isPresent() ? componentInstanceById.get().getInvariantName() : null; + } } 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 4920d4f10c..e5122aacf3 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 @@ -146,9 +146,16 @@ public class Service extends Component { return (ServiceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition(); } + public void setServiceFunction(String serviceFunction){ + getServiceMetadataDefinition().setServiceFunction(serviceFunction); + } + + public String getServiceFunction(){ + return getServiceMetadataDefinition().getServiceFunction(); + } - public void validateAndSetInstantiationType() { - if (this.getInstantiationType() == StringUtils.EMPTY) { + public void validateAndSetInstantiationType() { + if (this.getInstantiationType().equals(StringUtils.EMPTY)) { this.setInstantiationType(InstantiationTypes.A_LA_CARTE.getValue()); } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/User.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/User.java index 86d3d812ef..9081e474f6 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/User.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/User.java @@ -20,12 +20,14 @@ package org.openecomp.sdc.be.model; +import com.fasterxml.jackson.annotation.JsonInclude; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.openecomp.sdc.be.dao.utils.UserStatusEnum; import org.openecomp.sdc.be.resources.data.UserData; - +@JsonInclude public class User { + public static final String FORCE_DELETE_HEADER_FLAG = "FORCE_DELETE"; private String firstName; @@ -45,6 +47,10 @@ public class User { public User() { } + public User(String userId) { + this.userId = userId; + } + public User(UserData userDate) { this(userDate.getFirstName(), userDate.getLastName(), userDate.getUserId(), userDate.getEmail(), userDate.getRole(), userDate.getLastLoginTime()); @@ -58,7 +64,6 @@ public class User { this.email = emailAddress; this.role = role; this.lastLoginTime = lastLoginTime; - } public void copyData(User other) { diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/catalog/CatalogComponent.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/catalog/CatalogComponent.java index 4790382a65..c6965489ec 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/catalog/CatalogComponent.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/catalog/CatalogComponent.java @@ -20,14 +20,16 @@ package org.openecomp.sdc.be.model.catalog; -import com.google.common.collect.ImmutableList; -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import static java.util.Objects.requireNonNull; import java.util.ArrayList; import java.util.Collections; import java.util.List; -import static java.util.Objects.requireNonNull; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.category.CategoryDefinition; + +import com.google.common.collect.ImmutableList; public class CatalogComponent { @@ -42,7 +44,59 @@ public class CatalogComponent { private String categoryNormalizedName; private String subCategoryNormalizedName; private String distributionStatus; + private String uuid; + private String invariantUUID; + private String systemName; + private String description; private List<String> tags; + private Boolean isHighestVersion; + private String lastUpdaterUserId; + + + private List<CategoryDefinition> categories; + + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + + public String getInvariantUUID() { + return invariantUUID; + } + + public void setInvariantUUID(String invariantUUID) { + this.invariantUUID = invariantUUID; + } + + public String getSystemName() { + return systemName; + } + + public void setSystemName(String systemName) { + this.systemName = systemName; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + + public Boolean getIsHighestVersion() { + return isHighestVersion; + } + + public void setIsHighestVersion(Boolean isHighestVersion) { + this.isHighestVersion = isHighestVersion; + } public String getCategoryNormalizedName() { return categoryNormalizedName; @@ -140,4 +194,20 @@ public class CatalogComponent { requireNonNull(tags); this.tags = new ArrayList<>(tags); } + + public List<CategoryDefinition> getCategories() { + return categories == null ? Collections.emptyList() : ImmutableList.copyOf(categories); + } + + public void setCategories(List<CategoryDefinition> categories) { + this.categories = categories; + } + + public String getLastUpdaterUserId() { + return lastUpdaterUserId; + } + + public void setLastUpdaterUserId(String lastUpdaterUserId) { + this.lastUpdaterUserId = lastUpdaterUserId; + } } 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 503cf61e70..c2536e70d4 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 @@ -20,23 +20,9 @@ package org.openecomp.sdc.be.model.heat; -import lombok.AllArgsConstructor; -import lombok.Getter; -import org.openecomp.sdc.be.model.tosca.converters.HeatBooleanConverter; -import org.openecomp.sdc.be.model.tosca.converters.HeatCommaDelimitedListConverter; -import org.openecomp.sdc.be.model.tosca.converters.HeatJsonConverter; -import org.openecomp.sdc.be.model.tosca.converters.HeatNumberConverter; -import org.openecomp.sdc.be.model.tosca.converters.HeatStringConverter; -import org.openecomp.sdc.be.model.tosca.converters.PropertyValueConverter; -import org.openecomp.sdc.be.model.tosca.validators.HeatBooleanValidator; -import org.openecomp.sdc.be.model.tosca.validators.HeatCommaDelimitedListValidator; -import org.openecomp.sdc.be.model.tosca.validators.HeatNumberValidator; -import org.openecomp.sdc.be.model.tosca.validators.HeatStringValidator; -import org.openecomp.sdc.be.model.tosca.validators.PropertyTypeValidator; +import org.openecomp.sdc.be.model.tosca.converters.*; +import org.openecomp.sdc.be.model.tosca.validators.*; - -@AllArgsConstructor -@Getter public enum HeatParameterType { STRING("string", HeatStringValidator.getInstance(), HeatStringConverter.getInstance()), @@ -54,12 +40,30 @@ public enum HeatParameterType { private PropertyTypeValidator validator; private PropertyValueConverter converter; - public static HeatParameterType isValidType(final String typeName) { + HeatParameterType(String type, PropertyTypeValidator validator, PropertyValueConverter converter) { + this.type = type; + this.validator = validator; + this.converter = converter; + } + + public String getType() { + return type; + } + + public PropertyTypeValidator getValidator() { + return validator; + } + + public PropertyValueConverter getConverter() { + return converter; + } + + public static HeatParameterType isValidType(String typeName) { if (typeName == null) { return null; } - for (final HeatParameterType type : HeatParameterType.values()) { + for (HeatParameterType type : HeatParameterType.values()) { if (type.getType().equals(typeName)) { return type; } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/ToscaElement.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/ToscaElement.java index 7685d1c348..28efb308b6 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/ToscaElement.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/ToscaElement.java @@ -32,6 +32,7 @@ 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.jsonjanusgraph.operations.NodeTypeOperation; +import org.openecomp.sdc.common.log.api.ILogConfiguration; import org.slf4j.MDC; import java.util.HashMap; @@ -337,7 +338,7 @@ public abstract class ToscaElement { 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()); + MDC.put(ILogConfiguration.MDC_SERVICE_INSTANCE_ID, uuid.toString()); } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ArchiveOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ArchiveOperation.java index 77fd010e85..782867a856 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ArchiveOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ArchiveOperation.java @@ -128,10 +128,8 @@ public class ArchiveOperation extends BaseOperation { public List<String> setArchivedOriginsFlagInComponentInstances(GraphVertex compositionService) { List<String> ciUidsWithArchivedOrigins = new LinkedList(); - Either<List<GraphVertex>, JanusGraphOperationStatus> instanceOfVerticesE = janusGraphDao - .getChildrenVertecies(compositionService, EdgeLabelEnum.INSTANCE_OF, JsonParseFlagEnum.NoParse); - Either<List<GraphVertex>, JanusGraphOperationStatus> proxyOfVerticesE = janusGraphDao - .getChildrenVertecies(compositionService, EdgeLabelEnum.PROXY_OF, JsonParseFlagEnum.NoParse); + Either<List<GraphVertex>, JanusGraphOperationStatus> instanceOfVerticesE = janusGraphDao.getChildrenVertices(compositionService, EdgeLabelEnum.INSTANCE_OF, JsonParseFlagEnum.NoParse); + Either<List<GraphVertex>, JanusGraphOperationStatus> proxyOfVerticesE = janusGraphDao.getChildrenVertices(compositionService, EdgeLabelEnum.PROXY_OF, JsonParseFlagEnum.NoParse); List<GraphVertex> all = new LinkedList<>(); if (instanceOfVerticesE.isLeft()){ diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ArtifactsOperations.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ArtifactsOperations.java index 72fa71356e..50c165f535 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ArtifactsOperations.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ArtifactsOperations.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,6 +22,7 @@ package org.openecomp.sdc.be.model.jsonjanusgraph.operations; import fj.data.Either; import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang.text.StrBuilder; import org.apache.commons.lang3.tuple.ImmutableTriple; import org.apache.commons.lang3.tuple.Triple; import org.apache.tinkerpop.gremlin.structure.Direction; @@ -32,6 +33,7 @@ import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.HeatParameterDataDefinition; import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition; import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition; import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition; @@ -40,6 +42,7 @@ 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.Component; import org.openecomp.sdc.be.model.HeatParameterDefinition; import org.openecomp.sdc.be.model.InterfaceDefinition; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; @@ -49,7 +52,9 @@ import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.openecomp.sdc.common.jsongraph.util.CommonUtility; import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; +import org.openecomp.sdc.common.log.api.ILogConfiguration; import org.openecomp.sdc.common.log.wrappers.Logger; +import org.openecomp.sdc.common.util.GeneralUtility; import org.slf4j.MDC; import java.util.*; @@ -61,13 +66,15 @@ public class ArtifactsOperations extends BaseOperation { private static final String FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR = "failed to fetch {} for tosca element with id {}, error {}"; private static final Logger log = Logger.getLogger(ArtifactsOperations.class.getName()); - public Either<ArtifactDefinition, StorageOperationStatus> addArifactToComponent(ArtifactDefinition artifactInfo, String parentId, NodeTypeEnum type, boolean failIfExist, String instanceId) { + public Either<ArtifactDefinition, StorageOperationStatus> addArtifactToComponent(ArtifactDefinition artifactInfo, + Component component, NodeTypeEnum type, boolean failIfExist, String instanceId) { + String parentId = component.getUniqueId(); String artifactId = artifactInfo.getUniqueId(); if (artifactId == null && artifactInfo.getEsId() != null) { artifactId = artifactInfo.getEsId(); } - Either<ArtifactDataDefinition, StorageOperationStatus> status = updateArtifactOnGraph(parentId, artifactInfo, type, artifactId, instanceId, false, false); + Either<ArtifactDataDefinition, StorageOperationStatus> status = updateArtifactOnGraph(component, artifactInfo, type, artifactId, instanceId, false, false); if (status.isRight()) { log.debug("Failed to update artifact {} of {} {}. status is {}", artifactInfo.getArtifactName(), type.getName(), parentId, status.right().value()); @@ -84,9 +91,11 @@ public class ArtifactsOperations extends BaseOperation { } - public Either<ArtifactDefinition, StorageOperationStatus> updateArtifactOnResource(ArtifactDefinition artifactInfo, String id, String artifactId, NodeTypeEnum type, String instanceId) { + public Either<ArtifactDefinition, StorageOperationStatus> updateArtifactOnResource(ArtifactDefinition artifactInfo, + Component component, String artifactId, NodeTypeEnum type, String instanceId, boolean isUpdate) { - Either<ArtifactDataDefinition, StorageOperationStatus> status = updateArtifactOnGraph(id, artifactInfo, type, artifactId, instanceId, true, false); + String id = component.getUniqueId(); + Either<ArtifactDataDefinition, StorageOperationStatus> status = updateArtifactOnGraph(component, artifactInfo, type, artifactId, instanceId, isUpdate, false); if (status.isRight()) { log.debug("Failed to update artifact {} of {} {}. status is {}", artifactInfo.getArtifactName(), type.getName(), id, status.right().value()); @@ -97,7 +106,7 @@ public class ArtifactsOperations extends BaseOperation { ArtifactDataDefinition artifactData = status.left().value(); ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(artifactInfo, artifactData); - log.debug("The returned ArtifactDefintion is {}", artifactDefResult); + log.debug("The returned ArtifactDefinition is {}", artifactDefResult); return Either.left(artifactDefResult); } } @@ -296,45 +305,70 @@ public class ArtifactsOperations extends BaseOperation { } - public void updateUUID(ArtifactDataDefinition artifactData, String oldChecksum, String oldVesrion, boolean isUpdate, EdgeLabelEnum edgeLabel) { - if (oldVesrion == null || oldVesrion.isEmpty()) + private void updateUUID(Map<String, ArtifactDefinition> deploymentArtifacts, ArtifactDefinition updateArtifactData, String oldChecksum, String oldVesrion, boolean isUpdate, EdgeLabelEnum edgeLabel, String prevArtUid) { + if (oldVesrion == null || oldVesrion.isEmpty()) { oldVesrion = "0"; - - String currentChecksum = artifactData.getArtifactChecksum(); + } + String currentChecksum = updateArtifactData.getArtifactChecksum(); if (isUpdate) { - ArtifactTypeEnum type = ArtifactTypeEnum.findType(artifactData.getArtifactType()); + ArtifactTypeEnum type = ArtifactTypeEnum.findType(updateArtifactData.getArtifactType()); switch (type) { case HEAT_ENV: if (edgeLabel == EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS) { - generateUUID(artifactData, oldVesrion); - } else { - updateVersionAndDate(artifactData, oldVesrion); + generateUUID(updateArtifactData, oldVesrion); } break; case HEAT: case HEAT_NET: case HEAT_VOL: - generateUUID(artifactData, oldVesrion); - break; - default: - if (oldChecksum == null || oldChecksum.isEmpty()) { - if (currentChecksum != null) { - generateUUID(artifactData, oldVesrion); + boolean changed = false; + Optional<Entry<String, ArtifactDefinition>> any = deploymentArtifacts.entrySet() + .stream() + .filter(e -> e.getKey().equals(updateArtifactData.getArtifactLabel())) + .findAny(); + if ( any.isPresent() ){ + if ( !any.get().getValue().getArtifactChecksum().equals(updateArtifactData.getArtifactChecksum()) ){ + changed = true; + } + } + Optional<Entry<String, ArtifactDefinition>> anyEnv = deploymentArtifacts.entrySet() + .stream() + .filter(e -> prevArtUid.equals(e.getValue().getGeneratedFromId())) + .findAny(); + if ( anyEnv.isPresent() && anyEnv.get().getValue().getHeatParamUpdated()){ + String newCheckSum = sortAndCalculateChecksumForHeatParameters(updateArtifactData.getHeatParameters()); + if ( !anyEnv.get().getValue().getArtifactChecksum().equals(newCheckSum) ){ + changed = true; + anyEnv.get().getValue().setArtifactChecksum(newCheckSum); + UUID uuid = UUID.randomUUID(); + anyEnv.get().getValue().setArtifactUUID(uuid.toString()); } - } else if ((currentChecksum != null && !currentChecksum.isEmpty()) && !oldChecksum.equals(currentChecksum)) { - generateUUID(artifactData, oldVesrion); } + if ( changed && anyEnv.isPresent() ){ + generateUUID(updateArtifactData, oldVesrion); + anyEnv.get().getValue().setGeneratedFromId(updateArtifactData.getUniqueId()); + anyEnv.get().getValue().setDuplicated(false); + anyEnv.get().getValue().setArtifactVersion(updateArtifactData.getArtifactVersion()); + anyEnv.get().getValue().setHeatParamUpdated(false); + } + break; + default: + generateUUIDForNonHeatArtifactType(updateArtifactData, oldChecksum, oldVesrion, currentChecksum); break; } } else { - if (oldChecksum == null || oldChecksum.isEmpty()) { - if (currentChecksum != null) { - generateUUID(artifactData, oldVesrion); - } - } else if ((currentChecksum != null && !currentChecksum.isEmpty()) && !oldChecksum.equals(currentChecksum)) { + generateUUIDForNonHeatArtifactType(updateArtifactData, oldChecksum, oldVesrion, currentChecksum); + } + } + + private void generateUUIDForNonHeatArtifactType(ArtifactDataDefinition artifactData, String oldChecksum, String oldVesrion, String currentChecksum) { + if (oldChecksum == null || oldChecksum.isEmpty()) { + if (currentChecksum != null) { generateUUID(artifactData, oldVesrion); } + } else if ((currentChecksum != null && !currentChecksum.isEmpty()) && !oldChecksum.equals(currentChecksum)) { + generateUUID(artifactData, oldVesrion); } } @@ -344,9 +378,10 @@ public class ArtifactsOperations extends BaseOperation { return null; } - public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifactHeat, String componentId, NodeTypeEnum parentType, boolean failIfExist, String instanceId) { + public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, + ArtifactDefinition artifactHeat, Component component, NodeTypeEnum parentType, boolean failIfExist, String instanceId) { artifactHeatEnv.setGeneratedFromId(artifactHeat.getUniqueId()); - return addArifactToComponent(artifactHeatEnv, componentId, parentType, failIfExist, instanceId); + return addArtifactToComponent(artifactHeatEnv, component, parentType, failIfExist, instanceId); } public Either<ArtifactDefinition, StorageOperationStatus> getHeatArtifactByHeatEnvId(String parentId, ArtifactDefinition heatEnv, NodeTypeEnum parentType, String containerId, ComponentTypeEnum componentType) { @@ -362,20 +397,30 @@ public class ArtifactsOperations extends BaseOperation { return getArtifactById(parentId, id, compType, containerId); } - public Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact(String id, ArtifactDefinition artifactEnvInfo, String artifactId, String newArtifactId, NodeTypeEnum type, String instanceId) { + public Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact(Component component, ArtifactDefinition artifactEnvInfo, String artifactId, String newArtifactId, NodeTypeEnum type, String instanceId) { + + Either<Map<String, ArtifactDefinition>, JanusGraphOperationStatus> artifactsEither = getArtifactByLabel(component.getUniqueId(), instanceId, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS); + return updateHeatEnvArtifact(artifactsEither, component, artifactEnvInfo, artifactId, newArtifactId, type, instanceId); + } + + private Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact( + Either<Map<String, ArtifactDefinition>, JanusGraphOperationStatus> artifactsEither, Component component, + ArtifactDefinition artifactEnvInfo, String artifactId, String newArtifactId, NodeTypeEnum type, String instanceId) { - Either<Map<String, ArtifactDefinition>, JanusGraphOperationStatus> artifactsEither = getArtifactByLabel(id, instanceId, EdgeLabelEnum.DEPLOYMENT_ARTIFACTS); + String id = component.getUniqueId(); if (artifactsEither.isRight()) { log.debug("Failed to find artifacts in component {} with id {} ", id, artifactsEither.right().value()); return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(artifactsEither.right().value())); } Map<String, ArtifactDefinition> artifacts = artifactsEither.left().value(); - List<ArtifactDefinition> envList = artifacts.values().stream().filter(a -> a.getGeneratedFromId() != null && a.getGeneratedFromId().equals(artifactId)).collect(Collectors.toList()); + List<ArtifactDefinition> envList = artifacts.values().stream() + .filter(a -> a.getGeneratedFromId() != null && a.getGeneratedFromId().equals(artifactId)) + .collect(Collectors.toList()); if (envList != null && !envList.isEmpty()) { envList.forEach(a -> { a.setGeneratedFromId(newArtifactId); - updateArtifactOnResource(a, id, a.getUniqueId(), type, instanceId); + updateArtifactOnResource(a, component, a.getUniqueId(), type, instanceId, true); }); @@ -383,8 +428,16 @@ public class ArtifactsOperations extends BaseOperation { return Either.left(artifactEnvInfo); } - public Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvPlaceholder(ArtifactDefinition artifactInfo, String parentId, NodeTypeEnum type) { - return updateArtifactOnResource(artifactInfo, parentId, artifactInfo.getUniqueId(), type, null); + public Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifactOnInstance( + Component component, ArtifactDefinition artifactEnvInfo, String artifactId, String newArtifactId, NodeTypeEnum type, String instanceId) { + + String id = component.getUniqueId(); + Either<Map<String, ArtifactDefinition>, JanusGraphOperationStatus> artifactsEither = getArtifactByLabel(id, instanceId, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS); + return updateHeatEnvArtifact(artifactsEither, component, artifactEnvInfo, artifactId, newArtifactId, type, instanceId); + } + + public Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvPlaceholder(ArtifactDefinition artifactInfo, Component parent, NodeTypeEnum type) { + return updateArtifactOnResource(artifactInfo, parent, artifactInfo.getUniqueId(), type, null, true); } @@ -518,9 +571,10 @@ public class ArtifactsOperations extends BaseOperation { } - public Either<ArtifactDataDefinition, StorageOperationStatus> updateArtifactOnGraph(String componentId, ArtifactDefinition artifactInfo, NodeTypeEnum type, String artifactId, String instanceId, boolean isUpdate, boolean isDeletePlaceholder) { + public Either<ArtifactDataDefinition, StorageOperationStatus> updateArtifactOnGraph(Component component, ArtifactDefinition artifactInfo, NodeTypeEnum type, String artifactId, String instanceId, boolean isUpdate, boolean isDeletePlaceholder) { + String componentId = component.getUniqueId(); Either<ArtifactDataDefinition, StorageOperationStatus> res = null; - ArtifactDataDefinition artifactToUpdate = new ArtifactDataDefinition(artifactInfo); + ArtifactDefinition artifactToUpdate = new ArtifactDefinition(artifactInfo); ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType(); Triple<EdgeLabelEnum, Boolean, VertexTypeEnum> triple = getEdgeLabelEnumFromArtifactGroupType(groupType, type); @@ -535,6 +589,7 @@ public class ArtifactsOperations extends BaseOperation { } boolean isNeedToClone = isNeedToCloneEither.left().value(); + String prevArtUid = artifactToUpdate.getUniqueId(); if (artifactId == null || isNeedToClone) { String uniqueId; if (edgeLabelEnum != EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS && edgeLabelEnum != EdgeLabelEnum.INSTANCE_ARTIFACTS) { @@ -542,20 +597,21 @@ public class ArtifactsOperations extends BaseOperation { } else { uniqueId = UniqueIdBuilder.buildInstanceArtifactUniqueId(componentId, instanceId, artifactToUpdate.getArtifactLabel()); } + prevArtUid = artifactToUpdate.getUniqueId(); artifactToUpdate.setUniqueId(uniqueId); if (!isDeletePlaceholder) artifactToUpdate.setEsId(uniqueId); } else artifactToUpdate.setUniqueId(artifactId); - Map<String, ArtifactDataDefinition> artifacts = new HashMap<>(); + Map<String, ArtifactDefinition> artifacts = new HashMap<>(); Map<String, MapArtifactDataDefinition> artifactInst = null; if (edgeLabelEnum != EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS && edgeLabelEnum != EdgeLabelEnum.INSTANCE_ARTIFACTS) { Either<Map<String, ArtifactDataDefinition>, JanusGraphOperationStatus> artifactsEither = this.getDataFromGraph(componentId, edgeLabelEnum); if (artifactsEither.isLeft() && artifactsEither.left().value() != null && !artifactsEither.left().value().isEmpty()) { - artifacts = artifactsEither.left().value(); + artifacts = convertArtifactMapToArtifactDefinitionMap(artifactsEither.left().value()); if (isNeedToClone && artifacts != null) { artifacts.values().stream().forEach(a -> a.setDuplicated(Boolean.TRUE)); } @@ -570,7 +626,7 @@ public class ArtifactsOperations extends BaseOperation { } MapArtifactDataDefinition artifatcsOnInstance = artifactInst.get(instanceId); if (artifatcsOnInstance != null) { - artifacts = artifatcsOnInstance.getMapToscaDataDefinition(); + artifacts = convertArtifactMapToArtifactDefinitionMap(artifatcsOnInstance.getMapToscaDataDefinition()); } } } @@ -600,7 +656,8 @@ public class ArtifactsOperations extends BaseOperation { } } } - updateUUID(artifactToUpdate, oldChecksum, oldVersion, isUpdate, edgeLabelEnum); + + updateUUID(artifacts, artifactToUpdate, oldChecksum, oldVersion, isUpdate, edgeLabelEnum, prevArtUid); if (artifactInfo.getPayloadData() == null) { if (!artifactToUpdate.getMandatory() || artifactToUpdate.getEsId() != null) { @@ -614,11 +671,15 @@ public class ArtifactsOperations extends BaseOperation { StorageOperationStatus status = StorageOperationStatus.OK; if (edgeLabelEnum != EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS && edgeLabelEnum != EdgeLabelEnum.INSTANCE_ARTIFACTS) { - List<ArtifactDataDefinition> toscaDataList = new ArrayList<>(); + List<ArtifactDefinition> toscaDataList = new ArrayList<>(); toscaDataList.add(artifactToUpdate); if (isNeedToClone && artifacts != null) { artifacts.values().stream().filter(a -> !a.getArtifactLabel().equals(artifactToUpdate.getArtifactLabel())).forEach(toscaDataList::add); + }else{ + if ( artifacts != null ) { + artifacts.values().stream().filter(a -> artifactToUpdate.getUniqueId().equals(a.getGeneratedFromId())).forEach(toscaDataList::add); + } } status = updateToscaDataOfToscaElement(componentId, edgeLabelEnum, vertexTypeEnum, toscaDataList, JsonPresentationFields.ARTIFACT_LABEL); } else { @@ -629,8 +690,9 @@ public class ArtifactsOperations extends BaseOperation { if (isNeedToClone) { MapArtifactDataDefinition artifatcsOnInstance = artifactInst.get(instanceId); if (artifatcsOnInstance != null) { - artifacts = artifatcsOnInstance.getMapToscaDataDefinition(); - artifacts.put(artifactToUpdate.getArtifactLabel(), artifactToUpdate); + Map<String, ArtifactDataDefinition> mapToscaDataDefinition = artifatcsOnInstance.getMapToscaDataDefinition(); + ArtifactDataDefinition artifactDataDefinitionToUpdate = new ArtifactDataDefinition(artifactToUpdate); + mapToscaDataDefinition.put(artifactToUpdate.getArtifactLabel(), artifactDataDefinitionToUpdate); } for (Entry<String, MapArtifactDataDefinition> e : artifactInst.entrySet()) { @@ -659,7 +721,7 @@ public class ArtifactsOperations extends BaseOperation { UUID uuid = UUID.randomUUID(); artifactData.setArtifactUUID(uuid.toString()); - MDC.put("serviceInstanceID", uuid.toString()); + MDC.put(ILogConfiguration.MDC_SERVICE_INSTANCE_ID, uuid.toString()); updateVersionAndDate(artifactData, oldVesrion); } @@ -754,4 +816,13 @@ public class ArtifactsOperations extends BaseOperation { return result; } + public String sortAndCalculateChecksumForHeatParameters(List<HeatParameterDataDefinition> heatParameters) { + StrBuilder sb = new StrBuilder(); + heatParameters.stream() + .sorted(Comparator.comparingInt(HeatParameterDataDefinition::hashCode)) + .map(HeatParameterDataDefinition::hashCode) + .collect(Collectors.toSet()) + .forEach(sb::append); + return GeneralUtility.calculateMD5Base64EncodedByString(sb.toString()); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/BaseOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/BaseOperation.java index a4fe67eb3f..14ce6be609 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/BaseOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/BaseOperation.java @@ -62,13 +62,7 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.util.ValidationUtils; import org.springframework.beans.factory.annotation.Autowired; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.UUID; +import java.util.*; import java.util.stream.Collectors; /** @@ -924,36 +918,19 @@ public abstract class BaseOperation { } - @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, JanusGraphOperationStatus> toscaDataVertexRes = janusGraphDao - .getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson); + <T extends ToscaDataDefinition> StorageOperationStatus updateFullToscaData(GraphVertex toscaElement, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel, Map<String, T> toscaData) { + Either<GraphVertex, JanusGraphOperationStatus> toscaDataVertexRes = janusGraphDao.getChildVertex(toscaElement, edgeLabel, JsonParseFlagEnum.ParseJson); if (toscaDataVertexRes.isRight() && toscaDataVertexRes.right().value() != JanusGraphOperationStatus.NOT_FOUND) { JanusGraphOperationStatus status = toscaDataVertexRes.right().value(); CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_CHILD_VERTEX_OF_THE_TOSCA_ELEMENT_BY_LABEL_STATUS_IS, toscaElement.getUniqueId(), edgeLabel, status); - result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(toscaDataVertexRes.right().value()); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(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; + GraphVertex toscaDataVertex = null; + if (toscaDataVertexRes.isLeft()) { + toscaDataVertex = toscaDataVertexRes.left().value(); } - return result; - + StorageOperationStatus result = handleToscaData(toscaElement, vertexLabel, edgeLabel, toscaDataVertex, toscaData); + return result == null ? StorageOperationStatus.OK : result; } @SuppressWarnings({ "rawtypes", "unchecked" }) @@ -1373,18 +1350,25 @@ public abstract class BaseOperation { return StorageOperationStatus.OK; } - protected <K extends ToscaDataDefinition> StorageOperationStatus handleToscaData(GraphVertex toscaElement, VertexTypeEnum vertexLabel, EdgeLabelEnum edgeLabel, GraphVertex toscaDataVertex, Map<String, K> mergedToscaDataMap) { - + <K extends ToscaDataDefinition> StorageOperationStatus handleToscaData(GraphVertex toscaElement, VertexTypeEnum vertexLabel, + EdgeLabelEnum edgeLabel, GraphVertex toscaDataVertex, Map<String, K> mergedToscaDataMap) { StorageOperationStatus result = StorageOperationStatus.OK; if (toscaDataVertex == null) { - + if (MapUtils.isEmpty(mergedToscaDataMap)) { + //If no new data and this vertex type does not exist, return + return result; + } Either<GraphVertex, StorageOperationStatus> createRes = associateElementToData(toscaElement, vertexLabel, edgeLabel, mergedToscaDataMap); if (createRes.isRight()) { StorageOperationStatus status = createRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to assosiate tosca data {} of the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), status); + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to associate tosca data {} of the tosca element {}. Status is {}. ", edgeLabel, toscaElement.getUniqueId(), status); result = status; } } else { + if (MapUtils.isEmpty(mergedToscaDataMap)) { + JanusGraphOperationStatus janusGraphOperationStatus = janusGraphDao.disassociateAndDeleteLast(toscaElement, Direction.OUT, edgeLabel); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(janusGraphOperationStatus); + } toscaDataVertex.setJson(mergedToscaDataMap); Either<GraphVertex, JanusGraphOperationStatus> updateOrCopyRes = updateOrCopyOnUpdate(toscaDataVertex, toscaElement, edgeLabel); if (updateOrCopyRes.isRight()) { diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/CategoryOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/CategoryOperation.java index 7603657b9a..15ef5e32dc 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/CategoryOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/CategoryOperation.java @@ -78,8 +78,7 @@ public class CategoryOperation extends BaseOperation{ * @return */ public Either<GraphVertex, StorageOperationStatus> getSubCategoryForCategory(GraphVertex categoryV, String name ) { - Either<List<GraphVertex>, JanusGraphOperationStatus> childrenVertecies = janusGraphDao - .getChildrenVertecies(categoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse); + Either<List<GraphVertex>, JanusGraphOperationStatus> childrenVertecies = janusGraphDao.getChildrenVertices(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.convertJanusGraphStatusToStorageStatus(childrenVertecies.right().value())); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ExternalReferencesOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ExternalReferencesOperation.java index 71a581fa30..8dc1336d07 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ExternalReferencesOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ExternalReferencesOperation.java @@ -34,7 +34,11 @@ import org.openecomp.sdc.be.model.operations.impl.OperationUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; import static java.util.Collections.emptyMap; diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/GroupsOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/GroupsOperation.java index 03bab3b31e..c2bb1eb62f 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/GroupsOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/GroupsOperation.java @@ -31,12 +31,14 @@ import org.openecomp.sdc.be.datatypes.elements.*; import org.openecomp.sdc.be.datatypes.elements.MapCapabilityProperty; import org.openecomp.sdc.be.datatypes.elements.MapListCapabilityDataDefinition; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.datatypes.enums.PromoteVersionEnum; import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter; import org.openecomp.sdc.be.model.operations.StorageException; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.be.model.utils.GroupUtils; import org.openecomp.sdc.common.jsongraph.util.CommonUtility; import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; import org.openecomp.sdc.common.log.wrappers.Logger; @@ -46,6 +48,7 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; +import java.util.UUID; import java.util.stream.Collectors; @org.springframework.stereotype.Component("groups-operation") @@ -155,7 +158,7 @@ public class GroupsOperation extends BaseOperation { result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getComponentVertex.right().value())); } if (result == null) { - status = addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groups, JsonPresentationFields.NAME); + status = addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groups, JsonPresentationFields.CI_INVARIANT_NAME); if (status != StorageOperationStatus.OK) { result = Either.right(status); @@ -163,7 +166,7 @@ public class GroupsOperation extends BaseOperation { } if (result == null) { - Map<String, GroupDataDefinition> mapGroup = groups.stream().collect(Collectors.toMap(GroupDataDefinition::getName, x->x)); + Map<String, GroupDataDefinition> mapGroup = groups.stream().collect(Collectors.toMap(GroupDataDefinition::getInvariantName, x->x)); result = Either.left(ModelConverter.convertToGroupDefinitions(mapGroup)); } return result; @@ -179,8 +182,8 @@ public class GroupsOperation extends BaseOperation { result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getComponentVertex.right().value())); } if (result == null) { - List<String> groupName = groups.stream().map(GroupDataDefinition::getName).collect(Collectors.toList()); - status = deleteToscaDataElements(component.getUniqueId(), EdgeLabelEnum.GROUPS, groupName); + List<String> groupInvariantName = groups.stream().map(GroupDataDefinition::getInvariantName).collect(Collectors.toList()); + status = deleteToscaDataElements(component.getUniqueId(), EdgeLabelEnum.GROUPS, groupInvariantName); if (status != StorageOperationStatus.OK) { result = Either.right(status); @@ -194,7 +197,7 @@ public class GroupsOperation extends BaseOperation { return result; } - public <T extends GroupDataDefinition> Either<List<GroupDefinition>, StorageOperationStatus> updateGroups(Component component, List<T> groups, boolean promoteVersion) { + public <T extends GroupDataDefinition> Either<List<GroupDefinition>, StorageOperationStatus> updateGroups(Component component, List<T> groups, PromoteVersionEnum promoteVersion) { Either<List<GroupDefinition>, StorageOperationStatus> result = null; Either<GraphVertex, JanusGraphOperationStatus> getComponentVertex = null; StorageOperationStatus status = null; @@ -206,11 +209,11 @@ public class GroupsOperation extends BaseOperation { if (result == null) { groups.forEach(gr -> { updateVersion(promoteVersion, gr); - String groupUUID = UniqueIdBuilder.generateUUID(); - gr.setGroupUUID(groupUUID); + // String groupUUID = UniqueIdBuilder.generateUUID(); + // gr.setGroupUUID(groupUUID); }); - status = updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groups, JsonPresentationFields.NAME); + status = updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groups, JsonPresentationFields.CI_INVARIANT_NAME); if (status != StorageOperationStatus.OK) { result = Either.right(status); @@ -218,27 +221,42 @@ public class GroupsOperation extends BaseOperation { } if (result == null) { - Map<String, GroupDataDefinition> mapGroup = groups.stream().collect(Collectors.toMap( GroupDataDefinition::getName, x->x)); + Map<String, GroupDataDefinition> mapGroup = groups.stream().collect(Collectors.toMap( GroupDataDefinition::getInvariantName, x->x)); result = Either.left(ModelConverter.convertToGroupDefinitions(mapGroup)); + updateGroupsOnComponent(component, ModelConverter.convertToGroupDefinitions(mapGroup)); } return result; } - private <T extends GroupDataDefinition> void updateVersion(boolean promoteVersion, T group) { - if(promoteVersion) { - String version = group.getVersion(); - String newVersion = increaseMajorVersion(version); - group.setVersion(newVersion); + private void updateGroupsOnComponent(Component component, List<GroupDefinition> groupsToUpdate) { + List<GroupDefinition> groupsFromResource = component.getGroups(); + for (GroupDefinition group : groupsToUpdate) { + Optional<GroupDefinition> op = groupsFromResource.stream() + .filter(p -> p.getInvariantName() + .equalsIgnoreCase(group.getInvariantName())) + .findAny(); + if (op.isPresent()) { + GroupDefinition groupToUpdate = op.get(); + groupToUpdate.setMembers(group.getMembers()); + groupToUpdate.setCapabilities(group.getCapabilities()); + groupToUpdate.setProperties(group.getProperties()); + } } } - public void updateGroupOnComponent(String componentId, GroupDefinition groupDefinition) { + private <T extends GroupDataDefinition> void updateVersion(PromoteVersionEnum promoteVersion, T group) { + + group.setVersion(GroupUtils.updateVersion(promoteVersion, group.getVersion())); + } + + public void updateGroupOnComponent(String componentId, GroupDefinition groupDefinition, PromoteVersionEnum promoteMinorVersion) { GraphVertex componentVertex = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata) .left() .on(this::onJanusGraphError); + updateVersion(promoteMinorVersion, groupDefinition); StorageOperationStatus updateToscaResult = updateToscaDataOfToscaElement(componentVertex, EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groupDefinition, - JsonPresentationFields.NAME); + JsonPresentationFields.CI_INVARIANT_NAME); if (StorageOperationStatus.OK != updateToscaResult) { throw new StorageException(updateToscaResult, groupDefinition.getUniqueId()); @@ -247,6 +265,25 @@ public class GroupsOperation extends BaseOperation { updateLastUpdateDate(componentVertex); } + + public <T extends GroupDataDefinition> StorageOperationStatus updateGroupsOnComponent(String componentId, List<T> groups) { + GraphVertex componentVertex = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.ParseMetadata) + .left() + .on(this::onJanusGraphError); + + StorageOperationStatus updateToscaResult = updateToscaDataOfToscaElement(componentVertex, EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groups, JsonPresentationFields.CI_INVARIANT_NAME); + + + if (StorageOperationStatus.OK != updateToscaResult) { + throw new StorageException(updateToscaResult); + } + + updateLastUpdateDate(componentVertex); + + return updateToscaResult; + + } + private void updateLastUpdateDate(GraphVertex componentVertex) { componentVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); janusGraphDao.updateVertex(componentVertex) @@ -259,7 +296,7 @@ public class GroupsOperation extends BaseOperation { DaoStatusConverter.convertJanusGraphStatusToStorageStatus(janusGraphOperationStatus)); } - public Either<List<GroupProperty>, StorageOperationStatus> updateGroupPropertiesOnComponent(String componentId, GroupDefinition group, List<GroupProperty> newGroupProperties) { + public Either<List<GroupProperty>, StorageOperationStatus> updateGroupPropertiesOnComponent(String componentId, GroupDefinition group, List<GroupProperty> newGroupProperties, PromoteVersionEnum promoteMinorVersion) { Either<List<GroupProperty>, StorageOperationStatus> result = null; Either<GraphVertex, JanusGraphOperationStatus> getComponentVertex = null; @@ -280,8 +317,8 @@ public class GroupsOperation extends BaseOperation { currentProp.get().setValue(np.getValue()); } }); - - StorageOperationStatus updateDataRes = updateToscaDataOfToscaElement(componentVertex, EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, group, JsonPresentationFields.NAME); + updateVersion(promoteMinorVersion, group); + StorageOperationStatus updateDataRes = updateToscaDataOfToscaElement(componentVertex, EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, group, JsonPresentationFields.CI_INVARIANT_NAME); if (updateDataRes != StorageOperationStatus.OK) { log.debug("Failed to update properties for group {} error {}", group.getName(), updateDataRes); result = Either.right(updateDataRes); @@ -301,22 +338,7 @@ public class GroupsOperation extends BaseOperation { return result; } - /** - * The version of the group is an integer. In order to support BC, we might get a version in a float format. - * - * @param version - * @return - */ - private String increaseMajorVersion(String version) { - - String[] versionParts = version.split(ToscaElementLifecycleOperation.VERSION_DELIMITER_REGEXP); - Integer majorVersion = Integer.parseInt(versionParts[0]); - majorVersion++; - - return String.valueOf(majorVersion); - - } public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstances(Component component, String instanceId, List<GroupInstance> updatedGroupInstances) { @@ -343,7 +365,7 @@ public class GroupsOperation extends BaseOperation { } public Either<GroupDefinition, StorageOperationStatus> updateGroup(Component component, GroupDefinition currentGroup) { - StorageOperationStatus status = updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, currentGroup, JsonPresentationFields.NAME); + StorageOperationStatus status = updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, currentGroup, JsonPresentationFields.CI_INVARIANT_NAME); if (status != StorageOperationStatus.OK) { CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update group {} of component {}. The status is}. ", currentGroup.getName(), component.getName(), status); return Either.right(status); @@ -352,15 +374,16 @@ public class GroupsOperation extends BaseOperation { } public StorageOperationStatus deleteGroup(Component component, String currentGroupName) { - StorageOperationStatus status = deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, currentGroupName, JsonPresentationFields.NAME); + StorageOperationStatus status = deleteToscaDataElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, currentGroupName, JsonPresentationFields.CI_INVARIANT_NAME); if (status != StorageOperationStatus.OK) { CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete group {} of component {}. The status is}. ", currentGroupName, component.getName(), status); } return status; } - public Either<GroupDefinition, StorageOperationStatus> addGroup(Component component, GroupDefinition currentGroup) { - StorageOperationStatus status = addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, currentGroup, JsonPresentationFields.NAME); + public Either<GroupDefinition, StorageOperationStatus> addGroup(Component component, GroupDefinition currentGroup, PromoteVersionEnum promoteMinorVersion) { + updateVersion(promoteMinorVersion, currentGroup); + StorageOperationStatus status = addToscaDataToToscaElement(component.getUniqueId(), EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, currentGroup, JsonPresentationFields.CI_INVARIANT_NAME); if (status != StorageOperationStatus.OK) { CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update group {} of component {}. The status is}. ", currentGroup.getName(), component.getName(), status); return Either.right(status); @@ -386,6 +409,8 @@ public class GroupsOperation extends BaseOperation { }); GroupInstanceDataDefinition groupInstanceDataDefinition = new GroupInstanceDataDefinition(oldGroupInstance); List<String> pathKeys = new ArrayList<>(); + groupInstanceDataDefinition.setModificationTime(System.currentTimeMillis()); + groupInstanceDataDefinition.setCustomizationUUID(UUID.randomUUID().toString()); pathKeys.add(instanceId); StorageOperationStatus updateDataRes = updateToscaDataDeepElementOfToscaElement(componentId, EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, groupInstanceDataDefinition, pathKeys, JsonPresentationFields.NAME); if (updateDataRes != StorageOperationStatus.OK) { diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeTemplateOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeTemplateOperation.java index 2861337aec..6bdc7868d4 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeTemplateOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeTemplateOperation.java @@ -38,6 +38,10 @@ import org.openecomp.sdc.be.dao.jsongraph.types.EdgePropertyEnum; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils; +import org.openecomp.sdc.be.datatypes.elements.*; +import org.openecomp.sdc.be.datatypes.elements.MapCapabilityProperty; +import org.openecomp.sdc.be.datatypes.elements.MapListCapabilityDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.*; import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; @@ -86,6 +90,7 @@ import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement; import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElementTypeEnum; import org.openecomp.sdc.be.model.jsonjanusgraph.enums.JsonConstantKeysEnum; import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter; +import org.openecomp.sdc.be.model.operations.StorageException; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; @@ -93,6 +98,10 @@ import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.openecomp.sdc.common.jsongraph.util.CommonUtility; import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; +import org.openecomp.sdc.common.log.elements.LoggerSupportability; +import org.openecomp.sdc.common.log.enums.LogLevel; +import org.openecomp.sdc.common.log.enums.LoggerSupportabilityActions; +import org.openecomp.sdc.common.log.enums.StatusCode; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.util.ValidationUtils; @@ -106,20 +115,20 @@ import java.util.stream.Collectors; @org.springframework.stereotype.Component("node-template-operation") public class NodeTemplateOperation extends BaseOperation { private static final String FAILED_TO_FETCH_CONTAINER_VERTEX_ERROR = "Failed to fetch container vertex {} error {}"; - private static final String FAILED_TO_UPDATE_TOPOLOGY_TEMPLATE_WITH_NEW_COMPONENT_INSTANCE = "Failed to update topology template {} with new component instance {}. "; - private static final String ARTIFACT_PLACEHOLDER_TYPE = "type"; + private static final String FAILED_TO_UPDATE_TOPOLOGY_TEMPLATE_WITH_NEW_COMPONENT_INSTANCE = "Failed to update topology template {} with new component instance {}. "; + private static final String ARTIFACT_PLACEHOLDER_TYPE = "type"; private static final String ARTIFACT_PLACEHOLDER_DISPLAY_NAME = "displayName"; private static final Object ARTIFACT_PLACEHOLDER_DESCRIPTION = "description"; - public static final String HEAT_ENV_NAME = "heatEnv"; - public static final String HEAT_VF_ENV_NAME = "VfHeatEnv"; - public static final String HEAT_ENV_SUFFIX = "env"; + static final String HEAT_ENV_NAME = "heatEnv"; + static final String HEAT_VF_ENV_NAME = "VfHeatEnv"; + static final String HEAT_ENV_SUFFIX = "env"; private static Integer defaultHeatTimeout; public static final Integer NON_HEAT_TIMEOUT = 0; private static final Logger log = Logger.getLogger(NodeTemplateOperation.class.getName()); - + public LoggerSupportability loggerSupportability=LoggerSupportability.getLogger(NodeTemplateOperation.class.getName()); public NodeTemplateOperation() { - defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes(); + defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getHeatArtifactDeploymentTimeout().getDefaultMinutes(); if ((defaultHeatTimeout == null) || (defaultHeatTimeout < 1)) { defaultHeatTimeout = 60; } @@ -129,8 +138,8 @@ public class NodeTemplateOperation extends BaseOperation { 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> 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; @@ -169,7 +178,7 @@ public class NodeTemplateOperation extends BaseOperation { } if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) { TopologyTemplate updatedContainer = addComponentInstanceRes.left().value(); - result = addServerCapAndReqToProxyServerInstance(updatedContainer, componentInstance, componentInstanceData); + result = addCapAndReqToProxyServiceInstance(updatedContainer, componentInstance, componentInstanceData); if(result.isRight()) { return result; } @@ -197,12 +206,8 @@ public class NodeTemplateOperation extends BaseOperation { return result; } - private Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addServerCapAndReqToProxyServerInstance(TopologyTemplate updatedContainer, ComponentInstance componentInstance, - - ComponentInstanceDataDefinition componentInstanceData) { - - Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> result; - + private Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addCapAndReqToProxyServiceInstance(TopologyTemplate updatedContainer, ComponentInstance componentInstance, + ComponentInstanceDataDefinition componentInstanceData) { Map<String, MapListCapabilityDataDefinition> calcCap = updatedContainer.getCalculatedCapabilities(); Map<String, MapListRequirementDataDefinition> calcReg = updatedContainer.getCalculatedRequirements(); Map<String, MapCapabilityProperty> calcCapProp = updatedContainer.getCalculatedCapabilitiesProperties(); @@ -223,12 +228,10 @@ public class NodeTemplateOperation extends BaseOperation { Map<String, ListCapabilityDataDefinition> serverCap = additionalCap.entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, en -> new ListCapabilityDataDefinition(en.getValue().stream().map(CapabilityDataDefinition::new).collect(Collectors.toList())))); - serverCap.entrySet().forEach(entryPerType -> - entryPerType.getValue().getListToscaDataDefinition().forEach(cap -> { - cap.addToPath(componentInstance.getUniqueId()); - allCalculatedCap.add(entryPerType.getKey(), cap); - })); - + serverCap.entrySet().forEach(entryPerType -> entryPerType.getValue().getListToscaDataDefinition().forEach(cap -> { + cap.addToPath(componentInstance.getUniqueId()); + allCalculatedCap.add(entryPerType.getKey(), cap); + })); addToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, allCalculatedCap, componentInstance.getUniqueId()); @@ -244,34 +247,25 @@ public class NodeTemplateOperation extends BaseOperation { additionalCap.forEach(new BiConsumer<String, List<CapabilityDefinition>>() { @Override public void accept(String s, List<CapabilityDefinition> caps) { - if (caps != null && !caps.isEmpty()) { - - MapPropertiesDataDefinition dataToCreate = new MapPropertiesDataDefinition(); - + MapPropertiesDataDefinition dataToCreate; for (CapabilityDefinition cap : caps) { + dataToCreate = new MapPropertiesDataDefinition(); List<ComponentInstanceProperty> capPrps = cap.getProperties(); if (capPrps != null) { - for (ComponentInstanceProperty cip : capPrps) { dataToCreate.put(cip.getName(), new PropertyDataDefinition(cip)); } - StringBuilder sb = new StringBuilder(componentInstance.getUniqueId()); sb.append(ModelConverter.CAP_PROP_DELIM); - sb.append(cap.getOwnerId()); - sb.append(ModelConverter.CAP_PROP_DELIM).append(s).append(ModelConverter.CAP_PROP_DELIM).append(cap.getName()); allCalculatedCapProp.put(sb.toString(), dataToCreate); } } - } - } }); - addToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, allCalculatedCapProp, componentInstance.getUniqueId()); } @@ -288,12 +282,10 @@ public class NodeTemplateOperation extends BaseOperation { Map<String, ListRequirementDataDefinition> serverReq = additionalReq.entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, en -> new ListRequirementDataDefinition(en.getValue().stream().map(RequirementDataDefinition::new).collect(Collectors.toList())))); - serverReq.entrySet().forEach(entryPerType -> - entryPerType.getValue().getListToscaDataDefinition().forEach(cap -> { - cap.addToPath(componentInstance.getUniqueId()); - allCalculatedReq.add(entryPerType.getKey(), cap); - })); - + serverReq.entrySet().forEach(entryPerType -> entryPerType.getValue().getListToscaDataDefinition().forEach(cap -> { + cap.addToPath(componentInstance.getUniqueId()); + allCalculatedReq.add(entryPerType.getKey(), cap); + })); addToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, allCalculatedReq, componentInstance.getUniqueId()); @@ -302,10 +294,9 @@ public class NodeTemplateOperation extends BaseOperation { Either<ToscaElement, StorageOperationStatus> updatedComponentInstanceRes = topologyTemplateOperation.getToscaElement(updatedContainer.getUniqueId()); if (updatedComponentInstanceRes.isRight()) { CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with new component instance {}. ", updatedContainer.getName(), componentInstance.getName()); - result = Either.right(updatedComponentInstanceRes.right().value()); + Either.right(updatedComponentInstanceRes.right().value()); } - result = Either.left(new ImmutablePair<>((TopologyTemplate) updatedComponentInstanceRes.left().value(), componentInstanceData.getUniqueId())); - return result; + return Either.left(new ImmutablePair<>((TopologyTemplate) updatedComponentInstanceRes.left().value(), componentInstanceData.getUniqueId())); } private Either<String, StorageOperationStatus> buildValidateInstanceName(TopologyTemplate container, ToscaElement originToscaElement, ComponentInstance componentInstance, String instanceNumberSuffix) { @@ -421,7 +412,7 @@ public class NodeTemplateOperation extends BaseOperation { result = Either.right(StorageOperationStatus.INVALID_ID); } Boolean isArchived = originToscaElement.isArchived(); - if ( isArchived != null && isArchived ){ + if (isArchived != null && isArchived) { CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create instance {}. Origin {} component is archived . ", componentInstance.getName(), originToscaElement.getName()); result = Either.right(StorageOperationStatus.COMPONENT_IS_ARCHIVED); } @@ -437,7 +428,7 @@ public class NodeTemplateOperation extends BaseOperation { } } if (result == null) { - Either<GraphVertex, StorageOperationStatus> addToscaDataRes = addComponentInstanceToscaDataToContainerComponent(originToscaElement, componentInstance, updateElement.left().value(), user); + Either<GraphVertex, StorageOperationStatus> addToscaDataRes = addComponentInstanceToscaDataToContainerComponent(originToscaElement, componentInstance, updateElement.left().value()); if (addToscaDataRes.isRight()) { result = Either.right(addToscaDataRes.right().value()); } @@ -727,7 +718,7 @@ public class NodeTemplateOperation extends BaseOperation { return StorageOperationStatus.OK; } - protected Either<GraphVertex, StorageOperationStatus> addComponentInstanceToscaDataToContainerComponent(ToscaElement originToscaElement, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex, User user) { + protected Either<GraphVertex, StorageOperationStatus> addComponentInstanceToscaDataToContainerComponent(ToscaElement originToscaElement, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex) { Either<GraphVertex, StorageOperationStatus> result; StorageOperationStatus status; @@ -766,9 +757,9 @@ public class NodeTemplateOperation extends BaseOperation { return status; } - private MapPropertiesDataDefinition turnInputsIntoProperties(MapPropertiesDataDefinition instInput){ + private MapPropertiesDataDefinition turnInputsIntoProperties(MapPropertiesDataDefinition instInput) { if (instInput.getMapToscaDataDefinition() != null) { - for (PropertyDataDefinition currProp : instInput.getMapToscaDataDefinition().values()){ + for (PropertyDataDefinition currProp : instInput.getMapToscaDataDefinition().values()) { String temp = currProp.getValue(); currProp.setValue(currProp.getDefaultValue()); currProp.setDefaultValue(temp); @@ -996,7 +987,7 @@ public class NodeTemplateOperation extends BaseOperation { return null; } - @SuppressWarnings({ "unchecked" }) + @SuppressWarnings({"unchecked"}) private ArtifactDataDefinition createArtifactPlaceHolderInfo(ArtifactDataDefinition artifactHeat, String componentId, User user, String heatEnvType) { Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts(); if (deploymentResourceArtifacts == null) { @@ -1064,7 +1055,6 @@ public class NodeTemplateOperation extends BaseOperation { } /** - * * @param originNodeType * @param componentInstance * @param updatedContainerVertex @@ -1111,13 +1101,13 @@ public class NodeTemplateOperation extends BaseOperation { } } MapListRequirementDataDefinition fullCalculatedReq = new MapListRequirementDataDefinition(); - addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, VertexTypeEnum.FULLFILLED_REQUIREMENTS, fullCalculatedReq, componentInstance.getUniqueId()); + status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, VertexTypeEnum.FULLFILLED_REQUIREMENTS, fullCalculatedReq, componentInstance.getUniqueId()); return StorageOperationStatus.OK; } public static String createCapPropertyKey(String key, String instanceId) { - StringBuilder sb = new StringBuilder(instanceId); + StringBuffer sb = new StringBuffer(instanceId); sb.append(ModelConverter.CAP_PROP_DELIM).append(instanceId).append(ModelConverter.CAP_PROP_DELIM).append(key); return sb.toString(); } @@ -1230,7 +1220,7 @@ public class NodeTemplateOperation extends BaseOperation { 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(); + isUniqueName = !container.getComponentInstances().values().stream().anyMatch(ci -> ci.getName() != null && ci.getName().equals(instanceName)); } catch (Exception e) { CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during fetching component instance with name {} from component container {}. {} ", instanceName, container.getName(), e.getMessage()); @@ -1242,18 +1232,18 @@ public class NodeTemplateOperation extends BaseOperation { return instanceName + " " + (instanceSuffixNumber == null ? 0 : instanceSuffixNumber); } - public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String componentId, RequirementCapabilityRelDef relation) { + public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(Component component, String componentId, RequirementCapabilityRelDef relation) { List<RequirementCapabilityRelDef> relations = new ArrayList<>(); relations.add(relation); - Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> associateResourceInstances = associateResourceInstances(componentId, relations); + Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> associateResourceInstances = associateResourceInstances(component, componentId, relations); if (associateResourceInstances.isRight()) { return Either.right(associateResourceInstances.right().value()); } return Either.left(associateResourceInstances.left().value().get(0)); } - @SuppressWarnings({ "unchecked" }) - public <T extends ToscaDataDefinition> Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> associateResourceInstances(String componentId, List<RequirementCapabilityRelDef> relations) { + @SuppressWarnings({"unchecked"}) + public <T extends ToscaDataDefinition> Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> associateResourceInstances(Component component, String componentId, List<RequirementCapabilityRelDef> relations) { Either<GraphVertex, JanusGraphOperationStatus> containerVEither = janusGraphDao .getVertexById(componentId, JsonParseFlagEnum.ParseAll); @@ -1302,8 +1292,8 @@ public class NodeTemplateOperation extends BaseOperation { if (relationships == null || relationships.isEmpty()) { BeEcompErrorManager.getInstance().logBeFailedAddingResourceInstanceError("AssociateResourceInstances - missing relationship", fromNode, componentId); CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No requirement definition sent in order to set the relation between {} to {}", fromNode, toNode); - return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus( - JanusGraphOperationStatus.ILLEGAL_ARGUMENT)); + loggerSupportability.log(LogLevel.INFO,LoggerSupportabilityActions.CREATE_RELATION.getName(),"componentId: "+componentId+" No requirement definition sent in order to set the relation between: "+fromNode+" to: "+toNode); + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)); } for (CapabilityRequirementRelationship immutablePair : relationships) { @@ -1315,6 +1305,8 @@ public class NodeTemplateOperation extends BaseOperation { if (associateRes.isRight()) { status = associateRes.right().value(); BeEcompErrorManager.getInstance().logBeFailedAddingResourceInstanceError("AssociateResourceInstances - missing relationship", fromNode, componentId); + loggerSupportability.log(LogLevel.INFO,LoggerSupportabilityActions.CREATE_RELATIONS.name(), + StatusCode.ERROR,"missing relationship: "+fromNode,"ComopnentId: "+componentId); CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to associate resource instance {} to resource instance {}. status is {}", fromNode, toNode, status); return Either.right(status); } @@ -1338,10 +1330,12 @@ public class NodeTemplateOperation extends BaseOperation { CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "update customization UUID for from CI {} and to CI {}", relation.getFromNode(), relation.getToNode()); status = updateCustomizationUUID(relation.getFromNode(), compositionDataDefinition); if (status != StorageOperationStatus.OK) { + loggerSupportability.log(LogLevel.INFO,LoggerSupportabilityActions.CREATE_RELATIONS.name(),StatusCode.ERROR,"ERROR while update customization UUID for from CI "+relation.getFromNode()+" and to CI: "+relation.getToNode()); return Either.right(status); } status = updateCustomizationUUID(relation.getToNode(), compositionDataDefinition); if (status != StorageOperationStatus.OK) { + loggerSupportability.log(LogLevel.INFO,LoggerSupportabilityActions.CREATE_RELATIONS.name(),StatusCode.ERROR,"ERROR while update customization UUID for from CI "+relation.getFromNode()+" and to CI: "+relation.getToNode()); return Either.right(status); } } @@ -1349,18 +1343,16 @@ public class NodeTemplateOperation extends BaseOperation { reqCapRelDef.setRelationships(relationshipsResult); relationsList.add(reqCapRelDef); } - // update metadata of container and composition json status = updateAllAndCalculatedCapReqOnGraph(componentId, containerV, capResult, capFullResult, reqResult, reqFullResult); if (status != StorageOperationStatus.OK) { return Either.right(status); } - return Either.left(relationsList); } private StorageOperationStatus updateAllAndCalculatedCapReqOnGraph(String componentId, GraphVertex containerV, Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> capResult, - Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> capFullResult, Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqResult, - Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqFullResult) { + Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> capFullResult, Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqResult, + Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqFullResult) { containerV.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); Either<GraphVertex, JanusGraphOperationStatus> updateElement = janusGraphDao.updateVertex(containerV); if (updateElement.isRight()) { @@ -1403,7 +1395,7 @@ public class NodeTemplateOperation extends BaseOperation { return StorageOperationStatus.OK; } - @SuppressWarnings({ "unchecked" }) + @SuppressWarnings({"unchecked"}) public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) { if (requirementDef.getRelationships() == null) { CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No relation pair in request [ {} ]", requirementDef); @@ -1526,7 +1518,7 @@ public class NodeTemplateOperation extends BaseOperation { * @return */ public Either<RequirementDataDefinition, StorageOperationStatus> getFulfilledRequirementByRelation(String componentId, String instanceId, RequirementCapabilityRelDef foundRelation, - BiPredicate<RelationshipInfo, RequirementDataDefinition> predicate) { + BiPredicate<RelationshipInfo, RequirementDataDefinition> predicate) { Either<RequirementDataDefinition, StorageOperationStatus> result = null; Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqFullResult = null; @@ -1575,7 +1567,7 @@ public class NodeTemplateOperation extends BaseOperation { * @return */ public Either<CapabilityDataDefinition, StorageOperationStatus> getFulfilledCapabilityByRelation(String componentId, String instanceId, RequirementCapabilityRelDef foundRelation, - BiPredicate<RelationshipInfo, CapabilityDataDefinition> predicate) { + BiPredicate<RelationshipInfo, CapabilityDataDefinition> predicate) { Either<CapabilityDataDefinition, StorageOperationStatus> result = null; Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> capFullResult = null; @@ -1616,7 +1608,7 @@ public class NodeTemplateOperation extends BaseOperation { } private StorageOperationStatus updateCalculatedRequirementsAfterDeleteRelation(Map<String, MapListRequirementDataDefinition> calculatedRequirement, Map<String, MapListRequirementDataDefinition> fullFilledRequirement, String fromResInstanceUid, - RelationshipInstDataDefinition relation, CapabilityRequirementRelationship relationship) { + RelationshipInstDataDefinition relation, CapabilityRequirementRelationship relationship) { StorageOperationStatus status; String hereIsTheKey = null; MapListRequirementDataDefinition reqByInstance = calculatedRequirement.get(fromResInstanceUid); @@ -1651,7 +1643,7 @@ public class NodeTemplateOperation extends BaseOperation { } private StorageOperationStatus updateCalculatedCapabiltyAfterDeleteRelation(Map<String, MapListCapabilityDataDefinition> calculatedCapability, Map<String, MapListCapabilityDataDefinition> fullFilledCapability, String toResInstanceUid, - RelationshipInstDataDefinition relation, CapabilityRequirementRelationship relationship) { + RelationshipInstDataDefinition relation, CapabilityRequirementRelationship relationship) { StorageOperationStatus status; String hereIsTheKey = null; MapListCapabilityDataDefinition capByInstance = calculatedCapability.get(toResInstanceUid); @@ -1686,7 +1678,7 @@ public class NodeTemplateOperation extends BaseOperation { } private StorageOperationStatus moveFromFullFilledCapabilty(Map<String, MapListCapabilityDataDefinition> calculatedCapability, Map<String, MapListCapabilityDataDefinition> fullFilledCapability, String toResInstanceUid, - RelationshipInstDataDefinition relation, String hereIsTheKey, CapabilityRequirementRelationship relationship) { + RelationshipInstDataDefinition relation, String hereIsTheKey, CapabilityRequirementRelationship relationship) { MapListCapabilityDataDefinition capByInstance = fullFilledCapability.get(toResInstanceUid); if (capByInstance == null) { CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No capability in fulfilled list for instance {} ", toResInstanceUid); @@ -1735,7 +1727,7 @@ public class NodeTemplateOperation extends BaseOperation { } private StorageOperationStatus moveFromFullFilledRequirement(Map<String, MapListRequirementDataDefinition> calculatedRequirement, Map<String, MapListRequirementDataDefinition> fullFilledRequirement, String fromResInstanceUid, - RelationshipInstDataDefinition relation, String hereIsTheKey, CapabilityRequirementRelationship relationship) { + RelationshipInstDataDefinition relation, String hereIsTheKey, CapabilityRequirementRelationship relationship) { MapListRequirementDataDefinition reqByInstance = fullFilledRequirement.get(fromResInstanceUid); if (reqByInstance == null) { CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No requirement in fullfilled list for instance {} ", fromResInstanceUid); @@ -1798,8 +1790,8 @@ public class NodeTemplateOperation extends BaseOperation { } public <T extends ToscaDataDefinition> Either<Map<JsonPresentationFields, T>, StorageOperationStatus> connectInstancesInContainer(String fromResInstanceUid, String toResInstanceUid, RelationshipInfo relationPair, boolean originUI, - Map<String, MapListCapabilityDataDefinition> calculatedCapabilty, Map<String, MapListRequirementDataDefinition> calculatedRequirement, Map<String, MapListCapabilityDataDefinition> fullfilledCapabilty, - Map<String, MapListRequirementDataDefinition> fullfilledRequirement, CompositionDataDefinition compositionDataDefinition, String containerId) { + Map<String, MapListCapabilityDataDefinition> calculatedCapabilty, Map<String, MapListRequirementDataDefinition> calculatedRequirement, Map<String, MapListCapabilityDataDefinition> fullfilledCapabilty, + Map<String, MapListRequirementDataDefinition> fullfilledRequirement, CompositionDataDefinition compositionDataDefinition, String containerId) { String requirement = relationPair.getRequirement(); Map<String, ComponentInstanceDataDefinition> componentInstances = compositionDataDefinition.getComponentInstances(); @@ -1856,8 +1848,8 @@ public class NodeTemplateOperation extends BaseOperation { @SuppressWarnings("unchecked") private <T extends ToscaDataDefinition> Either<Map<JsonPresentationFields, T>, StorageOperationStatus> connectRequirementVsCapability(ComponentInstanceDataDefinition fromResInstance, ComponentInstanceDataDefinition toResInstance, - RelationshipInfo relationPair, boolean originUI, Map<String, MapListCapabilityDataDefinition> calculatedCapabilty, Map<String, MapListRequirementDataDefinition> calculatedRequirement, - Map<String, MapListCapabilityDataDefinition> fullfilledCapabilty, Map<String, MapListRequirementDataDefinition> fullfilledRequirement, String containerId) { + RelationshipInfo relationPair, boolean originUI, Map<String, MapListCapabilityDataDefinition> calculatedCapabilty, Map<String, MapListRequirementDataDefinition> calculatedRequirement, + Map<String, MapListCapabilityDataDefinition> fullfilledCapabilty, Map<String, MapListRequirementDataDefinition> fullfilledRequirement, String containerId) { String type = relationPair.getRelationship().getType(); // capability @@ -2007,25 +1999,27 @@ public class NodeTemplateOperation extends BaseOperation { return relationshipInstData; } - public <T extends Component> StorageOperationStatus associateComponentInstancesToComponent(Component containerComponent, Map<ComponentInstance, T> componentInstanceTMap, GraphVertex containerVertex, boolean allowDeleted) { + public <T extends Component> Map<String, ComponentInstanceDataDefinition> associateComponentInstancesToComponent(Component containerComponent, Map<ComponentInstance, T> componentInstanceTMap, GraphVertex containerVertex, boolean allowDeleted, boolean isUpdateCsar) { - StorageOperationStatus result = null; String containerId = containerComponent.getUniqueId(); - Map<String, ComponentInstanceDataDefinition> instancesJsonData = null; + Map<String, ComponentInstanceDataDefinition> instancesJsonData; Either<GraphVertex, JanusGraphOperationStatus> updateElement = null; if (!validateInstanceNames(componentInstanceTMap)) { - result = StorageOperationStatus.INCONSISTENCY; - } - if (result == null && !validateInstanceNames(componentInstanceTMap)) { - result = StorageOperationStatus.INCONSISTENCY; + throw new StorageException(StorageOperationStatus.INCONSISTENCY); } - if (result == null && !allowDeleted && !validateDeletedResources(componentInstanceTMap)) { - result = StorageOperationStatus.INCONSISTENCY; + if (!validateInstanceNames(componentInstanceTMap)) { + throw new StorageException(StorageOperationStatus.INCONSISTENCY); } - if (result == null) { - instancesJsonData = convertToComponentInstanceDataDefinition(componentInstanceTMap, containerId); + + if (!allowDeleted) { + if (!validateDeletedResources(componentInstanceTMap)) { + throw new StorageException(StorageOperationStatus.INCONSISTENCY); + } } - if (result == null && MapUtils.isNotEmpty(instancesJsonData)) { + + instancesJsonData = convertToComponentInstanceDataDefinition(componentInstanceTMap, containerId, isUpdateCsar); + + if (MapUtils.isNotEmpty(instancesJsonData)) { containerVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); Map<String, CompositionDataDefinition> compositions = new HashMap<>(); CompositionDataDefinition composition = new CompositionDataDefinition(); @@ -2035,22 +2029,21 @@ public class NodeTemplateOperation extends BaseOperation { updateElement = janusGraphDao.updateVertex(containerVertex); if (updateElement.isRight()) { CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update topology template {} with new component instances. ", containerComponent.getName()); - result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateElement.right().value()); + throw new StorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateElement.right().value())); } } - if (result == null && updateElement != null) { + if (updateElement != null) { GraphVertex vertexC = updateElement.left().value(); - instancesJsonData.entrySet().forEach(i ->createInstanceEdge(vertexC, i.getValue())); - result = StorageOperationStatus.OK; + instancesJsonData.entrySet().forEach(i -> createInstanceEdge(vertexC, i.getValue())); } - return result; + return instancesJsonData; } - private <T extends Component> Map<String, ComponentInstanceDataDefinition> convertToComponentInstanceDataDefinition(Map<ComponentInstance, T> componentInstanceTMap, String containerId) { + private <T extends Component> Map<String, ComponentInstanceDataDefinition> convertToComponentInstanceDataDefinition(Map<ComponentInstance, T> componentInstanceTMap, String containerId, boolean isUpdateCsar) { Map<String, ComponentInstanceDataDefinition> instances = new HashMap<>(); for (Entry<ComponentInstance, T> entry : componentInstanceTMap.entrySet()) { - ComponentInstanceDataDefinition instance = buildComponentInstanceDataDefinition(entry.getKey(), containerId, null, true, ModelConverter.convertToToscaElement(entry.getValue())); + ComponentInstanceDataDefinition instance = buildComponentInstanceDataDefinition(entry.getKey(), containerId, null, !isUpdateCsar || entry.getKey().isCreatedFromCsar(), ModelConverter.convertToToscaElement(entry.getValue())); instances.put(instance.getUniqueId(), instance); } return instances; @@ -2110,7 +2103,7 @@ public class NodeTemplateOperation extends BaseOperation { } - @SuppressWarnings({ "unchecked" }) + @SuppressWarnings({"unchecked"}) public StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId) { Either<GraphVertex, JanusGraphOperationStatus> metadataVertex = janusGraphDao .getVertexById(componentId, JsonParseFlagEnum.ParseAll); @@ -2181,10 +2174,10 @@ public class NodeTemplateOperation extends BaseOperation { return updateToscaDataDeepElementOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, property, pathKeys, JsonPresentationFields.NAME); } - public StorageOperationStatus updateComponentInstanceCapabilityProperty(Component containerComponent, String componentInstanceId, String capabilityUniqueId, ComponentInstanceProperty property) { + public StorageOperationStatus updateComponentInstanceCapabilityProperty(Component containerComponent, String componentInstanceId, String capabilityPropertyKey, ComponentInstanceProperty property) { List<String> pathKeys = new ArrayList<>(); pathKeys.add(componentInstanceId); - pathKeys.add(capabilityUniqueId); + pathKeys.add(capabilityPropertyKey); return updateToscaDataDeepElementOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, property, pathKeys, JsonPresentationFields.NAME); } @@ -2243,8 +2236,8 @@ public class NodeTemplateOperation extends BaseOperation { DaoStatusConverter::convertJanusGraphStatusToStorageStatus); if (result == StorageOperationStatus.OK && componentInstance.getIsProxy()) { - // create edge between container and service origin - result = createOrUpdateInstanceEdge(metadataVertex, EdgeLabelEnum.PROXY_OF, componentInstance.getSourceModelUid(), instUniqueId) + // create edge between container and service origin + result = createOrUpdateInstanceEdge(metadataVertex, EdgeLabelEnum.PROXY_OF, componentInstance.getSourceModelUid(), instUniqueId) .either(v -> StorageOperationStatus.OK, DaoStatusConverter::convertJanusGraphStatusToStorageStatus); } return result; @@ -2252,7 +2245,7 @@ public class NodeTemplateOperation extends BaseOperation { public StorageOperationStatus createAllottedOfEdge(String componentId, String instanceId, String serviceUUID) { Either<GraphVertex, JanusGraphOperationStatus> vertexById = janusGraphDao.getVertexById(componentId); - if ( vertexById.isRight() ){ + if (vertexById.isRight()) { log.debug("Failed to fetch component metadata vertex for id {} error {}", componentId, vertexById.right().value()); return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexById.right().value()); } @@ -2267,13 +2260,13 @@ public class NodeTemplateOperation extends BaseOperation { Either<List<GraphVertex>, JanusGraphOperationStatus> byCriteria = janusGraphDao .getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, props,hasNot, JsonParseFlagEnum.ParseMetadata ); - if ( byCriteria.isRight() ){ + if (byCriteria.isRight()) { log.debug("Failed to fetch vertex by criteria {} error {}", props, byCriteria.right().value()); return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(byCriteria.right().value()); } List<GraphVertex> vertecies = byCriteria.left().value(); StorageOperationStatus result = StorageOperationStatus.OK; - if ( vertecies != null ){ + if (vertecies != null) { GraphVertex serviceVertex = vertecies.get(0); //remove previous edges @@ -2333,11 +2326,10 @@ public class NodeTemplateOperation extends BaseOperation { } try { String jsonArr = JsonParserUtils.toJson(property); - log.debug("Update INSTANCES edge property with value {} ", jsonArr ); - + log.debug("Update INSTANCES edge property with value {} ", jsonArr); edge.property(EdgePropertyEnum.INSTANCES.getProperty(), jsonArr); } catch (IOException e) { - log.debug("Failed to convert INSTANCES edge property to json for container {}", metadataVertex.getUniqueId(), e ); + log.debug("Failed to convert INSTANCES edge property to json for container {}", metadataVertex.getUniqueId(), e); return Either.right(JanusGraphOperationStatus.GENERAL_ERROR); } return Either.left(metadataVertex); @@ -2361,7 +2353,7 @@ public class NodeTemplateOperation extends BaseOperation { String jsonArr = JsonParserUtils.toJson(property); edge.property(EdgePropertyEnum.INSTANCES.getProperty(), jsonArr); } catch (IOException e) { - log.debug("Failed to convert INSTANCES edge property to json for container {}", metadataVertex.getUniqueId(), e ); + log.debug("Failed to convert INSTANCES edge property to json for container {}", metadataVertex.getUniqueId(), e); return Either.right(JanusGraphOperationStatus.GENERAL_ERROR); } } @@ -2408,7 +2400,7 @@ public class NodeTemplateOperation extends BaseOperation { GraphVertex originVertex = vertexById.left().value(); JanusGraphVertex vertex = originVertex.getVertex(); Iterator<Edge> edges = vertex.edges(Direction.OUT, EdgeLabelEnum.ALLOTTED_OF.name()); - while ( edges != null && edges.hasNext() ){ + while (edges != null && edges.hasNext()) { Edge edge = edges.next(); edge.remove(); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeTypeOperation.java index eb8b90332c..96242e32a3 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeTypeOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeTypeOperation.java @@ -52,8 +52,8 @@ import java.util.stream.Collectors; @org.springframework.stereotype.Component("node-type-operation") public class NodeTypeOperation extends ToscaElementOperation { - public final static Pattern uuidNewVersion = Pattern.compile("^\\d{1,}.1"); - public final static Pattern uuidNormativeNewVersion = Pattern.compile("^\\d{1,}.0"); + public static final Pattern uuidNewVersion = Pattern.compile("^\\d+.1"); + public static final Pattern uuidNormativeNewVersion = Pattern.compile("^\\d+.0"); private static final Logger log = Logger.getLogger(NodeTypeOperation.class); private DerivedNodeTypeResolver derivedResourceResolver; @@ -68,10 +68,7 @@ public class NodeTypeOperation extends ToscaElementOperation { nodeType.generateUUID(); - //Set missing props such as names, default lifecycle state, dates etc... nodeType = getResourceMetaDataFromResource(nodeType); - - //Set unique ID String resourceUniqueId = nodeType.getUniqueId(); if (resourceUniqueId == null) { resourceUniqueId = UniqueIdBuilder.buildResourceUniqueId(); @@ -88,11 +85,9 @@ public class NodeTypeOperation extends ToscaElementOperation { derivedResources = derivedResourcesResult.left().value(); } - //Create Vertext Object and fill according to given NodeType GraphVertex nodeTypeVertex = new GraphVertex(VertexTypeEnum.NODE_TYPE); fillToscaElementVertexData(nodeTypeVertex, nodeType, JsonParseFlagEnum.ParseAll); - //Create Node Type in Graph Either<GraphVertex, JanusGraphOperationStatus> createdVertex = janusGraphDao.createVertex(nodeTypeVertex); if (createdVertex.isRight()) { JanusGraphOperationStatus status = createdVertex.right().value(); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/TopologyTemplateOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/TopologyTemplateOperation.java index a429033505..98450716e2 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/TopologyTemplateOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/TopologyTemplateOperation.java @@ -22,6 +22,24 @@ package org.openecomp.sdc.be.model.jsonjanusgraph.operations; import com.google.gson.reflect.TypeToken; import fj.data.Either; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; +import java.util.stream.Collectors; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; +import java.util.stream.Collectors; import org.apache.commons.collections.MapUtils; import org.apache.tinkerpop.gremlin.structure.Direction; import org.apache.tinkerpop.gremlin.structure.Edge; @@ -30,6 +48,8 @@ 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.datatypes.elements.MapCapabilityProperty; +import org.openecomp.sdc.be.datatypes.elements.MapListCapabilityDataDefinition; import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition; @@ -42,11 +62,9 @@ import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition; import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapCapabilityProperty; import org.openecomp.sdc.be.datatypes.elements.MapDataDefinition; import org.openecomp.sdc.be.datatypes.elements.MapGroupsDataDefinition; import org.openecomp.sdc.be.datatypes.elements.MapInterfaceDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapListCapabilityDataDefinition; import org.openecomp.sdc.be.datatypes.elements.MapListRequirementDataDefinition; import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PolicyDataDefinition; @@ -80,24 +98,12 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.util.ValidationUtils; import org.springframework.beans.factory.annotation.Autowired; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Arrays; -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.stream.Collectors; @org.springframework.stereotype.Component("topology-template-operation") public class TopologyTemplateOperation extends ToscaElementOperation { private static final Logger log = Logger.getLogger(TopologyTemplateOperation.class); - private Set<OriginTypeEnum> nodeTypeSet = new HashSet<>(Arrays.asList(OriginTypeEnum.VFC, OriginTypeEnum.CP, OriginTypeEnum.VL, OriginTypeEnum.Configuration, OriginTypeEnum.VFCMT)); + private static final String PATH_DELIMITER = "."; @Autowired private ArchiveOperation archiveOperation; @@ -120,7 +126,7 @@ public class TopologyTemplateOperation extends ToscaElementOperation { Either<GraphVertex, JanusGraphOperationStatus> createdVertex = janusGraphDao.createVertex(topologyTemplateVertex); if (createdVertex.isRight()) { JanusGraphOperationStatus status = createdVertex.right().value(); - log.debug("Error returned after creating topology template data node {}. status returned is ", topologyTemplateVertex, status); + log.debug( "Error returned after creating topology template data node {}. status returned is ", topologyTemplateVertex, status); result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); return result; } @@ -225,7 +231,7 @@ public class TopologyTemplateOperation extends ToscaElementOperation { return associatePoliciesToComponent(nodeTypeVertex, topologyTemplate.getPolicies()); } - private StorageOperationStatus associatePoliciesToComponent(GraphVertex nodeTypeVertex, Map<String, PolicyDataDefinition> policies) { + private StorageOperationStatus associatePoliciesToComponent(GraphVertex nodeTypeVertex, Map<String, PolicyDataDefinition> policies) { if (policies != null && !policies.isEmpty()) { policies.values().stream().filter(p -> p.getUniqueId() == null).forEach(p -> { String uid = UniqueIdBuilder.buildGroupingUid(nodeTypeVertex.getUniqueId(), p.getName()); @@ -241,11 +247,11 @@ public class TopologyTemplateOperation extends ToscaElementOperation { private StorageOperationStatus associateForwardingPathToResource(GraphVertex topologyTemplateVertex, TopologyTemplate topologyTemplate) { Map<String, ForwardingPathDataDefinition> forwardingPaths = topologyTemplate.getForwardingPaths(); - return associateForwardingPathToComponent(topologyTemplateVertex, forwardingPaths); + return associateForwardingPathToComponent(topologyTemplateVertex,forwardingPaths); } private StorageOperationStatus associateNodeFilterToResource(GraphVertex topologyTemplateVertex, - TopologyTemplate topologyTemplate) { + TopologyTemplate topologyTemplate) { Map<String, CINodeFilterDataDefinition> nodeFilters = topologyTemplate.getNodeFilterComponents(); return associateNodeFiltersToComponent(topologyTemplateVertex, nodeFilters); @@ -359,6 +365,15 @@ public class TopologyTemplateOperation extends ToscaElementOperation { return assosiateElementToData.right().value(); } } + Map<String, ListRequirementDataDefinition> requirements = topologyTemplate.getRequirements(); + if(MapUtils.isNotEmpty(requirements)) { + Either<GraphVertex, StorageOperationStatus> associateElementToData = + associateElementToData(nodeTypeVertex, VertexTypeEnum.REQUIREMENTS, + EdgeLabelEnum.REQUIREMENTS, requirements); + if (associateElementToData.isRight()) { + return associateElementToData.right().value(); + } + } return StorageOperationStatus.OK; } @@ -473,7 +488,7 @@ public class TopologyTemplateOperation extends ToscaElementOperation { } public StorageOperationStatus associateOrAddCalcCapReqToComponent(GraphVertex nodeTypeVertex, Map<String, MapListRequirementDataDefinition> calcRequirements, Map<String, MapListCapabilityDataDefinition> calcCapabilty, Map<String, MapCapabilityProperty> calculatedCapabilitiesProperties) { - if (calcRequirements != null && !calcRequirements.isEmpty()) { + if (!MapUtils.isEmpty(calcRequirements)) { Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_REQUIREMENTS, EdgeLabelEnum.CALCULATED_REQUIREMENTS, calcRequirements); if (assosiateElementToData.isRight()) { return assosiateElementToData.right().value(); @@ -484,8 +499,8 @@ public class TopologyTemplateOperation extends ToscaElementOperation { return assosiateElementToData.right().value(); } } - if (calcCapabilty != null && !calcCapabilty.isEmpty()) { - Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_CAPABILITIES, EdgeLabelEnum.CALCULATED_CAPABILITIES, calcCapabilty); + if (!MapUtils.isEmpty(calcCapabilty)) { + Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_CAPABILITIES ,EdgeLabelEnum.CALCULATED_CAPABILITIES, calcCapabilty); if (assosiateElementToData.isRight()) { return assosiateElementToData.right().value(); } @@ -495,7 +510,7 @@ public class TopologyTemplateOperation extends ToscaElementOperation { return assosiateElementToData.right().value(); } } - if (calculatedCapabilitiesProperties != null && !calculatedCapabilitiesProperties.isEmpty()) { + if (!MapUtils.isEmpty(calculatedCapabilitiesProperties)){ return associateOrAddElementToData(nodeTypeVertex, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, calculatedCapabilitiesProperties) .right() @@ -504,7 +519,7 @@ public class TopologyTemplateOperation extends ToscaElementOperation { return StorageOperationStatus.OK; } - private <T extends MapDataDefinition> Either<GraphVertex, StorageOperationStatus> associateOrAddElementToData(GraphVertex nodeTypeVertex, VertexTypeEnum vertexTypeEnum, EdgeLabelEnum edgeLabelEnum, Map<String, T> dataMap) { + private <T extends MapDataDefinition> Either<GraphVertex, StorageOperationStatus> associateOrAddElementToData(GraphVertex nodeTypeVertex, VertexTypeEnum vertexTypeEnum, EdgeLabelEnum edgeLabelEnum, Map<String, T> dataMap){ return janusGraphDao.getChildVertex(nodeTypeVertex, edgeLabelEnum, JsonParseFlagEnum.ParseJson) .either(dataVertex -> addElementsToComponent(nodeTypeVertex, dataVertex, vertexTypeEnum, edgeLabelEnum, dataMap), status -> associateElementToDataIfNotFound(status, nodeTypeVertex, vertexTypeEnum, edgeLabelEnum, dataMap)); @@ -523,7 +538,7 @@ public class TopologyTemplateOperation extends ToscaElementOperation { .map(e -> addElementToComponent(nodeTypeVertex.getUniqueId(), vertexTypeEnum, edgeLabelEnum, e)) .filter(s -> s != StorageOperationStatus.OK) .findFirst(); - if (error.isPresent()) { + if(error.isPresent()){ return Either.right(error.get()); } return Either.left(dataVertex); @@ -784,6 +799,14 @@ public class TopologyTemplateOperation extends ToscaElementOperation { } } + if (!componentParametersView.isIgnoreInterfaces()) { + JanusGraphOperationStatus storageStatus = setInterfcesFromGraph(componentV, toscaElement); + if (storageStatus != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(storageStatus)); + + } + } + if (!componentParametersView.isIgnoreComponentInstancesInterfaces()) { JanusGraphOperationStatus storageStatus = setComponentInstancesInterfacesFromGraph(componentV, toscaElement); @@ -814,6 +837,18 @@ public class TopologyTemplateOperation extends ToscaElementOperation { return JanusGraphOperationStatus.OK; } + private JanusGraphOperationStatus setInterfcesFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) { + Either<Map<String, InterfaceDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INTERFACE); + if (result.isLeft()) { + topologyTemplate.setInterfaces(result.left().value()); + } else { + if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + return result.right().value(); + } + } + return JanusGraphOperationStatus.OK; + } + private JanusGraphOperationStatus setPoliciesFromGraph(GraphVertex componentV, TopologyTemplate toscaElement) { Either<Map<String, PolicyDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.POLICIES); if (result.isLeft()) { @@ -866,11 +901,11 @@ public class TopologyTemplateOperation extends ToscaElementOperation { } public StorageOperationStatus associateNodeFiltersToComponent(GraphVertex nodeTypeVertex, - Map<String, CINodeFilterDataDefinition> filterMaps) { + Map<String, CINodeFilterDataDefinition> filterMaps) { if (filterMaps != null && !filterMaps.isEmpty()) { Either<GraphVertex, StorageOperationStatus> assosiateElementToData = associateElementToData - (nodeTypeVertex, VertexTypeEnum.NODE_FILTER_TEMPLATE, - EdgeLabelEnum.NODE_FILTER_TEMPLATE, filterMaps); + (nodeTypeVertex, VertexTypeEnum.NODE_FILTER_TEMPLATE, + EdgeLabelEnum.NODE_FILTER_TEMPLATE, filterMaps); if (assosiateElementToData.isRight()) { return assosiateElementToData.right().value(); } @@ -962,7 +997,7 @@ public class TopologyTemplateOperation extends ToscaElementOperation { } private JanusGraphOperationStatus setNodeFilterComponentFromGraph(GraphVertex componentV, - TopologyTemplate topologyTemplate) { + TopologyTemplate topologyTemplate) { Either<Map<String, CINodeFilterDataDefinition>, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.NODE_FILTER_TEMPLATE); @@ -1077,6 +1112,15 @@ public class TopologyTemplateOperation extends ToscaElementOperation { return result.right().value(); } } + Either<Map<String, ListCapabilityDataDefinition>, JanusGraphOperationStatus> capabilitiesResult = + getDataFromGraph(componentV, EdgeLabelEnum.CAPABILITIES); + if (capabilitiesResult.isLeft()) { + toscaElement.setCapabilities(capabilitiesResult.left().value()); + } else { + if (capabilitiesResult.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + return capabilitiesResult.right().value(); + } + } return JanusGraphOperationStatus.OK; } @@ -1096,14 +1140,14 @@ public class TopologyTemplateOperation extends ToscaElementOperation { List<CategoryDefinition> categories = new ArrayList<>(); switch (componentV.getType()) { - case RESOURCE: - return setResourceCategoryFromGraph(componentV, toscaElement); - case SERVICE: - return setServiceCategoryFromGraph(componentV, toscaElement, categories); + case RESOURCE: + return setResourceCategoryFromGraph(componentV, toscaElement); + case SERVICE: + return setServiceCategoryFromGraph(componentV, toscaElement, categories); - default: - log.debug("Not supported component type {} ", componentV.getType()); - break; + default: + log.debug("Not supported component type {} ", componentV.getType()); + break; } return JanusGraphOperationStatus.OK; } @@ -1121,8 +1165,7 @@ public class TopologyTemplateOperation extends ToscaElementOperation { category.setNormalizedName((String) metadataProperties.get(GraphPropertyEnum.NORMALIZED_NAME)); category.setName((String) metadataProperties.get(GraphPropertyEnum.NAME)); - Type listTypeCat = new TypeToken<List<String>>() { - }.getType(); + Type listTypeCat = new TypeToken<List<String>>() {}.getType(); List<String> iconsfromJsonCat = getGson().fromJson((String) metadataProperties.get(GraphPropertyEnum.ICONS.getProperty()), listTypeCat); category.setIcons(iconsfromJsonCat); categories.add(category); @@ -1151,49 +1194,49 @@ public class TopologyTemplateOperation extends ToscaElementOperation { } JanusGraphOperationStatus status = disassociateAndDeleteCommonElements(toscaElementVertex); if (status != JanusGraphOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); } status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_ATTRIBUTES); if (status != JanusGraphOperationStatus.OK) { log.debug("Failed to disassociate instances attributes for {} error {}", toscaElementVertex.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); } status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_PROPERTIES); if (status != JanusGraphOperationStatus.OK) { log.debug("Failed to disassociate instances properties for {} error {}", toscaElementVertex.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); } status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_INPUTS); if (status != JanusGraphOperationStatus.OK) { log.debug("Failed to disassociate instances inputs for {} error {}", toscaElementVertex.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); } status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.GROUPS); if (status != JanusGraphOperationStatus.OK) { log.debug("Failed to disassociate groups for {} error {}", toscaElementVertex.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); } status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.POLICIES); if (status != JanusGraphOperationStatus.OK) { log.debug("Failed to disassociate policies for {} error {}", toscaElementVertex.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); } status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_GROUPS); if (status != JanusGraphOperationStatus.OK) { log.debug("Failed to disassociate instance groups for {} error {}", toscaElementVertex.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); } status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INPUTS); if (status != JanusGraphOperationStatus.OK) { log.debug("Failed to disassociate inputs for {} error {}", toscaElementVertex.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); } status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_INPUTS); if (status != JanusGraphOperationStatus.OK) { log.debug("Failed to disassociate instance inputs for {} error {}", toscaElementVertex.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); } status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CAPABILITIES_PROPERTIES); if (status != JanusGraphOperationStatus.OK) { @@ -1203,42 +1246,42 @@ public class TopologyTemplateOperation extends ToscaElementOperation { status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CALCULATED_CAPABILITIES); if (status != JanusGraphOperationStatus.OK) { log.debug("Failed to disassociate calculated capabiliites for {} error {}", toscaElementVertex.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); } status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.FULLFILLED_CAPABILITIES); if (status != JanusGraphOperationStatus.OK) { log.debug("Failed to disassociate fullfilled capabilities for {} error {}", toscaElementVertex.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); } status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES); if (status != JanusGraphOperationStatus.OK) { log.debug("Failed to disassociate calculated capabiliites properties for {} error {}", toscaElementVertex.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); } status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.CALCULATED_REQUIREMENTS); if (status != JanusGraphOperationStatus.OK) { log.debug("Failed to disassociate calculated requirements for {} error {}", toscaElementVertex.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); } status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.FULLFILLED_REQUIREMENTS); if (status != JanusGraphOperationStatus.OK) { log.debug("Failed to disassociate full filled requirements for {} error {}", toscaElementVertex.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); } status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS); if (status != JanusGraphOperationStatus.OK) { log.debug("Failed to disassociate instance artifacts for {} error {}", toscaElementVertex.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); } status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.SERVICE_API_ARTIFACTS); if (status != JanusGraphOperationStatus.OK) { log.debug("Failed to disassociate service api artifacts for {} error {}", toscaElementVertex.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); } status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.FORWARDING_PATH); if (status != JanusGraphOperationStatus.OK) { log.debug("Failed to disassociate service api artifacts for {} error {}", toscaElementVertex.getUniqueId(), status); - return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); } status = janusGraphDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INTERFACE); if (status != JanusGraphOperationStatus.OK) { @@ -1357,7 +1400,7 @@ public class TopologyTemplateOperation extends ToscaElementOperation { getRes = janusGraphDao.getVertexById(uniqueId, JsonParseFlagEnum.ParseMetadata); if (getRes.isRight()) { JanusGraphOperationStatus status = getRes.right().value(); - log.debug("Cannot find service {} in the graph. status is {}", uniqueId, status); + log.debug( "Cannot find service {} in the graph. status is {}", uniqueId, status); result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); } } @@ -1372,7 +1415,7 @@ public class TopologyTemplateOperation extends ToscaElementOperation { if (result == null) { JanusGraphOperationStatus status = janusGraphDao.createEdge(userVertex, serviceVertex, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER, null); if (status != JanusGraphOperationStatus.OK) { - log.debug("Failed to associate user {} to component {}. Edge type is {}", userId, uniqueId, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER); + log.debug( "Failed to associate user {} to component {}. Edge type is {}", userId, uniqueId, EdgeLabelEnum.LAST_DISTRIBUTION_STATE_MODIFIER); result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); } } @@ -1390,10 +1433,8 @@ public class TopologyTemplateOperation extends ToscaElementOperation { } return result; } - /** * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId - * * @param componentId * @param instanceId * @param capabilityName @@ -1409,7 +1450,7 @@ public class TopologyTemplateOperation extends ToscaElementOperation { if (componentByLabelAndId.isRight()) { result = Either.right(componentByLabelAndId.right().value()); } - if (componentByLabelAndId.isLeft()) { + if(componentByLabelAndId.isLeft()){ Either<Map<String, MapCapabilityProperty>, JanusGraphOperationStatus> getDataRes = getDataFromGraph(componentByLabelAndId.left().value(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES); if (getDataRes.isRight()) { result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getDataRes.right().value())); @@ -1417,7 +1458,7 @@ public class TopologyTemplateOperation extends ToscaElementOperation { mapPropertiesDataDefinition = getDataRes.left().value(); } } - if (isNotEmptyMapOfProperties(instanceId, mapPropertiesDataDefinition)) { + if(isNotEmptyMapOfProperties(instanceId, mapPropertiesDataDefinition)){ result = Either.left(findComponentInstanceCapabilityProperties(instanceId, capabilityName, capabilityType, ownerId, mapPropertiesDataDefinition.get(instanceId).getMapToscaDataDefinition())); } return result; @@ -1439,14 +1480,14 @@ public class TopologyTemplateOperation extends ToscaElementOperation { private boolean isNotEmptyMapOfProperties(String instanceId, Map<String, MapCapabilityProperty> mapPropertiesDataDefinition) { - return MapUtils.isNotEmpty(mapPropertiesDataDefinition) && + return MapUtils.isNotEmpty(mapPropertiesDataDefinition) && mapPropertiesDataDefinition.get(instanceId) != null && MapUtils.isNotEmpty(mapPropertiesDataDefinition.get(instanceId).getMapToscaDataDefinition()); } private List<ComponentInstanceProperty> findComponentInstanceCapabilityProperties(String instanceId, String capabilityName, String capabilityType, String ownerId, Map<String, MapPropertiesDataDefinition> propertiesMap) { List<ComponentInstanceProperty> capPropsList = null; - for (Entry<String, MapPropertiesDataDefinition> capProp : propertiesMap.entrySet()) { + for(Entry<String, MapPropertiesDataDefinition> capProp : propertiesMap.entrySet()){ if (isBelongingPropertyMap(instanceId, capabilityName, capabilityType, ownerId, capProp)) { Map<String, PropertyDataDefinition> capMap = capProp.getValue().getMapToscaDataDefinition(); if (capMap != null && !capMap.isEmpty()) { @@ -1455,7 +1496,7 @@ public class TopologyTemplateOperation extends ToscaElementOperation { } } } - if (capPropsList == null) { + if(capPropsList == null){ capPropsList = new ArrayList<>(); } return capPropsList; @@ -1463,7 +1504,7 @@ public class TopologyTemplateOperation extends ToscaElementOperation { private boolean isBelongingPropertyMap(String instanceId, String capabilityName, String capabilityType, String ownerId, Entry<String, MapPropertiesDataDefinition> capProp) { if (capProp != null) { - String[] path = capProp.getKey().split(ModelConverter.CAP_PROP_DELIM); + String[] path = capProp.getKey().split(ModelConverter.CAP_PROP_DELIM ); if (path.length < 4) { log.debug("wrong key format for capabilty, key {}", capProp); return false; @@ -1491,11 +1532,11 @@ public class TopologyTemplateOperation extends ToscaElementOperation { } public StorageOperationStatus removePolicyFromToscaElement(GraphVertex componentV, String policyId) { - return deleteToscaDataElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policyId, JsonPresentationFields.UNIQUE_ID); + return deleteToscaDataElement(componentV, EdgeLabelEnum.POLICIES, VertexTypeEnum.POLICIES, policyId, JsonPresentationFields.UNIQUE_ID); } public StorageOperationStatus updateGroupOfToscaElement(GraphVertex componentV, GroupDefinition groupDefinition) { - return updateToscaDataOfToscaElement(componentV, EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groupDefinition, JsonPresentationFields.NAME); + return updateToscaDataOfToscaElement(componentV, EdgeLabelEnum.GROUPS, VertexTypeEnum.GROUPS, groupDefinition, JsonPresentationFields.CI_INVARIANT_NAME); } private void fillPolicyDefinition(GraphVertex componentV, PolicyDefinition policyDefinition, int counter) { @@ -1515,36 +1556,36 @@ public class TopologyTemplateOperation extends ToscaElementOperation { } void revertNamesOfCalculatedCapabilitiesRequirements(String componentId, TopologyTemplate toscaElement) { - if (MapUtils.isNotEmpty(toscaElement.getComponentInstances()) || MapUtils.isNotEmpty(toscaElement.getGroups())) { + if(MapUtils.isNotEmpty(toscaElement.getComponentInstances()) || MapUtils.isNotEmpty(toscaElement.getGroups())){ GraphVertex toscaElementV = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse) .left() .on(this::throwStorageException); - if (MapUtils.isNotEmpty(toscaElement.getComponentInstances())) { + if(MapUtils.isNotEmpty(toscaElement.getComponentInstances())){ toscaElement.getComponentInstances().values().forEach(i -> CapabilityRequirementNameResolver.revertNamesOfCalculatedCapabilitiesRequirements(toscaElement, i.getUniqueId(), this::getOriginToscaElement)); } - if (MapUtils.isNotEmpty(toscaElement.getGroups())) { + if(MapUtils.isNotEmpty(toscaElement.getGroups())){ toscaElement.getGroups().values().forEach(g -> CapabilityRequirementNameResolver.revertNamesOfCalculatedCapabilitiesRequirements(toscaElement, g.getUniqueId(), this::getOriginToscaElement)); } - topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, toscaElement.getCalculatedCapabilities()); - topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, toscaElement.getCalculatedRequirements()); - topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, toscaElement.getCalculatedCapabilitiesProperties()); + topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, toscaElement.getCalculatedCapabilities()); + topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, toscaElement.getCalculatedRequirements()); + topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, toscaElement.getCalculatedCapabilitiesProperties()); } } public void updateNamesOfCalculatedCapabilitiesRequirements(String componentId, TopologyTemplate toscaElement) { - if (MapUtils.isNotEmpty(toscaElement.getComponentInstances()) || MapUtils.isNotEmpty(toscaElement.getGroups())) { + if(MapUtils.isNotEmpty(toscaElement.getComponentInstances()) || MapUtils.isNotEmpty(toscaElement.getGroups())){ GraphVertex toscaElementV = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse) .left() .on(this::throwStorageException); - if (MapUtils.isNotEmpty(toscaElement.getComponentInstances())) { + if(MapUtils.isNotEmpty(toscaElement.getComponentInstances())){ toscaElement.getComponentInstances().values().forEach(i -> CapabilityRequirementNameResolver.updateNamesOfCalculatedCapabilitiesRequirements(toscaElement, i.getUniqueId(), i.getNormalizedName(), this::getOriginToscaElement)); } - if (MapUtils.isNotEmpty(toscaElement.getGroups())) { + if(MapUtils.isNotEmpty(toscaElement.getGroups())){ toscaElement.getGroups().values().forEach(g -> CapabilityRequirementNameResolver.updateNamesOfCalculatedCapabilitiesRequirements(toscaElement, g.getUniqueId(), g.getName(), this::getOriginToscaElement)); } - topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, toscaElement.getCalculatedCapabilities()); - topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, toscaElement.getCalculatedRequirements()); - topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, toscaElement.getCalculatedCapabilitiesProperties()); + topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, toscaElement.getCalculatedCapabilities()); + topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, toscaElement.getCalculatedRequirements()); + topologyTemplateOperation.updateFullToscaData(toscaElementV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, toscaElement.getCalculatedCapabilitiesProperties()); } } @@ -1552,13 +1593,13 @@ public class TopologyTemplateOperation extends ToscaElementOperation { log.debug("#getOriginToscaElement - origin name: {}", instance.getComponentName()); ToscaElementTypeEnum elementType = detectToscaType(instance.getOriginType()); Either<ToscaElement, StorageOperationStatus> getOriginRes; - if (elementType == ToscaElementTypeEnum.TOPOLOGY_TEMPLATE) { + if(elementType == ToscaElementTypeEnum.TOPOLOGY_TEMPLATE){ getOriginRes = this.getToscaElement(CapabilityRequirementNameResolver.getActualComponentUid(instance), getFilter()); } else { getOriginRes = nodeTypeOperation.getToscaElement(CapabilityRequirementNameResolver.getActualComponentUid(instance), getFilter()); } - if (getOriginRes.isRight()) { + if(getOriginRes.isRight()){ log.debug("Failed to get an origin component with uniqueId {}", CapabilityRequirementNameResolver.getActualComponentUid(instance)); throw new StorageException(getOriginRes.right().value()); } @@ -1567,7 +1608,11 @@ public class TopologyTemplateOperation extends ToscaElementOperation { private ToscaElementTypeEnum detectToscaType(OriginTypeEnum originType) { log.debug("#detectToscaType - type: {}", originType); - if (nodeTypeSet.contains(originType)){ + if(originType == OriginTypeEnum.VFC + || originType == OriginTypeEnum.CP + || originType == OriginTypeEnum.VL + || originType == OriginTypeEnum.Configuration + || originType == OriginTypeEnum.VFCMT){ return ToscaElementTypeEnum.NODE_TYPE; } else { return ToscaElementTypeEnum.TOPOLOGY_TEMPLATE; diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementLifecycleOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementLifecycleOperation.java index 771620d758..6ae99aeb1a 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementLifecycleOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementLifecycleOperation.java @@ -239,6 +239,15 @@ public class ToscaElementLifecycleOperation extends BaseOperation { } operation = getToscaElementOperation(currVersionV.getLabel()); result = operation.deleteToscaElement(currVersionV); + if (result.isRight()) { + return result; + } + if(preVersionVertex != null){ + String uniqueIdPreVer = (String) janusGraphDao.getProperty((JanusGraphVertex) preVersionVertex, GraphPropertyEnum.UNIQUE_ID.getProperty()); + result = operation.getToscaElement(uniqueIdPreVer); + }else{ + result = Either.left(null); + } } } catch (Exception e) { CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during undo checkout tosca element {}. {}", toscaElementId, e.getMessage()); @@ -254,114 +263,6 @@ public class ToscaElementLifecycleOperation extends BaseOperation { 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>, JanusGraphOperationStatus> getVerticesRes = janusGraphDao - .getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId)); - if (getVerticesRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId); - result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVerticesRes.right().value())); - } - if (result == null) { - toscaElement = getVerticesRes.left().value().get(toscaElementId); - modifier = getVerticesRes.left().value().get(modifierId); - owner = getVerticesRes.left().value().get(ownerId); - - StorageOperationStatus status = handleRelationsUponRequestForCertification(toscaElement, modifier, owner); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to handle relations on certification request for tosca element {}. Status is {}. ", toscaElement.getUniqueId(), status); - } - } - if (result == null) { - LifecycleStateEnum nextState = LifecycleStateEnum.READY_FOR_CERTIFICATION; - - toscaElement.addMetadataProperty(GraphPropertyEnum.STATE, nextState.name()); - toscaElement.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); - - resultUpdate = updateToscaElementVertexMetadataPropertiesAndJson(toscaElement); - if (resultUpdate.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to set lifecycle for tosca elememt {} to state {}, error: {}", toscaElement.getUniqueId(), nextState, resultUpdate.right().value()); - result = Either.right(resultUpdate.right().value()); - } - } - if (result == null) { - ToscaElementOperation operation = getToscaElementOperation(toscaElement.getLabel()); - result = operation.getToscaElement(toscaElement.getUniqueId()); - } - return result; - - } catch (Exception e) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during request certification tosca element {}. {}", toscaElementId, e.getMessage()); - } - return result; - } - - /** - * Starts certification of tosca element - * - * @param toscaElementId - * @param modifierId - * @param ownerId - * @return - */ - public Either<ToscaElement, StorageOperationStatus> startCertificationToscaElement(String toscaElementId, String modifierId, String ownerId) { - Either<ToscaElement, StorageOperationStatus> result = null; - Either<GraphVertex, StorageOperationStatus> resultUpdate = null; - GraphVertex toscaElement = null; - GraphVertex modifier = null; - GraphVertex owner; - try { - Either<Map<String, GraphVertex>, JanusGraphOperationStatus> getVerticesRes = janusGraphDao - .getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId)); - if (getVerticesRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId); - result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVerticesRes.right().value())); - } - if (result == null) { - toscaElement = getVerticesRes.left().value().get(toscaElementId); - modifier = getVerticesRes.left().value().get(modifierId); - owner = getVerticesRes.left().value().get(ownerId); - - StorageOperationStatus status = handleRelationsUponCertification(toscaElement, modifier, owner); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to handle relations during certification of tosca element {}. Status is {}. ", toscaElement.getUniqueId(), status); - } - } - if (result == null) { - LifecycleStateEnum nextState = LifecycleStateEnum.CERTIFICATION_IN_PROGRESS; - - toscaElement.addMetadataProperty(GraphPropertyEnum.STATE, nextState.name()); - toscaElement.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis()); - - resultUpdate = updateToscaElementVertexMetadataPropertiesAndJson(toscaElement); - if (resultUpdate.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Couldn't set lifecycle for component {} to state {}, error: {}", toscaElement.getUniqueId(), nextState, resultUpdate.right().value()); - result = Either.right(resultUpdate.right().value()); - } - } - if (result == null) { - ToscaElementOperation operation = getToscaElementOperation(toscaElement.getLabel()); - result = operation.getToscaElement(toscaElement.getUniqueId()); - } - } catch (Exception e) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during start certification tosca element {}. {}", toscaElementId, e.getMessage()); - } - return result; - } - public Either<ToscaElement, StorageOperationStatus> certifyToscaElement(String toscaElementId, String modifierId, String ownerId) { Either<ToscaElement, StorageOperationStatus> result = null; Either<GraphVertex, StorageOperationStatus> cloneRes = null; @@ -392,13 +293,12 @@ public class ToscaElementLifecycleOperation extends BaseOperation { if (cloneRes.isRight()) { CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to clone tosca element during certification. "); result = Either.right(cloneRes.right().value()); - } - } - if (result == null) { - certifiedToscaElement = cloneRes.left().value(); - status = handleRelationsOfNewestCertifiedToscaElement(toscaElement, certifiedToscaElement); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to handle relations of newest certified tosca element {}. Status is {}. ", certifiedToscaElement.getUniqueId(), status); + } else { + certifiedToscaElement = cloneRes.left().value(); + status = handleRelationsOfNewestCertifiedToscaElement(toscaElement, certifiedToscaElement); + if (status != StorageOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to handle relations of newest certified tosca element {}. Status is {}. ", certifiedToscaElement.getUniqueId(), status); + } } } if (result == null) { @@ -410,98 +310,15 @@ public class ToscaElementLifecycleOperation extends BaseOperation { 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); + private StorageOperationStatus handleRelationsOfNewestCertifiedToscaElement(GraphVertex toscaElement, GraphVertex certifiedToscaElement) { - try { - Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class); - properties.put(GraphPropertyEnum.UUID, uuid); - properties.put(GraphPropertyEnum.NAME, componentName); - Either<List<GraphVertex>, JanusGraphOperationStatus> getToscaElementsRes = janusGraphDao - .getByCriteria(vertexType, properties, JsonParseFlagEnum.ParseMetadata); - if (getToscaElementsRes.isRight()) { - result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getToscaElementsRes.right().value())); - } - if (result == null) { - result = markToscaElementsAsDeleted(operation, getToscaElementsRes.left().value()); - } - if (result == null) { - result = Either.left(true); - } - } catch (Exception e) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during deleteng all tosca elements by UUID {} and name {}. {} ", uuid, componentName, e.getMessage()); + JanusGraphOperationStatus createVersionEdgeStatus = janusGraphDao.createEdge(toscaElement, certifiedToscaElement, EdgeLabelEnum.VERSION, new HashMap<>()); + if (createVersionEdgeStatus != JanusGraphOperationStatus.OK) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create version edge from last element {} to new certified element {}. status=", toscaElement.getUniqueId(), certifiedToscaElement.getUniqueId(), + createVersionEdgeStatus); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createVersionEdgeStatus); } - 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>, JanusGraphOperationStatus> getVerticesRes = janusGraphDao - .getVerticesByUniqueIdAndParseFlag(prepareParametersToGetVerticesForRequestCertification(toscaElementId, modifierId, ownerId)); - if (getVerticesRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_VERTICES, toscaElementId); - result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(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, JanusGraphOperationStatus> updateVertexRes = janusGraphDao.updateVertex(toscaElement); - if (updateVertexRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update vertex {} . Status is {}. ", toscaElementId, updateVertexRes.right().value()); - result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateVertexRes.right().value())); - } - } - if (result == null) { - // cancel certification process - status = handleRelationsUponCancelCertification(toscaElement, nextState); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to handle relations upon cancel certification {}. Status is {}. ", toscaElement.getUniqueId(), status); - } - } - if (result == null) { - // fail certification - status = handleRelationsUponFailCertification(toscaElement, nextState); - if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to handle relations upon fail certification {}. Status is {}. ", toscaElement.getUniqueId(), status); - } - } - if (result == null) { - result = operation.getToscaElement(toscaElementId); - } - } catch (Exception e) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Exception occured during cancel or fail certification of tosca element {}. {}. ", toscaElementId, e.getMessage()); - } - return result; + return StorageOperationStatus.OK; } public Either<GraphVertex, JanusGraphOperationStatus> findUser(String userId) { @@ -511,7 +328,7 @@ public class ToscaElementLifecycleOperation extends BaseOperation { 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())) { + if (!(resourceToDelete.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)).equals(LifecycleStateEnum.CERTIFIED.name())) { Either<GraphVertex, StorageOperationStatus> deleteElementRes = operation.markComponentToDelete(resourceToDelete); if (deleteElementRes.isRight()) { CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete tosca element {}. Status is {}. ", resourceToDelete.getUniqueId(), deleteElementRes.right().value()); @@ -523,177 +340,6 @@ public class ToscaElementLifecycleOperation extends BaseOperation { return result; } - private StorageOperationStatus handleRelationsOfNewestCertifiedToscaElement(GraphVertex toscaElement, GraphVertex certifiedToscaElement) { - StorageOperationStatus result = null; - Edge foundEdge = null; - Iterator<Edge> certReqUserEdgeIter = null; - // add rfc relation to preserve follower information - // get user of certification request - certReqUserEdgeIter = toscaElement.getVertex().edges(Direction.IN, GraphEdgeLabels.LAST_STATE.name()); - if (certReqUserEdgeIter == null || !certReqUserEdgeIter.hasNext()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find rfc relation during certification clone. "); - result = StorageOperationStatus.NOT_FOUND; - } - if (result == null) { - JanusGraphOperationStatus - createVersionEdgeStatus = janusGraphDao - .createEdge(toscaElement, certifiedToscaElement, EdgeLabelEnum.VERSION, new HashMap<>()); - if (createVersionEdgeStatus != JanusGraphOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create version edge from last element {} to new certified element {}. status=", toscaElement.getUniqueId(), certifiedToscaElement.getUniqueId(), - createVersionEdgeStatus); - result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createVersionEdgeStatus); - } - } - if (result == null) { - if (certReqUserEdgeIter!=null) { - while (certReqUserEdgeIter.hasNext()) { - Edge edge = certReqUserEdgeIter.next(); - if (((String) janusGraphDao.getProperty(edge, EdgePropertyEnum.STATE)).equals(LifecycleStateEnum.READY_FOR_CERTIFICATION.name())) { - foundEdge = edge; - break; - } - - } - } - if (foundEdge == null) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find rfc relation during certification clone. "); - result = StorageOperationStatus.NOT_FOUND; - } - } - if (result == null) { - JanusGraphOperationStatus - createEdgeRes = janusGraphDao - .createEdge(foundEdge.outVertex(), certifiedToscaElement.getVertex(), EdgeLabelEnum.LAST_STATE, foundEdge); - if (createEdgeRes != JanusGraphOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create rfc relation for component {}. status=", certifiedToscaElement.getUniqueId(), createEdgeRes); - result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createEdgeRes); - } - } - if (result == null) { - result = StorageOperationStatus.OK; - } - return result; - } - - private StorageOperationStatus handleRelationsUponFailCertification(GraphVertex toscaElement, LifecycleStateEnum nextState) { - StorageOperationStatus result = null; - JanusGraphOperationStatus 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, JanusGraphOperationStatus> deleteResult = janusGraphDao - .deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.STATE, properties); - if (deleteResult.isRight()) { - status = deleteResult.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete state edge. Status is {}. ", status); - result = StorageOperationStatus.INCONSISTENCY; - } - if (result == null) { - // delete relation READY_FOR_CERTIFICATION - properties.put(GraphPropertyEnum.STATE, LifecycleStateEnum.READY_FOR_CERTIFICATION); - deleteResult = janusGraphDao - .deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.LAST_STATE, properties); - if (deleteResult.isRight()) { - status = deleteResult.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_DELETE_LAST_STATE_EDGE_STATUS_IS, status); - result = StorageOperationStatus.INCONSISTENCY; - } - } - if (result == null) { - // delete relation NOT_CERTIFIED_CHECKIN (in order to change to STATE) - properties.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - deleteResult = janusGraphDao - .deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.LAST_STATE, properties); - if (deleteResult.isRight()) { - status = deleteResult.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_DELETE_LAST_STATE_EDGE_STATUS_IS, status); - result = StorageOperationStatus.INCONSISTENCY; - } - } - if (result == null) { - // create new STATE relation NOT_CERTIFIED_CHECKIN - originEdge = deleteResult.left().value(); - user = originEdge.outVertex(); - status = janusGraphDao - .createEdge(user, toscaElement.getVertex(), EdgeLabelEnum.STATE, originEdge); - if (status != JanusGraphOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create state edge. Status is {}. ", status); - result = StorageOperationStatus.INCONSISTENCY; - } - } - if (result == null) { - // delete relation LAST_MODIFIER (in order to change tester to designer) - deleteResult = janusGraphDao - .deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.LAST_MODIFIER, new HashMap<>()); - if (status != JanusGraphOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create last modifier edge. Status is {}. ", status); - result = StorageOperationStatus.INCONSISTENCY; - } - } - if (result == null) { - // create new LAST_MODIFIER relation - originEdge = deleteResult.left().value(); - status = janusGraphDao.createEdge(user, toscaElement.getVertex(), EdgeLabelEnum.LAST_MODIFIER, originEdge); - if (status != JanusGraphOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create last modifier edge. Status is {}. ", status); - result = StorageOperationStatus.INCONSISTENCY; - } - } - } - if (result == null) { - result = StorageOperationStatus.OK; - } - return result; - } - - private StorageOperationStatus handleRelationsUponCancelCertification(GraphVertex toscaElement, LifecycleStateEnum nextState) { - StorageOperationStatus result = null; - Edge originEdge; - if (nextState == LifecycleStateEnum.READY_FOR_CERTIFICATION) { - // delete relation CERTIFICATION_IN_PROGRESS - Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class); - properties.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - Either<Edge, JanusGraphOperationStatus> deleteResult = janusGraphDao - .deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.STATE, properties); - - if (deleteResult.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete state edge. Status is {}. ", deleteResult.right().value()); - result = StorageOperationStatus.INCONSISTENCY; - } - if (result == null) { - // delete relation READY_FOR_CERTIFICATION (LAST_STATE) - properties.put(GraphPropertyEnum.STATE, nextState); - deleteResult = janusGraphDao - .deleteBelongingEdgeByCriteria(toscaElement, EdgeLabelEnum.LAST_STATE, properties); - - if (deleteResult.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_DELETE_LAST_STATE_EDGE_STATUS_IS, deleteResult.right().value()); - result = StorageOperationStatus.INCONSISTENCY; - } - } - if (result == null) { - // create relation READY_FOR_CERTIFICATION (STATE) - originEdge = deleteResult.left().value(); - JanusGraphOperationStatus - status = janusGraphDao - .createEdge(originEdge.outVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, originEdge); - if (status != JanusGraphOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create state edge. Status is {}. ", status); - result = StorageOperationStatus.INCONSISTENCY; - } - } - if (result == null) { - result = StorageOperationStatus.OK; - } - } - return result; - } - private StorageOperationStatus handleRelationsOfPreviousToscaElementBeforeCertifying(GraphVertex toscaElement, GraphVertex modifier, Integer majorVersion) { StorageOperationStatus result = null; if (majorVersion > 0) { @@ -729,84 +375,6 @@ public class ToscaElementLifecycleOperation extends BaseOperation { return result; } - private StorageOperationStatus handleRelationsUponRequestForCertification(GraphVertex toscaElement, GraphVertex modifier, GraphVertex owner) { - JanusGraphOperationStatus status; - StorageOperationStatus result = null; - - if (((String) toscaElement.getMetadataProperty(GraphPropertyEnum.STATE)).equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { - // remove CHECKOUT relation - Either<Edge, JanusGraphOperationStatus> deleteRes = janusGraphDao - .deleteEdge(owner, toscaElement, EdgeLabelEnum.STATE); - if (deleteRes.isRight()) { - status = deleteRes.right().value(); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete edge. Status is {}. ", status); - result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); - } - if (result == null) { - // create CHECKIN relation - Map<EdgePropertyEnum, Object> properties = new EnumMap<>(EdgePropertyEnum.class); - properties.put(EdgePropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN); - status = janusGraphDao - .createEdge(modifier.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.LAST_STATE, properties); - if (status != JanusGraphOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge. Status is {}", status); - result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); - } - } - } else { - status = janusGraphDao - .replaceEdgeLabel(owner.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE); - if (status != JanusGraphOperationStatus.OK) { - result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); - } - } - if (result == null) { - // create RFC relation - Map<EdgePropertyEnum, Object> properties = new EnumMap<>(EdgePropertyEnum.class); - properties.put(EdgePropertyEnum.STATE, LifecycleStateEnum.READY_FOR_CERTIFICATION); - status = janusGraphDao - .createEdge(modifier.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, properties); - if (status != JanusGraphOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create edge. Status is {}", status); - result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); - } - } - if (result == null) { - result = StorageOperationStatus.OK; - } - return result; - } - - private StorageOperationStatus handleRelationsUponCertification(GraphVertex toscaElement, GraphVertex modifier, GraphVertex owner) { - - StorageOperationStatus result = null; - JanusGraphOperationStatus status = janusGraphDao - .replaceEdgeLabel(owner.getVertex(), toscaElement.getVertex(), EdgeLabelEnum.STATE, EdgeLabelEnum.LAST_STATE); - if (status != JanusGraphOperationStatus.OK) { - result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); - } - if (result == null) { - Map<EdgePropertyEnum, Object> properties = new EnumMap<>(EdgePropertyEnum.class); - properties.put(EdgePropertyEnum.STATE, LifecycleStateEnum.CERTIFICATION_IN_PROGRESS); - status = janusGraphDao - .createEdge(modifier, toscaElement, EdgeLabelEnum.STATE, properties); - if (status != JanusGraphOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "failed to create edge. Status is {}", status); - result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); - } - } - if (result == null) { - Either<GraphVertex, StorageOperationStatus> updateRelationsRes = updateLastModifierEdge(toscaElement, owner, modifier); - if (updateRelationsRes.isRight()) { - result = updateRelationsRes.right().value(); - } - } - if (result == null) { - result = StorageOperationStatus.OK; - } - return result; - } - private Either<Vertex, StorageOperationStatus> findLastCertifiedToscaElementVertex(GraphVertex toscaElement) { return findLastCertifiedToscaElementVertexRecursively(toscaElement.getVertex()); } @@ -1208,7 +776,7 @@ public class ToscaElementLifecycleOperation extends BaseOperation { 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())) { + if (toscaElementVertex.getType() == ComponentTypeEnum.SERVICE) { nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); } if (!MapUtils.isEmpty(toscaElementVertex.getMetadataJson())) { @@ -1348,7 +916,7 @@ public class ToscaElementLifecycleOperation extends BaseOperation { 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)) { + if (toscaElementVertex.getType() == ComponentTypeEnum.SERVICE) { nextVersionToscaElementVertex.addMetadataProperty(GraphPropertyEnum.DISTRIBUTION_STATUS, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name()); } if (!MapUtils.isEmpty(toscaElementVertex.getMetadataJson())) { @@ -1399,27 +967,14 @@ public class ToscaElementLifecycleOperation extends BaseOperation { 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 EnumMap<>(GraphPropertyEnum.class); - vertexProperties.put(GraphPropertyEnum.STATE, nextState); - Either<Edge, JanusGraphOperationStatus> deleteResult = janusGraphDao - .deleteBelongingEdgeByCriteria(toscaElementVertex, EdgeLabelEnum.LAST_STATE, vertexProperties); - if (deleteResult.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, faileToUpdateStateMsg, toscaElementVertex.getUniqueId(), deleteResult.right().value()); - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "failed to update last state relation"); - result = Either.right(StorageOperationStatus.INCONSISTENCY); - } - } - if (result == null) { - // Remove CHECKOUT relation + // Remove CHECKOUT relation Either<Edge, JanusGraphOperationStatus> deleteEdgeResult = janusGraphDao .deleteEdge(ownerVertex, toscaElementVertex, EdgeLabelEnum.STATE); - if (deleteEdgeResult.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, faileToUpdateStateMsg, toscaElementVertex.getUniqueId()); + if (deleteEdgeResult.isRight()) { + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, faileToUpdateStateMsg, toscaElementVertex.getUniqueId()); result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(deleteEdgeResult.right().value())); - } } + if (result == null) { // Create CHECKIN relation Map<EdgePropertyEnum, Object> edgeProperties = new EnumMap<>(EdgePropertyEnum.class); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementOperation.java index 791db33d66..e973400963 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementOperation.java @@ -20,14 +20,17 @@ package org.openecomp.sdc.be.model.jsonjanusgraph.operations; -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; -import fj.data.Either; +import java.lang.reflect.Type; +import java.util.*; +import java.util.Map.Entry; +import java.util.stream.Collectors; + import org.apache.commons.collections.CollectionUtils; import org.apache.tinkerpop.gremlin.structure.Direction; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.apache.tinkerpop.gremlin.structure.VertexProperty; +import org.janusgraph.core.JanusGraphVertex; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; @@ -64,14 +67,10 @@ import org.openecomp.sdc.common.util.ValidationUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StopWatch; -import java.lang.reflect.Type; -import java.util.*; -import java.util.Map.Entry; -import java.util.stream.Collectors; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; + +import fj.data.Either; public abstract class ToscaElementOperation extends BaseOperation { private static final String FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR = "failed to fetch {} for tosca element with id {}, error {}"; @@ -80,6 +79,8 @@ public abstract class ToscaElementOperation extends BaseOperation { private static final String FAILED_TO_CREATE_EDGE_WITH_LABEL_FROM_USER_VERTEX_TO_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS = "Failed to create edge with label {} from user vertex {} to tosca element vertex {} on graph. Status is {}. "; + private static final String FAILED_TO_GET_CREATOR_VERTEX_OF_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS = "Failed to get creator vertex with label {} of tosca element vertex {} on graph. Status is {}. "; + private static Logger log = Logger.getLogger(ToscaElementOperation.class.getName()); private static final Gson gson = new Gson(); @@ -189,8 +190,18 @@ public abstract class ToscaElementOperation extends BaseOperation { } } if (result == null) { - status = janusGraphDao - .createEdge(user.getVertex(), createdToscaElementVertex.getVertex(), EdgeLabelEnum.CREATOR, new HashMap<>()); + Either<GraphVertex, JanusGraphOperationStatus> creatorVertexRes = janusGraphDao.getParentVertex(previousToscaElement, + EdgeLabelEnum.CREATOR, JsonParseFlagEnum.NoParse); + if (creatorVertexRes.isRight()) { + status = creatorVertexRes.right().value(); + CommonUtility.addRecordToLog(log, + LogLevelEnum.DEBUG, FAILED_TO_GET_CREATOR_VERTEX_OF_TOSCA_ELEMENT_VERTEX_ON_GRAPH_STATUS_IS, + EdgeLabelEnum.CREATOR, + nextToscaElement.getMetadataProperty(GraphPropertyEnum.NORMALIZED_NAME), status); + result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + status = janusGraphDao.createEdge(creatorVertexRes.left().value().getVertex(), createdToscaElementVertex.getVertex(), + EdgeLabelEnum.CREATOR, new HashMap<>()); if (status != JanusGraphOperationStatus.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); @@ -603,8 +614,7 @@ public abstract class ToscaElementOperation extends BaseOperation { if (derivedResources != null && !derivedResources.isEmpty()) { for (GraphVertex derived : derivedResources) { - Either<List<GraphVertex>, JanusGraphOperationStatus> derivedProperties = janusGraphDao - .getChildrenVertecies(derived, edge, JsonParseFlagEnum.ParseJson); + Either<List<GraphVertex>, JanusGraphOperationStatus> derivedProperties = janusGraphDao.getChildrenVertices(derived, edge, JsonParseFlagEnum.ParseJson); if (derivedProperties.isRight()) { if (derivedProperties.right().value() != JanusGraphOperationStatus.NOT_FOUND) { log.debug("Failed to get properties for derived from {} error {}", derived.getUniqueId(), derivedProperties.right().value()); @@ -714,42 +724,38 @@ public abstract class ToscaElementOperation extends BaseOperation { log.debug("Failed to fetch users by criteria {} error {}", props, usersByCriteria.right().value()); return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(usersByCriteria.right().value())); } - List<GraphVertex> users = usersByCriteria.left().value(); + GraphVertex userV = usersByCriteria.left().value().get(0); List<T> components = new ArrayList<>(); List<T> componentsPerUser; - for (GraphVertex userV : users) { - HashSet<String> ids = new HashSet<>(); - Either<List<GraphVertex>, JanusGraphOperationStatus> childrenVertecies = janusGraphDao - .getChildrenVertecies(userV, EdgeLabelEnum.STATE, JsonParseFlagEnum.NoParse); - if (childrenVertecies.isRight() && childrenVertecies.right().value() != JanusGraphOperationStatus.NOT_FOUND) { - log.debug("Failed to fetch children vertices for user {} by edge {} error {}", userV.getMetadataProperty(GraphPropertyEnum.USERID), EdgeLabelEnum.STATE, childrenVertecies.right().value()); + HashSet<String> ids = new HashSet<String>(); + Either<List<GraphVertex>, JanusGraphOperationStatus> childrenVertecies = janusGraphDao.getChildrenVertices(userV, EdgeLabelEnum.STATE, JsonParseFlagEnum.NoParse); + if (childrenVertecies.isRight() && childrenVertecies.right().value() != JanusGraphOperationStatus.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.convertJanusGraphStatusToStorageStatus(childrenVertecies.right().value())); - } + } - // get all resource with current state - if (childrenVertecies.isLeft()) { - componentsPerUser = fetchComponents(lifecycleStates, childrenVertecies.left().value(), neededType, EdgeLabelEnum.STATE); + // get all resource with current state + if (childrenVertecies.isLeft()) { + componentsPerUser = fetchComponents(userId, lifecycleStates, childrenVertecies.left().value(), neededType, EdgeLabelEnum.STATE); - if (componentsPerUser != null) { - for (T comp : componentsPerUser) { - ids.add(comp.getUniqueId()); - components.add(comp); - } + 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 = janusGraphDao - .getChildrenVertecies(userV, EdgeLabelEnum.LAST_STATE, JsonParseFlagEnum.NoParse); + childrenVertecies = janusGraphDao.getChildrenVertices(userV, EdgeLabelEnum.LAST_STATE, JsonParseFlagEnum.NoParse); if (childrenVertecies.isRight() && childrenVertecies.right().value() != JanusGraphOperationStatus.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.convertJanusGraphStatusToStorageStatus(childrenVertecies.right().value())); } if (childrenVertecies.isLeft()) { boolean isFirst; - componentsPerUser = fetchComponents(lastStateStates, childrenVertecies.left().value(), neededType, EdgeLabelEnum.LAST_STATE); + componentsPerUser = fetchComponents(userId, lastStateStates, childrenVertecies.left().value(), neededType, EdgeLabelEnum.LAST_STATE); if (componentsPerUser != null) { for (T comp : componentsPerUser) { isFirst = true; @@ -773,7 +779,7 @@ public abstract class ToscaElementOperation extends BaseOperation { } - private <T extends ToscaElement> List<T> fetchComponents(Set<LifecycleStateEnum> lifecycleStates, List<GraphVertex> vertices, ComponentTypeEnum neededType, EdgeLabelEnum edgelabel) { + private <T extends ToscaElement> List<T> fetchComponents(String userId, Set<LifecycleStateEnum> lifecycleStates, List<GraphVertex> vertices, ComponentTypeEnum neededType, EdgeLabelEnum edgelabel) { List<T> components = new ArrayList<>(); for (GraphVertex node : vertices) { @@ -787,7 +793,12 @@ public abstract class ToscaElementOperation extends BaseOperation { log.debug("no supported STATE {} for element {}", stateStr, node.getUniqueId()); continue; } - if (lifecycleStates != null && lifecycleStates.contains(nodeState)) { + + //get user from edge and compare to user from followed request + JanusGraphVertex userVertex = (JanusGraphVertex) edge.outVertex(); + String userIdFromEdge = (String) janusGraphDao.getProperty(userVertex, GraphPropertyEnum.USERID.getProperty()); + + if (lifecycleStates != null && lifecycleStates.contains(nodeState) && (userIdFromEdge.equals(userId))) { Boolean isDeleted = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_DELETED); Boolean isArchived = (Boolean) node.getMetadataProperty(GraphPropertyEnum.IS_ARCHIVED); @@ -915,6 +926,8 @@ public abstract class ToscaElementOperation extends BaseOperation { } protected JanusGraphOperationStatus setResourceCategoryFromGraphV(Vertex vertex, CatalogComponent catalogComponent) { + List<CategoryDefinition> categories = new ArrayList<>(); + SubCategoryDefinition subcategory; Either<Vertex, JanusGraphOperationStatus> childVertex = janusGraphDao .getChildVertex(vertex, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse); @@ -923,25 +936,44 @@ public abstract class ToscaElementOperation extends BaseOperation { return childVertex.right().value(); } Vertex subCategoryV = childVertex.left().value(); - catalogComponent.setSubCategoryNormalizedName((String) subCategoryV.property(JsonPresentationFields.NORMALIZED_NAME.getPresentation()).value()); - Either<Vertex, JanusGraphOperationStatus> parentVertex = janusGraphDao - .getParentVertex(subCategoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse); + String subCategoryNormalizedName = (String) subCategoryV.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty()).value(); + catalogComponent.setSubCategoryNormalizedName(subCategoryNormalizedName); + subcategory = new SubCategoryDefinition(); + subcategory.setUniqueId((String) subCategoryV.property(GraphPropertyEnum.UNIQUE_ID.getProperty()).value()); + subcategory.setNormalizedName(subCategoryNormalizedName); + subcategory.setName((String) subCategoryV.property(GraphPropertyEnum.NAME.getProperty()).value()); + Either<Vertex, JanusGraphOperationStatus> parentVertex = janusGraphDao.getParentVertex(subCategoryV, EdgeLabelEnum.SUB_CATEGORY, JsonParseFlagEnum.NoParse); Vertex categoryV = parentVertex.left().value(); - catalogComponent.setCategoryNormalizedName((String) categoryV.property(JsonPresentationFields.NORMALIZED_NAME.getPresentation()).value()); + String categoryNormalizedName = (String) categoryV.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty()).value(); + catalogComponent.setCategoryNormalizedName(categoryNormalizedName); + CategoryDefinition category = new CategoryDefinition(); + category.setUniqueId((String) categoryV.property(GraphPropertyEnum.UNIQUE_ID.getProperty()).value()); + category.setNormalizedName(categoryNormalizedName); + category.setName((String) categoryV.property(GraphPropertyEnum.NAME.getProperty()).value()); + category.addSubCategory(subcategory); + categories.add(category); + catalogComponent.setCategories(categories); return JanusGraphOperationStatus.OK; } protected JanusGraphOperationStatus setServiceCategoryFromGraphV(Vertex vertex, CatalogComponent catalogComponent) { - Either<Vertex, JanusGraphOperationStatus> childVertex = janusGraphDao - .getChildVertex(vertex, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse); + List<CategoryDefinition> categories = new ArrayList<>(); + Either<Vertex, JanusGraphOperationStatus> childVertex = janusGraphDao.getChildVertex(vertex, EdgeLabelEnum.CATEGORY, JsonParseFlagEnum.NoParse); if (childVertex.isRight()) { log.debug(FAILED_TO_FETCH_FOR_TOSCA_ELEMENT_WITH_ID_ERROR, EdgeLabelEnum.CATEGORY, catalogComponent.getUniqueId(), childVertex.right().value()); return childVertex.right().value(); } Vertex categoryV = childVertex.left().value(); - catalogComponent.setCategoryNormalizedName((String) categoryV.property(JsonPresentationFields.NORMALIZED_NAME.getPresentation()).value()); + String categoryNormalizedName = (String) categoryV.property(GraphPropertyEnum.NORMALIZED_NAME.getProperty()).value(); + catalogComponent.setCategoryNormalizedName(categoryNormalizedName); + CategoryDefinition category = new CategoryDefinition(); + category.setUniqueId((String) categoryV.property(GraphPropertyEnum.UNIQUE_ID.getProperty()).value()); + category.setNormalizedName(categoryNormalizedName); + category.setName((String) categoryV.property(GraphPropertyEnum.NAME.getProperty()).value()); + categories.add(category); + catalogComponent.setCategories(categories); return JanusGraphOperationStatus.OK; } @@ -1241,8 +1273,18 @@ public abstract class ToscaElementOperation extends BaseOperation { catalogComponent.setName((String) metadatObj.get(JsonPresentationFields.NAME.getPresentation())); catalogComponent.setIcon((String) metadatObj.get(JsonPresentationFields.ICON.getPresentation())); catalogComponent.setLifecycleState((String) metadatObj.get(JsonPresentationFields.LIFECYCLE_STATE.getPresentation())); - catalogComponent.setLastUpdateDate((Long) metadatObj.get(JsonPresentationFields.LAST_UPDATE_DATE.getPresentation())); + Object lastUpdateDate = metadatObj.get(JsonPresentationFields.LAST_UPDATE_DATE.getPresentation()); + catalogComponent.setLastUpdateDate( (lastUpdateDate != null ? (Long)lastUpdateDate : 0L)); catalogComponent.setDistributionStatus((String) metadatObj.get(JsonPresentationFields.DISTRIBUTION_STATUS.getPresentation())); + catalogComponent.setDescription((String) metadatObj.get(JsonPresentationFields.DESCRIPTION.getPresentation())); + catalogComponent.setSystemName((String) metadatObj.get(JsonPresentationFields.SYSTEM_NAME.getPresentation())); + catalogComponent.setUuid((String) metadatObj.get(JsonPresentationFields.UUID.getPresentation())); + catalogComponent.setInvariantUUID((String) metadatObj.get(JsonPresentationFields.INVARIANT_UUID.getPresentation())); + catalogComponent.setIsHighestVersion((Boolean) metadatObj.get(JsonPresentationFields.HIGHEST_VERSION.getPresentation())); + Iterator<Edge> edges = vertex.edges(Direction.IN, EdgeLabelEnum.STATE.name()); + if(edges.hasNext()){ + catalogComponent.setLastUpdaterUserId((String) edges.next().outVertex().property(GraphPropertiesDictionary.USERID.getProperty()).value()); + } Object resourceType = metadatObj.get(JsonPresentationFields.RESOURCE_TYPE.getPresentation()); if (resourceType != null) { catalogComponent.setResourceType((String) resourceType); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaOperationFacade.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaOperationFacade.java index 0d39bb264f..5b3aea0868 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaOperationFacade.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaOperationFacade.java @@ -37,6 +37,11 @@ import org.openecomp.sdc.be.datatypes.elements.*; import org.openecomp.sdc.be.datatypes.elements.MapInterfaceDataDefinition; import org.openecomp.sdc.be.datatypes.enums.*; import org.openecomp.sdc.be.model.*; +import org.openecomp.sdc.be.datatypes.elements.MapCapabilityProperty; +import org.openecomp.sdc.be.datatypes.elements.MapListCapabilityDataDefinition; +import org.openecomp.sdc.be.model.CatalogUpdateTimestamp; +import org.openecomp.sdc.be.datatypes.elements.MapCapabilityProperty; +import org.openecomp.sdc.be.datatypes.elements.MapListCapabilityDataDefinition; import org.openecomp.sdc.be.model.catalog.CatalogComponent; import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.TopologyTemplate; import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement; @@ -45,6 +50,7 @@ import org.openecomp.sdc.be.model.operations.StorageException; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; +import org.openecomp.sdc.be.model.utils.GroupUtils; import org.openecomp.sdc.be.resources.data.ComponentMetadataData; import org.openecomp.sdc.common.jsongraph.util.CommonUtility; import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum; @@ -408,12 +414,13 @@ public class ToscaOperationFacade { return nodeTemplateOperation.getFulfilledCapabilityByRelation(componentId, instanceId, relation, predicate); } - public StorageOperationStatus associateResourceInstances(String componentId, List<RequirementCapabilityRelDef> relations) { - Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> status = nodeTemplateOperation.associateResourceInstances(componentId, relations); - if (status.isRight()) { - return status.right().value(); + public Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> associateResourceInstances(Component component, String componentId, List<RequirementCapabilityRelDef> relations) { + Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> reqAndCapListEither = nodeTemplateOperation.associateResourceInstances(component, componentId, relations); + if (component != null) { + updateInstancesCapAndReqOnComponentFromDB(component); } - return StorageOperationStatus.OK; + return reqAndCapListEither; + } protected Either<Boolean, StorageOperationStatus> validateToscaResourceNameUniqueness(String name) { @@ -454,41 +461,38 @@ public class ToscaOperationFacade { Either<GraphVertex, JanusGraphOperationStatus> componentVEither = janusGraphDao .getVertexById(oldComponent.getUniqueId(), JsonParseFlagEnum.NoParse); if (componentVEither.isRight()) { - log.debug("Falied to fetch component {} error {}", oldComponent.getUniqueId(), componentVEither.right().value()); + log.debug("Failed to fetch component {} error {}", oldComponent.getUniqueId(), componentVEither.right().value()); return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(componentVEither.right().value())); } GraphVertex componentv = componentVEither.left().value(); - Either<GraphVertex, JanusGraphOperationStatus> parentVertexEither = janusGraphDao - .getParentVertex(componentv, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); + Either<GraphVertex, JanusGraphOperationStatus> parentVertexEither = janusGraphDao.getParentVertex(componentv, EdgeLabelEnum.VERSION, JsonParseFlagEnum.NoParse); if (parentVertexEither.isRight() && parentVertexEither.right().value() != JanusGraphOperationStatus.NOT_FOUND) { - log.debug("Falied to fetch parent version for component {} error {}", oldComponent.getUniqueId(), parentVertexEither.right().value()); + log.debug("Failed to fetch parent version for component {} error {}", oldComponent.getUniqueId(), parentVertexEither.right().value()); return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(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()); + log.debug("Failed to remove old component {} error {}", oldComponent.getUniqueId(), deleteToscaComponent.right().value()); return Either.right(deleteToscaComponent.right().value()); } Either<Resource, StorageOperationStatus> createToscaComponent = createToscaComponent(newComponent); if (createToscaComponent.isRight()) { - log.debug("Falied to create tosca element component {} error {}", newComponent.getUniqueId(), createToscaComponent.right().value()); + log.debug("Failed to create tosca element component {} error {}", newComponent.getUniqueId(), createToscaComponent.right().value()); return Either.right(createToscaComponent.right().value()); } Resource newElement = createToscaComponent.left().value(); Either<GraphVertex, JanusGraphOperationStatus> newVersionEither = janusGraphDao .getVertexById(newElement.getUniqueId(), JsonParseFlagEnum.NoParse); if (newVersionEither.isRight()) { - log.debug("Falied to fetch new tosca element component {} error {}", newComponent.getUniqueId(), newVersionEither.right().value()); + log.debug("Failed to fetch new tosca element component {} error {}", newComponent.getUniqueId(), newVersionEither.right().value()); return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(newVersionEither.right().value())); } if (parentVertexEither.isLeft()) { GraphVertex previousVersionV = parentVertexEither.left().value(); - JanusGraphOperationStatus - createEdge = janusGraphDao - .createEdge(previousVersionV, newVersionEither.left().value(), EdgeLabelEnum.VERSION, null); + JanusGraphOperationStatus createEdge = janusGraphDao.createEdge(previousVersionV, newVersionEither.left().value(), EdgeLabelEnum.VERSION, null); if (createEdge != JanusGraphOperationStatus.OK) { - log.debug("Falied to associate to previous version {} new version {} error {}", previousVersionV.getUniqueId(), newVersionEither.right().value(), createEdge); + log.debug("Failed to associate to previous version {} new version {} error {}", previousVersionV.getUniqueId(), newVersionEither.right().value(), createEdge); return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createEdge)); } } @@ -515,7 +519,7 @@ public class ToscaOperationFacade { } newComponent.setDeploymentArtifacts(depArtifacts); - newComponent.setGroups(oldComponent.getGroups()); + newComponent.setLastUpdateDate(null); newComponent.setHighestVersion(true); } @@ -731,7 +735,7 @@ public class ToscaOperationFacade { for (EdgeLabelEnum edgeLabelEnum : forbiddenEdgeLabelEnums) { Either<Edge, JanusGraphOperationStatus> belongingEdgeByCriteria = janusGraphDao .getBelongingEdgeByCriteria(elementV, edgeLabelEnum, null); - if (belongingEdgeByCriteria.isLeft()){ + if (belongingEdgeByCriteria.isLeft()) { log.debug("Marked element {} in use. don't delete it", elementV.getUniqueId()); isAllowedToDelete = false; break; @@ -803,9 +807,7 @@ public class ToscaOperationFacade { return result; } - public StorageOperationStatus associateComponentInstancesToComponent(Component containerComponent, Map<ComponentInstance, Resource> resourcesInstancesMap, boolean allowDeleted) { - - StorageOperationStatus result = null; + public void associateComponentInstancesToComponent(Component containerComponent, Map<ComponentInstance, Resource> resourcesInstancesMap, boolean allowDeleted, boolean isUpdateCsar) { CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Going to add component instances to component {}", containerComponent.getUniqueId()); Either<GraphVertex, JanusGraphOperationStatus> metadataVertex = janusGraphDao @@ -815,12 +817,13 @@ public class ToscaOperationFacade { if (status == JanusGraphOperationStatus.NOT_FOUND) { status = JanusGraphOperationStatus.INVALID_ID; } - result = DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status); + throw new StorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); } - if (result == null) { - result = nodeTemplateOperation.associateComponentInstancesToComponent(containerComponent, resourcesInstancesMap, metadataVertex.left().value(), allowDeleted); - } - return result; + + Map<String, ComponentInstanceDataDefinition> compnentInstancesMap = nodeTemplateOperation.associateComponentInstancesToComponent(containerComponent, resourcesInstancesMap, metadataVertex.left().value(), allowDeleted, isUpdateCsar); + + containerComponent.setComponentInstances(ModelConverter.getComponentInstancesFromMapObject(compnentInstancesMap, containerComponent)); + } public Either<ImmutablePair<Component, String>, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(Component containerComponent, Component origComponent, ComponentInstance componentInstance) { @@ -933,8 +936,8 @@ public class ToscaOperationFacade { return currCounter == null ? null : maxCounter; } - public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) { - return nodeTemplateOperation.associateResourceInstances(componentId, requirementDef); + public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(Component component, String componentId, RequirementCapabilityRelDef requirementDef) { + return nodeTemplateOperation.associateResourceInstances(component, componentId, requirementDef); } @@ -1390,12 +1393,11 @@ public class ToscaOperationFacade { return Optional.empty(); } - public StorageOperationStatus associateDeploymentArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts, String componentId, User user) { + public StorageOperationStatus associateDeploymentArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instDeploymentArtifacts, Component component, User user) { - Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao - .getVertexById(componentId, JsonParseFlagEnum.NoParse); + Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse); if (getVertexEither.isRight()) { - log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); + log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value()); return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()); } @@ -1413,17 +1415,15 @@ public class ToscaOperationFacade { instArtMap.put(entry.getKey(), artifactsMap); } } - + ModelConverter.setComponentInstancesDeploymentArtifactsToComponent(instArtMap, component); return topologyTemplateOperation.associateInstDeploymentArtifactsToComponent(vertex, instArtMap); - } - public StorageOperationStatus associateArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instArtifacts, String componentId) { + public StorageOperationStatus associateArtifactsToInstances(Map<String, Map<String, ArtifactDefinition>> instArtifacts, Component component) { - Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao - .getVertexById(componentId, JsonParseFlagEnum.NoParse); + Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse); if (getVertexEither.isRight()) { - log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); + log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value()); return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()); } @@ -1441,17 +1441,16 @@ public class ToscaOperationFacade { instArtMap.put(entry.getKey(), artifactsMap); } } - + ModelConverter.setComponentInstancesInformationalArtifactsToComponent(instArtMap, component); return topologyTemplateOperation.associateInstArtifactsToComponent(vertex, instArtMap); } - public StorageOperationStatus associateInstAttributeToComponentToInstances(Map<String, List<PropertyDefinition>> instArttributes, String componentId) { + public StorageOperationStatus associateInstAttributeToComponentToInstances(Map<String, List<PropertyDefinition>> instArttributes, Component component) { - Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao - .getVertexById(componentId, JsonParseFlagEnum.NoParse); + Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse); if (getVertexEither.isRight()) { - log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); + log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value()); return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()); } @@ -1467,17 +1466,24 @@ public class ToscaOperationFacade { instAttr.put(entry.getKey(), attributesMap); } } - + setComponentInstanceAttributesOnComponent(component, instAttr); return topologyTemplateOperation.associateInstAttributeToComponent(vertex, instAttr); } // endregion - public StorageOperationStatus associateOrAddCalculatedCapReq(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReg, String componentId) { - Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao - .getVertexById(componentId, JsonParseFlagEnum.NoParse); + private void setComponentInstanceAttributesOnComponent(Component resource, Map<String, MapPropertiesDataDefinition> instAttr) { + Map<String, List<ComponentInstanceProperty>> componentInstancesAttributes = resource.getComponentInstancesAttributes(); + if (componentInstancesAttributes == null) + componentInstancesAttributes = new HashMap<>(); + componentInstancesAttributes.putAll(ModelConverter.getComponentInstancesAttributes(instAttr)); + resource.setComponentInstancesAttributes(componentInstancesAttributes); + } + + public StorageOperationStatus associateOrAddCalculatedCapReq(Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties, Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReg, Component component) { + Either<GraphVertex, JanusGraphOperationStatus> getVertexEither = janusGraphDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse); if (getVertexEither.isRight()) { - log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); + log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, component.getUniqueId(), getVertexEither.right().value()); return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value()); } @@ -1516,13 +1522,32 @@ public class ToscaOperationFacade { mapToscaDataDefinition.put(instReq.getKey(), new ListRequirementDataDefinition(instReq.getValue().stream().map(RequirementDataDefinition::new).collect(Collectors.toList()))); } - MapListRequirementDataDefinition capMap = nodeTemplateOperation.prepareCalculatedRequirementForNodeType(mapToscaDataDefinition, new ComponentInstanceDataDefinition(entry.getKey())); + MapListRequirementDataDefinition reqMap = nodeTemplateOperation.prepareCalculatedRequirementForNodeType(mapToscaDataDefinition, new ComponentInstanceDataDefinition(entry.getKey())); - calcRequirements.put(entry.getKey().getUniqueId(), capMap); + String componentInstanceId = entry.getKey().getUniqueId(); + calcRequirements.put(componentInstanceId, reqMap); } } - return topologyTemplateOperation.associateOrAddCalcCapReqToComponent(vertex, calcRequirements, calcCapabilty, calculatedCapabilitiesProperties); + StorageOperationStatus storageOperationStatus = topologyTemplateOperation.associateOrAddCalcCapReqToComponent(vertex, calcRequirements, calcCapabilty, calculatedCapabilitiesProperties); + updateInstancesCapAndReqOnComponentFromDB(component); + return storageOperationStatus; + } + + private void updateInstancesCapAndReqOnComponentFromDB(Component component) { + ComponentParametersView componentParametersView = new ComponentParametersView(true); + componentParametersView.setIgnoreCapabilities(false); + componentParametersView.setIgnoreRequirements(false); + componentParametersView.setIgnoreCapabiltyProperties(false); + componentParametersView.setIgnoreComponentInstances(false); + Either<Component, StorageOperationStatus> componentEither = getToscaElement(component.getUniqueId(), componentParametersView); + if (componentEither.isRight()) { + throw new StorageException(StorageOperationStatus.NOT_FOUND); + } + Component updatedComponent = componentEither.left().value(); + component.setCapabilities(updatedComponent.getCapabilities()); + component.setRequirements(updatedComponent.getRequirements()); + component.setComponentInstances(updatedComponent.getComponentInstances()); } private Either<List<Service>, StorageOperationStatus> getLatestVersionNonCheckoutServicesMetadataOnly(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps) { @@ -1723,6 +1748,8 @@ public class ToscaOperationFacade { private void fillNodeTypePropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType) { switch (internalComponentType.toLowerCase()) { case "vf": + hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, Arrays.asList(ResourceTypeEnum.VFCMT.name())); + break; case "cvfc": hasNotProps.put(GraphPropertyEnum.RESOURCE_TYPE, Arrays.asList(ResourceTypeEnum.VFCMT.name(), ResourceTypeEnum.Configuration.name())); break; @@ -2449,7 +2476,7 @@ public class ToscaOperationFacade { } public Either<List<GroupDefinition>, StorageOperationStatus> updateGroupsOnComponent(Component component, List<GroupDataDefinition> updatedGroups) { - return groupsOperation.updateGroups(component, updatedGroups, true); + return groupsOperation.updateGroups(component, updatedGroups, PromoteVersionEnum.MINOR); } public Either<List<GroupInstance>, StorageOperationStatus> updateGroupInstancesOnComponent(Component component, String instanceId, List<GroupInstance> updatedGroupInstances) { @@ -2509,8 +2536,8 @@ public class ToscaOperationFacade { return topologyTemplateOperation.deleteToscaDataElements(containerComponent.getUniqueId(), EdgeLabelEnum.INPUTS, inputsToDelete.stream().map(PropertyDataDefinition::getName).collect(Collectors.toList())); } - public StorageOperationStatus updateComponentInstanceCapabiltyProperty(Component containerComponent, String componentInstanceUniqueId, String capabilityUniqueId, ComponentInstanceProperty property) { - return nodeTemplateOperation.updateComponentInstanceCapabilityProperty(containerComponent, componentInstanceUniqueId, capabilityUniqueId, property); + public StorageOperationStatus updateComponentInstanceCapabiltyProperty(Component containerComponent, String componentInstanceUniqueId, String capabilityPropertyKey, ComponentInstanceProperty property) { + return nodeTemplateOperation.updateComponentInstanceCapabilityProperty(containerComponent, componentInstanceUniqueId, capabilityPropertyKey, property); } public StorageOperationStatus updateComponentInstanceCapabilityProperties(Component containerComponent, String componentInstanceUniqueId) { @@ -2559,7 +2586,7 @@ public class ToscaOperationFacade { Either<ToscaElement, StorageOperationStatus> shouldUpdateDerivedVersion = nodeTypeOperation.shouldUpdateDerivedVersion(toscaElementToUpdate, nodeTypeV); if (shouldUpdateDerivedVersion.isRight() && StorageOperationStatus.OK != shouldUpdateDerivedVersion.right().value()) { log.debug("Failed to update derived version for node type {} derived {}, error: {}", componentId, clonedResource.getDerivedFrom().get(0), shouldUpdateDerivedVersion.right().value()); - return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value())); + return Either.right(shouldUpdateDerivedVersion.right().value()); } if (shouldUpdateDerivedVersion.isLeft()) { return Either.left(ModelConverter.convertFromToscaElement(shouldUpdateDerivedVersion.left().value())); @@ -2595,7 +2622,7 @@ public class ToscaOperationFacade { private Optional<MapCapabilityProperty> convertComponentInstanceProperties(Component component, String instanceId) { return component.fetchInstanceById(instanceId) - .map(ci -> ModelConverter.convertToMapOfMapCapabiltyProperties(ci.getCapabilities(), instanceId)); + .map(ci -> ModelConverter.convertToMapOfMapCapabilityProperties(ci.getCapabilities(), instanceId, ci.getOriginType().isAtomicType())); } public Either<PolicyDefinition, StorageOperationStatus> associatePolicyToComponent(String componentId, PolicyDefinition policyDefinition, int counter) { @@ -2630,7 +2657,7 @@ public class ToscaOperationFacade { DaoStatusConverter::convertJanusGraphStatusToStorageStatus); } - public Either<PolicyDefinition, StorageOperationStatus> updatePolicyOfComponent(String componentId, PolicyDefinition policyDefinition) { + public Either<PolicyDefinition, StorageOperationStatus> updatePolicyOfComponent(String componentId, PolicyDefinition policyDefinition, PromoteVersionEnum promoteVersionEnum) { Either<PolicyDefinition, StorageOperationStatus> result = null; Either<GraphVertex, JanusGraphOperationStatus> getVertexEither; getVertexEither = janusGraphDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); @@ -2639,6 +2666,7 @@ public class ToscaOperationFacade { result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value())); } if (result == null) { + policyDefinition.setVersion(GroupUtils.updateVersion(promoteVersionEnum, policyDefinition.getVersion())); StorageOperationStatus status = topologyTemplateOperation.updatePolicyOfToscaElement(getVertexEither.left().value(), policyDefinition); if (status != StorageOperationStatus.OK) { return Either.right(status); @@ -2685,7 +2713,36 @@ public class ToscaOperationFacade { DaoStatusConverter.convertJanusGraphStatusToStorageStatus(toe)); } - public void updateNamesOfCalculatedCapabilitiesRequirements(String componentId){ + public CatalogUpdateTimestamp updateCatalogTimes() { + long now = System.currentTimeMillis(); + + GraphVertex catalogRoot = janusGraphDao.getVertexByLabel(VertexTypeEnum.CATALOG_ROOT) + .left() + .on(this::onJanusGraphError); + + Long currentTime = (Long) catalogRoot.getMetadataProperty(GraphPropertyEnum.CURRENT_CATALOG_UPDATE_TIME); + catalogRoot.addMetadataProperty(GraphPropertyEnum.PREV_CATALOG_UPDATE_TIME, currentTime); + catalogRoot.addMetadataProperty(GraphPropertyEnum.CURRENT_CATALOG_UPDATE_TIME, now); + + janusGraphDao.updateVertex(catalogRoot).left().on(this::onJanusGraphError); + + return new CatalogUpdateTimestamp(currentTime, now); + } + + public CatalogUpdateTimestamp getCatalogTimes() { + + + GraphVertex catalogRoot = janusGraphDao.getVertexByLabel(VertexTypeEnum.CATALOG_ROOT) + .left() + .on(this::onJanusGraphError); + + Long currentTime = (Long) catalogRoot.getMetadataProperty(GraphPropertyEnum.CURRENT_CATALOG_UPDATE_TIME); + Long prevTime = (Long) catalogRoot.getMetadataProperty(GraphPropertyEnum.PREV_CATALOG_UPDATE_TIME); + + return new CatalogUpdateTimestamp(prevTime == null ? 0 : prevTime.longValue(), currentTime == null ? 0 : currentTime.longValue()); + } + + public void updateNamesOfCalculatedCapabilitiesRequirements(String componentId) { topologyTemplateOperation .updateNamesOfCalculatedCapabilitiesRequirements(componentId, getTopologyTemplate(componentId)); } @@ -2696,7 +2753,7 @@ public class ToscaOperationFacade { } private TopologyTemplate getTopologyTemplate(String componentId) { - return (TopologyTemplate)topologyTemplateOperation + return (TopologyTemplate) topologyTemplateOperation .getToscaElement(componentId, getFilterComponentWithCapProperties()) .left() .on(this::throwStorageException); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/UpgradeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/UpgradeOperation.java index 599dbc1995..b97afb64f0 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/UpgradeOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/UpgradeOperation.java @@ -101,7 +101,7 @@ public class UpgradeOperation extends BaseOperation { private StorageOperationStatus fillDependenciesByVertex(String componentId, List<ComponentDependency> dependencies, GraphVertex vertex) { StorageOperationStatus status = StorageOperationStatus.OK; - if ( needToAddToDepenedency(vertex) ) { + if ( needToAddToDependency(vertex) ) { ComponentDependency dependency = fillDataFromVertex(vertex, null, null); List<EdgeLabelEnum> dependList = Arrays.asList(EdgeLabelEnum.INSTANCE_OF, EdgeLabelEnum.PROXY_OF, EdgeLabelEnum.ALLOTTED_OF); @@ -118,22 +118,22 @@ public class UpgradeOperation extends BaseOperation { } return status; } - private boolean needToAddToDepenedency(GraphVertex vertex){ + + private boolean needToAddToDependency(GraphVertex vertex){ Boolean isDeleted = (Boolean) vertex.getMetadataProperty(GraphPropertyEnum.IS_DELETED); Boolean isArchived = (Boolean) vertex.getMetadataProperty(GraphPropertyEnum.IS_ARCHIVED); - return ( isDeleted == Boolean.TRUE || isArchived == Boolean.TRUE) ? false : true; + return !Boolean.TRUE.equals(isDeleted) && !Boolean.TRUE.equals(isArchived); } private StorageOperationStatus fillDependenciesByLabel(String componentId, GraphVertex vertex, ComponentDependency dependency, EdgeLabelEnum label) { - Either<List<GraphVertex>, JanusGraphOperationStatus> parentVertecies = janusGraphDao - .getParentVertecies(vertex, label, JsonParseFlagEnum.ParseAll); - if (parentVertecies.isRight() && parentVertecies.right().value() != JanusGraphOperationStatus.NOT_FOUND) { - log.debug("Failed to fetch parent verticies by label INSTANCE_OF for vertex with id {} error {}", componentId, parentVertecies.right().value()); - return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(parentVertecies.right().value()); + Either<List<GraphVertex>, JanusGraphOperationStatus> parentVertices = janusGraphDao.getParentVertices(vertex, label, JsonParseFlagEnum.ParseAll); + if (parentVertices.isRight() && parentVertices.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + log.debug("Failed to fetch parent verticies by label INSTANCE_OF for vertex with id {} error {}", componentId, parentVertices.right().value()); + return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(parentVertices.right().value()); } - if (parentVertecies.isLeft()) { + if (parentVertices.isLeft()) { List<ComponentDependency> existIn = new ArrayList<>( ); - parentVertecies.left().value().forEach(v -> handleHighestVersion(vertex, label, existIn, v) ); + parentVertices.left().value().forEach(v -> handleHighestVersion(vertex, label, existIn, v) ); dependency.addDependencies(existIn); } return StorageOperationStatus.OK; @@ -141,7 +141,7 @@ public class UpgradeOperation extends BaseOperation { private void handleHighestVersion(GraphVertex vertexOrigin, EdgeLabelEnum label, List<ComponentDependency> exisIn, GraphVertex containerVertex) { Boolean isHighest = (Boolean) containerVertex.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION); - if ( isHighest && needToAddToDepenedency(containerVertex) ) { + if ( isHighest && needToAddToDependency(containerVertex) ) { JanusGraphVertex janusGraphVertex = containerVertex.getVertex(); Iterator<Edge> edges = janusGraphVertex.edges(Direction.OUT, EdgeLabelEnum.VERSION.name()); //verify that it is a last version - highest by version number @@ -160,13 +160,12 @@ public class UpgradeOperation extends BaseOperation { } private boolean findAllottedChain(GraphVertex vertex, ComponentDependency container) { - Either<List<GraphVertex>, JanusGraphOperationStatus> parentVertecies = janusGraphDao - .getParentVertecies(vertex, EdgeLabelEnum.INSTANCE_OF, JsonParseFlagEnum.ParseAll); + Either<List<GraphVertex>, JanusGraphOperationStatus> parentVertecies = janusGraphDao.getParentVertices(vertex, EdgeLabelEnum.INSTANCE_OF, JsonParseFlagEnum.ParseAll); if (parentVertecies.isLeft()) { List<ComponentDependency> existIn = new ArrayList<>(); parentVertecies.left().value().forEach(v -> { Boolean isHighest = (Boolean) v.getMetadataProperty(GraphPropertyEnum.IS_HIGHEST_VERSION); - if ( isHighest && needToAddToDepenedency(v) ) { + if ( isHighest && needToAddToDependency(v) ) { JanusGraphVertex janusGraphVertex = v.getVertex(); Iterator<Edge> edges = janusGraphVertex.edges(Direction.OUT, EdgeLabelEnum.VERSION.name()); //verify that it is a last version - highest by version number diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/CapabilityRequirementNameResolver.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/CapabilityRequirementNameResolver.java index ed9c8f7d2e..225be207df 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/CapabilityRequirementNameResolver.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/CapabilityRequirementNameResolver.java @@ -24,16 +24,30 @@ import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; import org.openecomp.sdc.be.config.BeEcompErrorManager; -import org.openecomp.sdc.be.datatypes.elements.*; +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.MapCapabilityProperty; +import org.openecomp.sdc.be.datatypes.elements.MapListCapabilityDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.TopologyTemplate; import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement; import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElementTypeEnum; import org.openecomp.sdc.be.model.utils.ComponentUtilities; import org.openecomp.sdc.common.log.wrappers.Logger; -import java.util.*; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; import java.util.function.Function; import java.util.stream.Collectors; + import static org.apache.commons.collections.CollectionUtils.isNotEmpty; import static org.apache.commons.lang3.StringUtils.isBlank; @@ -42,11 +56,8 @@ public class CapabilityRequirementNameResolver { private static final Logger log = Logger.getLogger(CapabilityRequirementNameResolver.class); private static final String PATH_DELIMITER = "."; - private CapabilityRequirementNameResolver() { - } - public static void updateNamesOfCalculatedCapabilitiesRequirements(TopologyTemplate toscaElement, String ownerId, String ownerName, Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) { - Map<String, ToscaElement> componentCacheToRepair = new HashMap<>(); + Map<String,ToscaElement> componentCacheToRepair = new HashMap<>(); log.debug("#updateNamesOfCalculatedCapabilitiesRequirements"); updateCalculatedCapabilitiesNames(componentCacheToRepair, toscaElement, ownerId, ownerName, originGetter); updateCalculatedRequirementsNames(componentCacheToRepair, toscaElement, ownerId, ownerName, originGetter); @@ -54,12 +65,12 @@ public class CapabilityRequirementNameResolver { } private static void updateCalculatedCapabilitiesPropertiesKeys(TopologyTemplate toscaElement, String ownerId) { - if (calCapPropertiesExist(toscaElement, ownerId)) { - MapCapabilityProperty newProps = new MapCapabilityProperty(); + if(calCapPropertiesExist(toscaElement, ownerId)){ + MapCapabilityProperty newProps = new MapCapabilityProperty(); toscaElement.getCalculatedCapabilitiesProperties().get(ownerId) .getMapToscaDataDefinition() - .forEach((k, v) -> updateAndAddCalculatedCapabilitiesProperties(k, v, toscaElement.getCalculatedCapabilities().get(ownerId), newProps)); - if (MapUtils.isNotEmpty(newProps.getMapToscaDataDefinition())) { + .forEach((k, v)-> updateAndAddCalculatedCapabilitiesProperties(k, v, toscaElement.getCalculatedCapabilities().get(ownerId), newProps)); + if(MapUtils.isNotEmpty(newProps.getMapToscaDataDefinition())) { toscaElement.getCalculatedCapabilitiesProperties().put(ownerId, newProps); } } @@ -73,20 +84,20 @@ public class CapabilityRequirementNameResolver { } private static void updateCalculatedRequirementsNames(Map<String, ToscaElement> componentCacheToRepair, TopologyTemplate toscaElement, String ownerId, String ownerName, Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) { - if (requirementsExist(toscaElement, ownerId)) { + if(requirementsExist(toscaElement, ownerId)){ String prefix = ownerName + PATH_DELIMITER; repairReqNames(componentCacheToRepair, toscaElement, ownerId, originGetter); toscaElement.getCalculatedRequirements().get(ownerId) .getMapToscaDataDefinition().values().stream() .flatMap(l -> l.getListToscaDataDefinition().stream()) .forEach(r -> { - if (isRequiredToRepair(r.getName())) { + if(isRequiredToRepair(r.getName())){ BeEcompErrorManager.getInstance() .logBeComponentMissingError("The empty name of the requirement was found. Id: " + r.getUniqueId() + ", ownerId: " + ownerId + ", ownerName: " + ownerName, toscaElement.getComponentType().getValue(), toscaElement.getName()); } - if (ComponentUtilities.isNotUpdatedCapReqName(prefix, r.getName(), r.getPreviousName())) { - if (StringUtils.isNotEmpty(r.getPreviousName())) { + if(ComponentUtilities.isNotUpdatedCapReqName(prefix, r.getName(), r.getPreviousName())) { + if(StringUtils.isNotEmpty(r.getPreviousName())){ r.setParentName(r.getPreviousName()); } r.setPreviousName(r.getName()); @@ -103,20 +114,20 @@ public class CapabilityRequirementNameResolver { } private static void updateCalculatedCapabilitiesNames(Map<String, ToscaElement> componentCacheToRepair, TopologyTemplate toscaElement, String ownerId, String ownerName, Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) { - if (capabilitiesExist(toscaElement, ownerId)) { + if(capabilitiesExist(toscaElement, ownerId)){ String prefix = ownerName + PATH_DELIMITER; repairCapNames(componentCacheToRepair, toscaElement, ownerId, originGetter); toscaElement.getCalculatedCapabilities().get(ownerId) .getMapToscaDataDefinition().values().stream() .flatMap(l -> l.getListToscaDataDefinition().stream()) .forEach(c -> { - if (isRequiredToRepair(c.getName())) { + if(isRequiredToRepair(c.getName())){ BeEcompErrorManager.getInstance() .logBeComponentMissingError("The empty name of the capability was found. Id: " + c.getUniqueId() + ", ownerId: " + ownerId + ", ownerName: " + ownerName, toscaElement.getComponentType().getValue(), toscaElement.getName()); } - if (ComponentUtilities.isNotUpdatedCapReqName(prefix, c.getName(), c.getPreviousName())) { - if (StringUtils.isNotEmpty(c.getPreviousName())) { + if(ComponentUtilities.isNotUpdatedCapReqName(prefix, c.getName(), c.getPreviousName())) { + if(StringUtils.isNotEmpty(c.getPreviousName())){ c.setParentName(c.getPreviousName()); } c.setPreviousName(c.getName()); @@ -146,13 +157,13 @@ public class CapabilityRequirementNameResolver { ComponentInstanceDataDefinition instance = toscaElement.getComponentInstances() != null ? toscaElement.getComponentInstances().get(ownerId) : null; - if (instance != null && emptyNameFound) { + if(instance != null && emptyNameFound){ log.debug("#repairCapNames - Going to repair the name of the capability for the owner {}. ", ownerId); toscaElement.getCalculatedCapabilities().get(ownerId) .getMapToscaDataDefinition().values() .stream() .flatMap(l -> l.getListToscaDataDefinition().stream()) - .forEach(c -> repairCapName(componentCacheToRepair, instance, c, originGetter)); + .forEach(c-> repairCapName(componentCacheToRepair, instance, c, originGetter)); } } @@ -170,18 +181,18 @@ public class CapabilityRequirementNameResolver { ComponentInstanceDataDefinition instance = toscaElement.getComponentInstances() != null ? toscaElement.getComponentInstances().get(ownerId) : null; - if (instance != null && emptyNameFound) { + if(instance != null && emptyNameFound){ log.debug("#repairReqNames - Going to repair the name of the requirement for the owner {}. ", ownerId); toscaElement.getCalculatedRequirements().get(ownerId) .getMapToscaDataDefinition().values() .stream() .flatMap(l -> l.getListToscaDataDefinition().stream()) - .forEach(r -> repairReqName(componentCacheToRepair, instance, r, originGetter)); + .forEach(r-> repairReqName(componentCacheToRepair, instance, r, originGetter)); } } private static void repairCapName(Map<String, ToscaElement> componentCacheToRepair, ComponentInstanceDataDefinition instance, CapabilityDataDefinition capability, Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) { - if (isRequiredToRepair(capability.getName())) { + if(isRequiredToRepair(capability.getName())){ log.debug("#repairTopologyTemplateCapName - Going to build the name for the capability: ", capability.getUniqueId()); buildSetCapName(componentCacheToRepair, capability, instance, originGetter); } @@ -189,16 +200,16 @@ public class CapabilityRequirementNameResolver { private static boolean isRequiredToRepair(String name) { boolean isRequiredToRepair = StringUtils.isEmpty(name) || name.endsWith(".null") || name.contains(".null."); - if (isRequiredToRepair) { - log.debug("#isRequiredToRepair - The name {} should be repaired. ", name); - } else { - log.debug("#isRequiredToRepair - The name {} should not be repaired. ", name); + if(isRequiredToRepair){ + log.debug("#isRequiredToRepair - The name {} should be repaired. ", name) ; + } else{ + log.debug("#isRequiredToRepair - The name {} should not be repaired. ", name) ; } return isRequiredToRepair; } private static void repairReqName(Map<String, ToscaElement> componentCacheToRepair, ComponentInstanceDataDefinition instance, RequirementDataDefinition requirement, Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) { - if (isRequiredToRepair(requirement.getName())) { + if(isRequiredToRepair(requirement.getName())){ log.debug("#repairTopologyTemplateCapName - Going to build the name for the requirement: ", requirement.getUniqueId()); buildSetReqName(componentCacheToRepair, requirement, instance, originGetter); } @@ -210,14 +221,14 @@ public class CapabilityRequirementNameResolver { String capName = key[key.length - 1]; Optional<CapabilityDataDefinition> foundCapOpt = calculatedCapabilities.getMapToscaDataDefinition().get(capType) .getListToscaDataDefinition().stream() - .filter(c -> StringUtils.isNotEmpty(c.getPreviousName()) && c.getPreviousName().equals(capName)) + .filter(c -> StringUtils.isNotEmpty(c.getPreviousName())&& c.getPreviousName().equals(capName)) .findFirst(); foundCapOpt.ifPresent(capabilityDataDefinition -> key[key.length - 1] = capabilityDataDefinition.getName()); - newProps.put(buildCaLCapPropKey(key), properties); + newProps.put(buildCaLCapPropKey(key),properties); } public static void revertNamesOfCalculatedCapabilitiesRequirements(TopologyTemplate toscaElement, String ownerId, Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) { - Map<String, ToscaElement> componentCacheToRepair = new HashMap<>(); + Map<String,ToscaElement> componentCacheToRepair = new HashMap<>(); log.debug("#revertNamesOfCalculatedCapabilitiesRequirements"); revertCalculatedCapabilitiesPropertiesKeys(componentCacheToRepair, toscaElement, ownerId, originGetter); revertCalculatedCapabilitiesNames(toscaElement, ownerId); @@ -226,12 +237,12 @@ public class CapabilityRequirementNameResolver { private static void revertCalculatedCapabilitiesPropertiesKeys(Map<String, ToscaElement> componentCacheToRepair, TopologyTemplate toscaElement, String ownerId, Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) { repairCapNames(componentCacheToRepair, toscaElement, ownerId, originGetter); - if (calCapPropertiesExist(toscaElement, ownerId)) { - MapCapabilityProperty newProps = new MapCapabilityProperty(); + if(calCapPropertiesExist(toscaElement, ownerId)){ + MapCapabilityProperty newProps = new MapCapabilityProperty(); toscaElement.getCalculatedCapabilitiesProperties().get(ownerId) .getMapToscaDataDefinition() - .forEach((k, v) -> revertAndAddCalculatedCapabilitiesProperties(k, v, toscaElement.getCalculatedCapabilities().get(ownerId), newProps)); - if (MapUtils.isNotEmpty(newProps.getMapToscaDataDefinition())) { + .forEach((k,v) -> revertAndAddCalculatedCapabilitiesProperties(k, v, toscaElement.getCalculatedCapabilities().get(ownerId), newProps)); + if(MapUtils.isNotEmpty(newProps.getMapToscaDataDefinition())) { toscaElement.getCalculatedCapabilitiesProperties().put(ownerId, newProps); } } @@ -239,7 +250,7 @@ public class CapabilityRequirementNameResolver { private static void revertCalculatedRequirementsNames(Map<String, ToscaElement> componentCacheToRepair, TopologyTemplate toscaElement, String ownerId, Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) { repairReqNames(componentCacheToRepair, toscaElement, ownerId, originGetter); - if (requirementsExist(toscaElement, ownerId)) { + if(requirementsExist(toscaElement, ownerId)){ toscaElement.getCalculatedRequirements().get(ownerId) .getMapToscaDataDefinition().values().stream() .flatMap(l -> l.getListToscaDataDefinition().stream()) @@ -248,14 +259,14 @@ public class CapabilityRequirementNameResolver { } private static void revertReqNames(RequirementDataDefinition requirement) { - if (StringUtils.isNotEmpty(requirement.getPreviousName())) { + if(StringUtils.isNotEmpty(requirement.getPreviousName())) { requirement.setName(requirement.getPreviousName()); requirement.setPreviousName(requirement.getParentName()); } } private static void revertCalculatedCapabilitiesNames(TopologyTemplate toscaElement, String ownerId) { - if (capabilitiesExist(toscaElement, ownerId)) { + if(capabilitiesExist(toscaElement, ownerId)){ toscaElement.getCalculatedCapabilities().get(ownerId) .getMapToscaDataDefinition().values().stream() .flatMap(l -> l.getListToscaDataDefinition().stream()) @@ -264,7 +275,7 @@ public class CapabilityRequirementNameResolver { } private static void revertCapNames(CapabilityDataDefinition capability) { - if (StringUtils.isNotEmpty(capability.getPreviousName())) { + if(StringUtils.isNotEmpty(capability.getPreviousName())) { capability.setName(capability.getPreviousName()); capability.setPreviousName(capability.getParentName()); } @@ -284,9 +295,9 @@ public class CapabilityRequirementNameResolver { private static String buildCaLCapPropKey(String[] keyArray) { StringBuilder key = new StringBuilder(); - for (int i = 0; i < keyArray.length; ++i) { + for(int i = 0; i< keyArray.length; ++i){ key.append(keyArray[i]); - if (i < keyArray.length - 1) { + if(i < keyArray.length - 1){ key.append(ModelConverter.CAP_PROP_DELIM); } } @@ -294,52 +305,52 @@ public class CapabilityRequirementNameResolver { } private static void buildSetCapName(Map<String, ToscaElement> componentsCache, CapabilityDataDefinition capability, ComponentInstanceDataDefinition instance, Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) { - List<String> reducedPath = capability.getOwnerId() != null ? getReducedPathByOwner(capability.getPath(), capability.getOwnerId()) : getReducedPath(capability.getPath()); + List<String> reducedPath = capability.getOwnerId() !=null ? getReducedPathByOwner(capability.getPath() , capability.getOwnerId() ) : getReducedPath(capability.getPath()) ; log.debug("reducedPath for ownerId {}, reducedPath {} ", capability.getOwnerId(), reducedPath); reducedPath.remove(reducedPath.size() - 1); ToscaElement originComponent = getOriginComponent(componentsCache, instance, originGetter); - String name = isRequiredToRepair(capability.getParentName()) ? + String name = isRequiredToRepair(capability.getParentName()) ? extractNameFromUniqueId(capability.getUniqueId()) : capability.getParentName(); StringBuilder repairedName = buildSubstitutedName(componentsCache, originComponent, reducedPath, originGetter); log.debug("#buildSetCapName - The name for the capability was built: {}", repairedName); capability.setName(repairedName.append(name).toString()); - if (isRequiredToRepair(capability.getPreviousName())) { + if(isRequiredToRepair(capability.getPreviousName())){ capability.setPreviousName(capability.getName().substring(capability.getName().indexOf(PATH_DELIMITER) + 1)); } - if (isRequiredToRepair(capability.getParentName())) { + if(isRequiredToRepair(capability.getParentName())){ capability.setParentName(name); } } private static void buildSetReqName(Map<String, ToscaElement> componentsCache, RequirementDataDefinition requirement, ComponentInstanceDataDefinition instance, Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) { - List<String> reducedPath = requirement.getOwnerId() != null ? getReducedPathByOwner(requirement.getPath(), requirement.getOwnerId()) : getReducedPath(requirement.getPath()); + List<String> reducedPath = requirement.getOwnerId() !=null ? getReducedPathByOwner(requirement.getPath() , requirement.getOwnerId() ) : getReducedPath(requirement.getPath()) ; log.debug("reducedPath for ownerId {}, reducedPath {} ", requirement.getOwnerId(), reducedPath); reducedPath.remove(reducedPath.size() - 1); ToscaElement originComponent = getOriginComponent(componentsCache, instance, originGetter); - String name = isRequiredToRepair(requirement.getParentName()) ? + String name = isRequiredToRepair(requirement.getParentName()) ? extractNameFromUniqueId(requirement.getUniqueId()) : requirement.getParentName(); StringBuilder repairedName = buildSubstitutedName(componentsCache, originComponent, reducedPath, originGetter); log.debug("#buildSetReqName - The name for the capability was built: ", repairedName); requirement.setName(repairedName.append(name).toString()); - if (isRequiredToRepair(requirement.getPreviousName())) { + if(isRequiredToRepair(requirement.getPreviousName())){ requirement.setPreviousName(requirement.getName().substring(requirement.getName().indexOf(PATH_DELIMITER) + 1)); } - if (isRequiredToRepair(requirement.getParentName())) { + if(isRequiredToRepair(requirement.getParentName())){ requirement.setParentName(name); } } private static String extractNameFromUniqueId(String uniqueId) { String[] uid = uniqueId.split("\\."); - return uid[uid.length - 1]; + return uid [uid.length - 1]; } private static StringBuilder buildSubstitutedName(Map<String, ToscaElement> componentsCache, ToscaElement originComponent, List<String> path, Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) { StringBuilder substitutedName = new StringBuilder(); log.debug("#buildSubstitutedName"); - if (isNotEmpty(path) && isTopologyTemplateNotCvfc(originComponent)) { + if(isNotEmpty(path) && isTopologyTemplateNotCvfc(originComponent)){ log.debug("#buildSubstitutedName"); List<String> reducedPath = getReducedPath(path); Collections.reverse(reducedPath); @@ -353,7 +364,7 @@ public class CapabilityRequirementNameResolver { } private static ToscaElement getOriginComponent(Map<String, ToscaElement> componentsCache, ComponentInstanceDataDefinition instance, Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) { - if (componentsCache.containsKey(getActualComponentUid(instance))) { + if(componentsCache.containsKey(getActualComponentUid(instance))){ return componentsCache.get(getActualComponentUid(instance)); } ToscaElement origin = originGetter.apply(instance); @@ -371,17 +382,17 @@ public class CapabilityRequirementNameResolver { private static void appendNameRecursively(Map<String, ToscaElement> componentsCache, ToscaElement originComponent, Iterator<String> instanceIdIter, StringBuilder substitutedName, Function<ComponentInstanceDataDefinition, ToscaElement> originGetter) { log.debug("#appendNameRecursively"); - if (isTopologyTemplateNotCvfc(originComponent) - && MapUtils.isNotEmpty(((TopologyTemplate) originComponent).getComponentInstances()) && instanceIdIter.hasNext()) { + if(isTopologyTemplateNotCvfc(originComponent) + && MapUtils.isNotEmpty(((TopologyTemplate)originComponent).getComponentInstances()) && instanceIdIter.hasNext()){ String ownerId = instanceIdIter.next(); - Optional<ComponentInstanceDataDefinition> instanceOpt = ((TopologyTemplate) originComponent).getComponentInstances().values().stream().filter(i -> i.getUniqueId().equals(ownerId)).findFirst(); - if (instanceOpt.isPresent()) { + Optional<ComponentInstanceDataDefinition> instanceOpt = ((TopologyTemplate)originComponent).getComponentInstances().values().stream().filter(i -> i.getUniqueId().equals(ownerId)).findFirst(); + if(instanceOpt.isPresent()){ substitutedName.append(instanceOpt.get().getNormalizedName()).append(PATH_DELIMITER); ToscaElement getOriginRes = getOriginComponent(componentsCache, instanceOpt.get(), originGetter); appendNameRecursively(componentsCache, getOriginRes, instanceIdIter, substitutedName, originGetter); - } else if (MapUtils.isNotEmpty(((TopologyTemplate) originComponent).getGroups())) { - Optional<GroupDataDefinition> groupOpt = ((TopologyTemplate) originComponent).getGroups().values().stream().filter(g -> g.getUniqueId().equals(ownerId)).findFirst(); + } else if(MapUtils.isNotEmpty(((TopologyTemplate)originComponent).getGroups())){ + Optional<GroupDataDefinition> groupOpt = ((TopologyTemplate)originComponent).getGroups().values().stream().filter(g -> g.getUniqueId().equals(ownerId)).findFirst(); groupOpt.ifPresent(groupDataDefinition -> substitutedName.append(groupDataDefinition.getName()).append(PATH_DELIMITER)); } else { log.debug("Failed to find an capability owner with uniqueId {} on a component with uniqueId {}", ownerId, originComponent.getUniqueId()); @@ -389,24 +400,23 @@ public class CapabilityRequirementNameResolver { } } - private static List<String> getReducedPathByOwner(List<String> path, String ownerId) { + private static List<String> getReducedPathByOwner(List<String> path , String ownerId) { log.debug("ownerId {}, path {} ", ownerId, path); - if (CollectionUtils.isEmpty(path)) { + if ( CollectionUtils.isEmpty(path) ){ log.debug("cannot perform reduce by owner, path to component is empty"); return path; } - if (isBlank(ownerId)) { + if ( isBlank(ownerId) ){ log.debug("cannot perform reduce by owner, component owner is empty"); return path; } //reduce by owner - Map map = path.stream().collect(Collectors.toMap(it -> dropLast(it, PATH_DELIMITER), Function.identity(), (a, b) -> a.endsWith(ownerId) ? a : b)); + Map map = path.stream().collect( Collectors.toMap( it -> dropLast(it, PATH_DELIMITER) , Function.identity() , (a , b ) -> a.endsWith(ownerId) ? a : b )); //reduce list&duplicates and preserve order - return path.stream().distinct().filter(it -> map.values().contains(it)).collect(Collectors.toList()); + return path.stream().distinct().filter(it -> map.values().contains(it) ).collect(Collectors.toList()); } - - private static String dropLast(String path, String delimiter) { - if (isBlank(path) || isBlank(delimiter)) { + private static String dropLast( String path, String delimiter ) { + if (isBlank(path) || isBlank(delimiter)){ return path; } return path.substring(0, path.lastIndexOf(delimiter)); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/ModelConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/ModelConverter.java index 189599bd4b..39d3548279 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/ModelConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/ModelConverter.java @@ -27,11 +27,18 @@ import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.BooleanUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ReflectionToStringBuilder; +import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionaryExtractor; +import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition; +import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; +import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.elements.*; import org.openecomp.sdc.be.datatypes.elements.MapInterfaceDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.CreatedFrom; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFieldsExtractor; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.model.*; @@ -40,12 +47,18 @@ import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.TopologyTemplate; import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement; import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElementTypeEnum; import org.openecomp.sdc.be.model.jsonjanusgraph.enums.JsonConstantKeysEnum; +import org.openecomp.sdc.be.model.operations.StorageException; 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.openecomp.sdc.common.log.wrappers.Logger; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + import java.util.*; import java.util.Map.Entry; import java.util.function.Function; @@ -195,8 +208,7 @@ public class ModelConverter { resource.setCsarUUID((String) topologyTemplate.getMetadataValue(JsonPresentationFields.CSAR_UUID)); resource.setCsarVersion((String) topologyTemplate.getMetadataValue(JsonPresentationFields.CSAR_VERSION)); resource.setImportedToscaChecksum((String) topologyTemplate.getMetadataValue(JsonPresentationFields.IMPORTED_TOSCA_CHECKSUM)); - convertInterfaces(topologyTemplate, resource); - + convertInterfaces(topologyTemplate, resource); } convertComponentInstances(topologyTemplate, resource); convertRelations(topologyTemplate, resource); @@ -217,14 +229,14 @@ public class ModelConverter { } private static void convertInterfaces(TopologyTemplate toscaElement, Resource resource) { - Map<String, InterfaceDataDefinition> interfaces = toscaElement.getInterfaces(); - Map<String, InterfaceDefinition> copy; - if (interfaces != null) { - copy = interfaces.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new InterfaceDefinition(e.getValue()))); - } else { - copy = new HashMap<>(); - } - resource.setInterfaces(copy); + Map<String, InterfaceDataDefinition> interfaces = toscaElement.getInterfaces(); + Map<String, InterfaceDefinition> copy; + if (interfaces != null) { + copy = interfaces.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new InterfaceDefinition(e.getValue()))); + } else { + copy = new HashMap<>(); + } + resource.setInterfaces(copy); } private static void convertServiceInterfaces(TopologyTemplate toscaElement, Service service) { @@ -293,30 +305,39 @@ public class ModelConverter { Map<String, MapArtifactDataDefinition> instDeploymentArtifacts = topologyTemplate.getInstDeploymentArtifacts(); Map<String, MapArtifactDataDefinition> instanceArtifacts = topologyTemplate.getInstanceArtifacts(); + setComponentInstancesDeploymentArtifactsToComponent(instDeploymentArtifacts, component); + setComponentInstancesInformationalArtifactsToComponent(instanceArtifacts, component); + + } + + public static void setComponentInstancesInformationalArtifactsToComponent(Map<String, MapArtifactDataDefinition> instanceArtifacts, Component component) { List<ComponentInstance> instances = component.getComponentInstances(); - if (instDeploymentArtifacts != null && instances != null) { - instDeploymentArtifacts.entrySet().forEach(e -> { + 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().setDeploymentArtifacts(deplArt); + ci.get().setArtifacts(deplArt); } }); } - if (instanceArtifacts != null && instances != null) { - instanceArtifacts.entrySet().forEach(e -> { + } + + public static void setComponentInstancesDeploymentArtifactsToComponent(Map<String, MapArtifactDataDefinition> instDeploymentArtifacts, Component component) { + 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().setArtifacts(deplArt); + ci.get().setDeploymentArtifacts(deplArt); } }); } - } public static void convertComponentInstances(Component component, TopologyTemplate topologyTemplate) { @@ -404,7 +425,7 @@ public class ModelConverter { requirementCapabilityRelDef.setRequirement(p.getRelation().getRequirement()); requirementCapabilityRelDef.setType(p.getRelation().getRelationship().getType()); requirementCapabilityRelDef.setCapability(p.getRelation().getCapability()); - + requirementCapabilityRelDef.setOriginUI(relation.isOriginUI()); relationsList.add(requirementCapabilityRelDef); }); @@ -517,18 +538,55 @@ public class ModelConverter { return component.getCapabilities() != null && component.getComponentInstances() != null && component.getComponentInstances() .stream() - .filter(ci->MapUtils.isNotEmpty(ci.getCapabilities())) - .findFirst() - .isPresent(); + .anyMatch(ci->MapUtils.isNotEmpty(ci.getCapabilities())); } private static boolean groupsCapabilitiesExist(Component component) { return component.getCapabilities() != null && component.getGroups() != null && component.getGroups() .stream() - .filter(g->MapUtils.isNotEmpty(g.getCapabilities())) - .findFirst() - .isPresent(); + .anyMatch(g->MapUtils.isNotEmpty(g.getCapabilities())); + } + + public static MapCapabilityProperty convertToMapOfMapCapabilityProperties(Map<String, List<CapabilityDefinition>> capabilities, String ownerId, boolean isAtomicType) { + + Map<String, MapPropertiesDataDefinition> toscaCapPropMap = new HashMap<>(); + if(MapUtils.isNotEmpty(capabilities)){ + capabilities.forEach((s, caps)-> addCapsProperties(ownerId, isAtomicType, toscaCapPropMap, caps)); + } + return new MapCapabilityProperty(toscaCapPropMap); } + + private static void addCapsProperties(String ownerId, boolean isAtomicType, Map<String, MapPropertiesDataDefinition> toscaCapPropMap, List<CapabilityDefinition> caps) { + if (CollectionUtils.isNotEmpty(caps)) { + caps.forEach(cap -> addCapProperties(ownerId, isAtomicType, toscaCapPropMap, cap)); + } + } + + private static void addCapProperties(String ownerId, boolean isAtomicType, Map<String, MapPropertiesDataDefinition> toscaCapPropMap, CapabilityDefinition cap) { + if (CollectionUtils.isNotEmpty(cap.getProperties())) { + MapPropertiesDataDefinition dataToCreate = new MapPropertiesDataDefinition(cap.getProperties() + .stream() + .map(PropertyDataDefinition::new) + .collect(Collectors.toMap(PropertyDataDefinition::getName, p -> p))); + toscaCapPropMap.put(buildCapabilityPropertyKey(isAtomicType, cap.getType(),cap.getName(),ownerId, cap), + new MapPropertiesDataDefinition(dataToCreate)); + } + } + + public static String buildCapabilityPropertyKey(boolean isAtomicType, String capabilityType, String capabilityName, String componentInstanceUniqueId, CapabilityDefinition cap) { + StringBuilder sb = new StringBuilder(componentInstanceUniqueId); + sb.append(CAP_PROP_DELIM) + .append(cap.getOwnerId()) + .append(CAP_PROP_DELIM); + if(!isAtomicType && !componentInstanceUniqueId.equals(cap.getOwnerId())){ + sb.append(cap.getOwnerId()) + .append(CAP_PROP_DELIM); + } + return sb.append(capabilityType) + .append(CAP_PROP_DELIM) + .append(capabilityName).toString(); + } + public static MapCapabilityProperty convertToMapOfMapCapabiltyProperties(Map<String, List<CapabilityDefinition>> instCapabilities, String ownerId) { return convertToMapOfMapCapabiltyProperties(instCapabilities, ownerId, false); } @@ -668,6 +726,11 @@ public class ModelConverter { } else { service.setServiceRole(""); } + if (((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_FUNCTION)) != null){ + service.setServiceFunction((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_FUNCTION)); + } else { + service.setServiceFunction(""); + } } component.setConformanceLevel((String) toscaElement.getMetadataValue(JsonPresentationFields.CONFORMANCE_LEVEL)); component.setIcon((String) toscaElement.getMetadataValue(JsonPresentationFields.ICON)); @@ -875,44 +938,47 @@ public class ModelConverter { Map<String, ListCapabilityDataDefinition> toscaCapabilities = toscaElement.getCapabilities(); Map<String, MapPropertiesDataDefinition> toscaCapPropMap = toscaElement.getCapabilitiesProperties(); + Map<String, List<CapabilityDefinition>> capabilitiesMapFromMapObject = getCapabilitiesMapFromMapObject(toscaCapabilities, toscaCapPropMap); + if (capabilitiesMapFromMapObject != null) { + component.setCapabilities(capabilitiesMapFromMapObject); + } + } + + public static Map<String, List<CapabilityDefinition>> getCapabilitiesMapFromMapObject(Map<String, ListCapabilityDataDefinition> toscaCapabilities, Map<String, MapPropertiesDataDefinition> toscaCapPropMap) { Map<String, List<CapabilityDefinition>> compCap = new HashMap<>(); if (toscaCapabilities == null || toscaCapabilities.isEmpty()) - return; - toscaCapabilities.forEach((s, cap)-> { + return null; + toscaCapabilities.forEach((s, cap)-> { - if (cap != null) { - List<CapabilityDataDefinition> capDataList = cap.getListToscaDataDefinition(); + if (cap != null) { + List<CapabilityDataDefinition> capDataList = cap.getListToscaDataDefinition(); - if (capDataList != null && !capDataList.isEmpty()) { - List<CapabilityDefinition> capList = capDataList.stream().map(CapabilityDefinition::new).collect(Collectors.toList()); - compCap.put(s, capList); + if (capDataList != null && !capDataList.isEmpty()) { + List<CapabilityDefinition> capList = capDataList.stream().map(CapabilityDefinition::new).collect(Collectors.toList()); + compCap.put(s, capList); + } } - } - } - ); + } + ); if (toscaCapPropMap != null && !toscaCapPropMap.isEmpty()) { - toscaCapPropMap.forEach((s, capProp)-> { - String[] result = s.split(CAP_PROP_DELIM); - if (capProp != null) { - Map<String, PropertyDataDefinition> capMap = capProp.getMapToscaDataDefinition(); - - if (capMap != null && !capMap.isEmpty()) { - List<ComponentInstanceProperty> capPropsList = capMap.values().stream().map(ComponentInstanceProperty::new).collect(Collectors.toList()); - - List<CapabilityDefinition> cap = compCap.get(result[0]); - Optional<CapabilityDefinition> op = cap.stream().filter(c -> c.getName().equals(result[1])).findFirst(); - if (op.isPresent()) { - op.get().setProperties(capPropsList); + toscaCapPropMap.forEach((s, capProp)-> { + String[] result = s.split(CAP_PROP_DELIM); + if (capProp != null) { + Map<String, PropertyDataDefinition> capMap = capProp.getMapToscaDataDefinition(); + + if (capMap != null && !capMap.isEmpty()) { + List<ComponentInstanceProperty> capPropsList = capMap.values().stream().map(ComponentInstanceProperty::new).collect(Collectors.toList()); + + List<CapabilityDefinition> cap = compCap.get(result[0]); + Optional<CapabilityDefinition> op = cap.stream().filter(c -> c.getName().equals(result[1])).findFirst(); + op.ifPresent(capabilityDefinition -> capabilityDefinition.setProperties(capPropsList)); } } } - } - ); + ); } - - component.setCapabilities(compCap); - + return compCap; } private static void convertGroups(TopologyTemplate toscaElement, Component component) { @@ -938,7 +1004,7 @@ public class ModelConverter { Map<String, GroupDataDefinition> groups = new HashMap<>(); if (groupDefinitions != null && groups.isEmpty()) { - groups = groupDefinitions.stream().collect(Collectors.toMap(GroupDefinition::getName, GroupDefinition::new)); + groups = groupDefinitions.stream().collect(Collectors.toMap(GroupDefinition::getInvariantName, GroupDefinition::new)); } toscaElement.setGroups(groups); } @@ -1019,7 +1085,7 @@ public class ModelConverter { Map<String, InterfaceDefinition> interfaces = service.getInterfaces(); if (interfaces != null && !interfaces.isEmpty()) { Map<String, InterfaceDataDefinition> copy = interfaces.entrySet().stream() - .collect(Collectors.toMap(Map.Entry::getKey, e -> new InterfaceDataDefinition(e.getValue()))); + .collect(Collectors.toMap(Map.Entry::getKey, e -> new InterfaceDataDefinition(e.getValue()))); topologyTemplate.setInterfaces(copy); } } @@ -1028,7 +1094,7 @@ public class ModelConverter { convertServiceMetaData(service, topologyTemplate); convertServiceApiArtifacts(service, topologyTemplate); convertServicePaths(service,topologyTemplate); - convertServiceInterfaces(service, topologyTemplate); + convertServiceInterfaces(topologyTemplate,service); } private static void convertServicePaths(Service service, TopologyTemplate topologyTemplate) { @@ -1182,6 +1248,11 @@ public class ModelConverter { } else { toscaElement.setMetadataValue(JsonPresentationFields.SERVICE_ROLE, ""); } + if (((Service) component).getServiceFunction() != null){ + toscaElement.setMetadataValue(JsonPresentationFields.SERVICE_FUNCTION, ((Service) component).getServiceFunction()); + } else { + toscaElement.setMetadataValue(JsonPresentationFields.SERVICE_FUNCTION, ""); + } } toscaElement.setMetadataValue(JsonPresentationFields.CONFORMANCE_LEVEL, component.getConformanceLevel()); toscaElement.setMetadataValue(JsonPresentationFields.IS_DELETED, component.getIsDeleted()); @@ -1208,6 +1279,7 @@ public class ModelConverter { List<GroupInstance> groupInstances = topologyTemplate.getInstGroups().get(key).getMapToscaDataDefinition().entrySet().stream().map(e -> new GroupInstance(e.getValue())).collect(Collectors.toList()); currComponentInstance.setGroupInstances(groupInstances); } + setComponentInstanceSource(currComponentInstance, component); if(nodeFilterComponents != null && nodeFilterComponents.containsKey(key)){ currComponentInstance.setNodeFilter(nodeFilterComponents.get(key)); } @@ -1229,6 +1301,36 @@ public class ModelConverter { component.setComponentInstances(componentInstances); } + public static List<ComponentInstance> getComponentInstancesFromMapObject(Map<String, ComponentInstanceDataDefinition> componentInstancesDefinitionMap, Component component) { + List<ComponentInstance> componentInstances = new ArrayList<>(); + ComponentInstance currComponentInstance; + for (Map.Entry<String, ComponentInstanceDataDefinition> entry : componentInstancesDefinitionMap.entrySet()) { + String key = entry.getKey(); + currComponentInstance = new ComponentInstance(componentInstancesDefinitionMap.get(key)); + setComponentInstanceSource(currComponentInstance, component); + componentInstances.add(currComponentInstance); + } + return componentInstances; + } + + private static void setComponentInstanceSource(ComponentInstance currComponentInstance, Component component) { + if (Objects.isNull(currComponentInstance.getCreatedFrom())){ + if (ComponentTypeEnum.RESOURCE.equals(component.getComponentType())){ + Resource resource = (Resource) component; + if (isFromCsar(resource)){ + currComponentInstance.setCreatedFrom(CreatedFrom.CSAR); + } + else { + currComponentInstance.setCreatedFrom(CreatedFrom.UI); + } + } + } + } + + private static boolean isFromCsar(Resource resource) { + return resource.getResourceType() == ResourceTypeEnum.VF || resource.getResourceType() == ResourceTypeEnum.CVFC; + } + private static void setComponentInstancesInputsToComponent(TopologyTemplate topologyTemplate, Component component) { if (topologyTemplate.getInstInputs() != null) { Map<String, List<ComponentInstanceInput>> inputs = new HashMap<>(); @@ -1258,64 +1360,85 @@ public class ModelConverter { } } - private static void setComponentInstancesInterfacesToComponent(TopologyTemplate topologyTemplate, Component component) { - if (topologyTemplate.getInstInterfaces() != null) { - Map<String, List<ComponentInstanceInterface>> interfaces = new HashMap<>(); - for (Entry<String, MapInterfaceInstanceDataDefinition> entry : topologyTemplate.getInstInterfaces().entrySet()) { - if (entry.getValue() != null && entry.getValue().getMapToscaDataDefinition() != null) { - String key = entry.getKey(); - List<ComponentInstanceInterface> componentInstanceInterfaces = entry.getValue() - .getMapToscaDataDefinition().entrySet().stream().map(e -> new - ComponentInstanceInterface(e.getKey(), e.getValue())) - .collect(Collectors.toList()); - interfaces.put(key, componentInstanceInterfaces); - } - } - component.setComponentInstancesInterfaces(interfaces); - } - else if (topologyTemplate.getComponentInstInterfaces() != null) { - Map<String, List<ComponentInstanceInterface>> interfaces = new HashMap<>(); - for (Entry<String, MapInterfaceDataDefinition> entry : topologyTemplate.getComponentInstInterfaces().entrySet()) { - if (entry.getValue() != null && entry.getValue().getMapToscaDataDefinition() != null) { - String key = entry.getKey(); - List<ComponentInstanceInterface> componentInstanceInterfaces = entry.getValue() - .getMapToscaDataDefinition().entrySet().stream().map(e -> new - ComponentInstanceInterface(e.getKey(), e.getValue())) - .collect(Collectors.toList()); - interfaces.put(key, componentInstanceInterfaces); - } - } - component.setComponentInstancesInterfaces(interfaces); - } + public static Map<String, List<ComponentInstanceProperty>> getComponentInstancesAttributes(Map<String, MapPropertiesDataDefinition> mapPropertiesDataDefinition) { + Map<String, List<ComponentInstanceProperty>> attributes = new HashMap<>(); + for (Map.Entry<String, MapPropertiesDataDefinition> entry : mapPropertiesDataDefinition.entrySet()) { + if (entry.getValue() != null && entry.getValue().getMapToscaDataDefinition() != null) { + String key = entry.getKey(); + List<ComponentInstanceProperty> componentInstanceAttributes = entry.getValue().getMapToscaDataDefinition().entrySet().stream().map(e -> new ComponentInstanceProperty(new ComponentInstanceProperty(e.getValue()))) + .collect(Collectors.toList()); + attributes.put(key, componentInstanceAttributes); + } + } + return attributes; + } - } + private static void setComponentInstancesInterfacesToComponent(TopologyTemplate topologyTemplate, Component component) { + if (topologyTemplate.getInstInterfaces() != null) { + Map<String, List<ComponentInstanceInterface>> interfaces = new HashMap<>(); + for (Map.Entry<String, MapInterfaceInstanceDataDefinition> entry : topologyTemplate.getInstInterfaces().entrySet()) { + if (entry.getValue() != null && entry.getValue().getMapToscaDataDefinition() != null) { + String key = entry.getKey(); + List<ComponentInstanceInterface> componentInstanceInterfaces = entry.getValue() + .getMapToscaDataDefinition().entrySet().stream().map(e -> new + ComponentInstanceInterface(e.getKey(), e.getValue())) + .collect(Collectors.toList()); + interfaces.put(key, componentInstanceInterfaces); + } + } + component.setComponentInstancesInterfaces(interfaces); + } + else if (topologyTemplate.getComponentInstInterfaces() != null) { + Map<String, List<ComponentInstanceInterface>> interfaces = new HashMap<>(); + for (Map.Entry<String, MapInterfaceDataDefinition> entry : topologyTemplate.getComponentInstInterfaces().entrySet()) { + if (entry.getValue() != null && entry.getValue().getMapToscaDataDefinition() != null) { + String key = entry.getKey(); + List<ComponentInstanceInterface> componentInstanceInterfaces = entry.getValue() + .getMapToscaDataDefinition().entrySet().stream().map(e -> new + ComponentInstanceInterface(e.getKey(), e.getValue())) + .collect(Collectors.toList()); + interfaces.put(key, componentInstanceInterfaces); + } + } + component.setComponentInstancesInterfaces(interfaces); + } - private static void setComponentInstancesAttributesToComponent(TopologyTemplate topologyTemplate, Component component) { - if (topologyTemplate.getInstAttributes() != null) { - Map<String, List<ComponentInstanceProperty>> attributes = new HashMap<>(); - for (Map.Entry<String, MapPropertiesDataDefinition> entry : topologyTemplate.getInstAttributes().entrySet()) { - if (entry.getValue() != null && entry.getValue().getMapToscaDataDefinition() != null) { - String key = entry.getKey(); - List<ComponentInstanceProperty> componentInstanceAttributes = entry.getValue().getMapToscaDataDefinition().entrySet().stream().map(e -> new ComponentInstanceProperty(new ComponentInstanceProperty(e.getValue()))) - .collect(Collectors.toList()); - attributes.put(key, componentInstanceAttributes); - } - } - component.setComponentInstancesAttributes(attributes); - } - } + } + + private static void setComponentInstancesAttributesToComponent(TopologyTemplate topologyTemplate, Component component) { + if (topologyTemplate.getInstAttributes() != null) { + Map<String, List<ComponentInstanceProperty>> attributes = new HashMap<>(); + for (Map.Entry<String, MapPropertiesDataDefinition> entry : topologyTemplate.getInstAttributes().entrySet()) { + if (entry.getValue() != null && entry.getValue().getMapToscaDataDefinition() != null) { + String key = entry.getKey(); + List<ComponentInstanceProperty> componentInstanceAttributes = entry.getValue().getMapToscaDataDefinition().entrySet().stream().map(e -> new ComponentInstanceProperty(new ComponentInstanceProperty(e.getValue()))) + .collect(Collectors.toList()); + attributes.put(key, componentInstanceAttributes); + } + } + component.setComponentInstancesAttributes(attributes); + } + } - private static void setComponentInstancesRequirementsToComponent(TopologyTemplate topologyTemplate, Component component) { + + public 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, List<RequirementDefinition>> instanceRequiermentsFromMapObject = getInstanceRequirementsFromMapObject(topologyTemplate.getCalculatedRequirements(), component); + component.setRequirements(instanceRequiermentsFromMapObject); + } + } + public static Map<String, List<RequirementDefinition>> getInstanceRequirementsFromMapObject(Map<String, MapListRequirementDataDefinition> mapListRequirements, Component component) { + // Requirements of component organized by capability + Map<String, List<RequirementDefinition>> instancesRequirements = new HashMap<>(); + if (mapListRequirements!= null) { 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()) { + for (Map.Entry<String, MapListRequirementDataDefinition> entry : mapListRequirements.entrySet()) { String instanceId = entry.getKey(); // Requirements of instance organized by capability @@ -1324,7 +1447,7 @@ public class ModelConverter { if(capsMapList != null) { for (Entry<String, ListRequirementDataDefinition> entryTypeList : capsMapList.entrySet()) { String capabilityType = entryTypeList.getKey(); - List<RequirementDefinition> caps = entryTypeList.getValue().getListToscaDataDefinition().stream().map(RequirementDefinition::new).collect(Collectors.toList()); + List<RequirementDefinition> caps = entryTypeList.getValue().getListToscaDataDefinition().stream().map(RequirementDefinition::new).collect(Collectors.toList()); if (instancesRequirements.containsKey(capabilityType)) { instancesRequirements.get(capabilityType).addAll(caps); } else { @@ -1339,9 +1462,10 @@ public class ModelConverter { } component.setRequirements(instancesRequirements); } + return instancesRequirements; } - private static void setComponentInstancesCapabilitiesToComponentAndCI(TopologyTemplate topologyTemplate, Component component) { + public static void setComponentInstancesCapabilitiesToComponentAndCI(TopologyTemplate topologyTemplate, Component component) { Map<String, MapCapabilityProperty> calculatedCapProperties = topologyTemplate.getCalculatedCapabilitiesProperties(); if (topologyTemplate.getCalculatedCapabilities() != null) { @@ -1662,32 +1786,52 @@ public class ModelConverter { } public static ComponentMetadataData convertToComponentMetadata(GraphVertex vertex) { - ComponentMetadataData metadata = null; + ComponentMetadataData metadata; switch (vertex.getType()) { case SERVICE: - metadata = new ServiceMetadataData(vertex.getMetadataJson()); + metadata = new ServiceMetadataData(new GraphPropertiesDictionaryExtractor(vertex.getMetadataJson())); break; case RESOURCE: - metadata = new ResourceMetadataData(vertex.getMetadataJson()); + metadata = new ResourceMetadataData(new GraphPropertiesDictionaryExtractor(vertex.getMetadataJson())); break; case PRODUCT: - metadata = new ProductMetadataData(vertex.getMetadataJson()); + metadata = new ProductMetadataData(new GraphPropertiesDictionaryExtractor(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)); + throw new StorageException(JanusGraphOperationStatus.INVALID_TYPE); } + 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 ComponentMetadataDataDefinition convertToComponentMetadataDataDefinition(GraphVertex vertex) { + ComponentMetadataDataDefinition metadata; + switch (vertex.getType()) { + case SERVICE: + metadata = new ServiceMetadataDataDefinition(new JsonPresentationFieldsExtractor(vertex.getMetadataJson())); + break; + case RESOURCE: + metadata = new ResourceMetadataDataDefinition(new JsonPresentationFieldsExtractor(vertex.getMetadataJson())); + break; + case PRODUCT: + metadata = new ProductMetadataDataDefinition(new JsonPresentationFieldsExtractor(vertex.getMetadataJson())); + break; + default: + throw new StorageException(JanusGraphOperationStatus.INVALID_TYPE); + } + metadata.setUniqueId(vertex.getUniqueId()); + metadata.setLastUpdateDate((Long) vertex.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE)); + metadata.setUUID((String) vertex.getJsonMetadataField(JsonPresentationFields.UUID)); + metadata.setState((String) vertex.getJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE)); return metadata; } public static List<GroupDefinition> convertToGroupDefinitions(Map<String, GroupDataDefinition> groups) { - List<GroupDefinition> groupDefinitions = null; + List<GroupDefinition> groupDefinitions = new ArrayList<>(); if (MapUtils.isNotEmpty(groups)) { groupDefinitions = groups.values().stream().map(GroupDefinition::new).collect(Collectors.toList()); } @@ -1718,7 +1862,7 @@ public class ModelConverter { return calculatedCapabilities; } - public static Map<String, ListCapabilityDataDefinition> buildMapOfListsOfCapabilities(GroupDefinition groupDefinition) { + private static Map<String, ListCapabilityDataDefinition> buildMapOfListsOfCapabilities(GroupDefinition groupDefinition) { return groupDefinition.getCapabilities().entrySet() .stream() .collect(Collectors.toMap(Map.Entry::getKey, e-> new ListCapabilityDataDefinition(e.getValue() diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/StorageException.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/StorageException.java index 51ae18b0d4..7ca574b0c2 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/StorageException.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/StorageException.java @@ -20,6 +20,7 @@ package org.openecomp.sdc.be.model.operations; +import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; @@ -48,6 +49,11 @@ public class StorageException extends RuntimeException{ this.params = params; } + public StorageException(CassandraOperationStatus cassandraOperationStatus, String... params) { + storageOperationStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(cassandraOperationStatus); + this.params = params; + } + public StorageOperationStatus getStorageOperationStatus() { return storageOperationStatus; } 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 deleted file mode 100644 index b1ce9de66e..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IAdditionalInformationOperation.java +++ /dev/null @@ -1,73 +0,0 @@ -/*- - * ============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 org.janusgraph.core.JanusGraphVertex; -import fj.data.Either; -import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; -import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.model.AdditionalInformationDefinition; -import org.openecomp.sdc.be.resources.data.AdditionalInfoParameterData; - -import java.util.List; - -public interface IAdditionalInformationOperation { - - public Either<AdditionalInformationDefinition, JanusGraphOperationStatus> addAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String key, String value); - - public Either<AdditionalInformationDefinition, JanusGraphOperationStatus> updateAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String origKey, String key, String value); - - public Either<AdditionalInformationDefinition, JanusGraphOperationStatus> deleteAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String key); - - public Either<AdditionalInfoParameterData, JanusGraphOperationStatus> addAdditionalInformationNode(NodeTypeEnum nodeType, String resourceUniqueId); - - public Either<AdditionalInformationDefinition, JanusGraphOperationStatus> addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId, AdditionalInformationDefinition parameters); - - public JanusGraphOperationStatus findResourceAllAdditionalInformationRecursively(String uniqueId, List<AdditionalInformationDefinition> properties); - - public JanusGraphOperationStatus 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> 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<Integer, StorageOperationStatus> getNumberOfAdditionalInformationParameters(NodeTypeEnum nodeType, String resourceId, boolean inTransaction); - - public Either<Integer, JanusGraphOperationStatus> getNumberOfParameters(NodeTypeEnum nodeType, String resourceId); - - public Either<AdditionalInfoParameterInfo, JanusGraphOperationStatus> getAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String id); - - public Either<AdditionalInfoParameterInfo, StorageOperationStatus> getAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String id, boolean inTransaction); - - public Either<AdditionalInformationDefinition, JanusGraphOperationStatus> getAllAdditionalInformationParameters(NodeTypeEnum nodeType, String resourceId, boolean ignoreVerification); - - 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<JanusGraphVertex, JanusGraphOperationStatus> addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId, JanusGraphVertex matadatVertex); - - public JanusGraphOperationStatus addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId, AdditionalInformationDefinition parameters, JanusGraphVertex 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 deleted file mode 100644 index e3b7689d30..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IArtifactOperation.java +++ /dev/null @@ -1,42 +0,0 @@ -/*- - * ============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 org.janusgraph.core.JanusGraphVertex; -import fj.data.Either; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.model.ArtifactDefinition; - -import java.util.Map; - -public interface IArtifactOperation { - - public Either<ArtifactDefinition, StorageOperationStatus> addArifactToComponent(ArtifactDefinition artifactInfo, String id, NodeTypeEnum type, boolean failIfExist, boolean inTransaction); - - public Either<ArtifactDefinition, StorageOperationStatus> updateArifactOnResource(ArtifactDefinition artifactInfo, String id, String artifactId, NodeTypeEnum type, boolean inTransaction); - - public Either<ArtifactDefinition, StorageOperationStatus> removeArifactFromResource(String id, String artifactId, NodeTypeEnum resource, boolean deleteMandatoryArtifact, boolean inTransaction); - - public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, boolean inTransaction); - - public StorageOperationStatus addArifactToComponent(ArtifactDefinition artifactInfo, String parentId, NodeTypeEnum type, boolean failIfExist, JanusGraphVertex parentVertex); - -} 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/ICacheMangerOperation.java index 196661fb76..fcf5fab019 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/ICacheMangerOperation.java @@ -20,28 +20,22 @@ package org.openecomp.sdc.be.model.operations.api; -import fj.data.Either; -import org.apache.tinkerpop.gremlin.structure.Edge; -import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import java.util.List; -import java.util.Map; - -public interface IUserAdminOperation { - - public Either<User, ActionStatus> getUserData(String id, boolean inTransaction); - - public Either<User, StorageOperationStatus> saveUserData(User user); - - public Either<User, StorageOperationStatus> updateUserData(User user); - - public Either<User, StorageOperationStatus> deActivateUser(User user); - - public Either<User, ActionStatus> deleteUserData(String id); - - public Either<List<User>, ActionStatus> getAllUsersWithRole(String role, String status); - - public Either<List<Edge>, StorageOperationStatus> getUserPendingTasksList(User user, Map<String, Object> properties); +/** + * Created by mlando on 9/5/2016. + */ +public interface ICacheMangerOperation { + + /** + * + * + * @param componentId + * @param timestamp + * @param nodeTypeEnum + */ + void updateComponentInCache(String componentId, long timestamp, NodeTypeEnum nodeTypeEnum); + + void storeComponentInCache(org.openecomp.sdc.be.model.Component component, NodeTypeEnum nodeTypeEnum); } 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 deleted file mode 100644 index 0b2807a82e..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/api/IComponentInstanceOperation.java +++ /dev/null @@ -1,71 +0,0 @@ -/*- - * ============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 fj.data.Either; -import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -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.resources.data.ComponentInstanceData; - -public interface IComponentInstanceOperation { - - public Either<Integer, StorageOperationStatus> increaseAndGetResourceInstanceSpecificCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, boolean inTransaction); - - /** - * Adds Attribute to resource instance - * - * @param resourceInstanceAttribute - * * @param resourceInstanceId * @param index * @param inTransaction - * @return - **/ - public Either<ComponentInstanceProperty, StorageOperationStatus> addAttributeValueToResourceInstance(ComponentInstanceProperty resourceInstanceAttribute, String resourceInstanceId, Integer index, boolean inTransaction); - - /** - * Updates Attribute on resource instance - * - * @param attribute - * @param resourceInstanceId - * @param inTransaction - * @return - */ - public Either<ComponentInstanceProperty, StorageOperationStatus> updateAttributeValueInResourceInstance(ComponentInstanceProperty attribute, String resourceInstanceId, boolean inTransaction); - - - 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 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); - -} 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 71a54a3214..6ecfc1048b 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 @@ -21,6 +21,7 @@ package org.openecomp.sdc.be.model.operations.api; import fj.data.Either; +import org.openecomp.sdc.be.config.Configuration; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; @@ -51,7 +52,7 @@ public interface IElementOperation { public Either<Map<String, Object>, ActionStatus> getAllDeploymentArtifactTypes(); - public Either<Integer, ActionStatus> getDefaultHeatTimeout(); + public Either<Configuration.HeatDeploymentArtifactTimeout, ActionStatus> getDefaultHeatTimeout(); public <T extends GraphNode> Either<CategoryData, StorageOperationStatus> getCategoryData(String name, NodeTypeEnum type, Class<T> clazz); 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 c53f3e3d86..427ad4314a 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 @@ -24,7 +24,6 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.reflect.TypeToken; -import org.janusgraph.core.JanusGraphVertex; import fj.data.Either; import java.lang.reflect.Type; import java.util.List; @@ -35,8 +34,6 @@ import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; 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; import org.openecomp.sdc.be.dao.janusgraph.HealingJanusGraphGenericDao; import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; @@ -54,7 +51,6 @@ 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.ResourceMetadataData; -import org.openecomp.sdc.be.resources.data.UniqueIdData; import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.beans.factory.annotation.Autowired; @@ -74,69 +70,6 @@ public abstract class AbstractOperation { protected DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance(); - protected <SomeData extends GraphNode, SomeDefenition> Either<SomeData, JanusGraphOperationStatus> addDefinitionToNodeType(SomeDefenition someDefinition, NodeTypeEnum nodeType, String nodeUniqueId, final GraphEdgeLabels edgeType, - Supplier<SomeData> dataBuilder, Supplier<String> defNameGenerator) { - String defName = defNameGenerator.get(); - log.debug("Got {} {}", defName, someDefinition); - - SomeData someData = dataBuilder.get(); - - log.debug("Before adding {} to graph. data = {}", defName, someData); - - @SuppressWarnings("unchecked") - Either<SomeData, JanusGraphOperationStatus> eitherSomeData = janusGraphGenericDao - .createNode(someData, (Class<SomeData>) someData.getClass()); - - log.debug("After adding {} to graph. status is = {}", defName, eitherSomeData); - - if (eitherSomeData.isRight()) { - JanusGraphOperationStatus operationStatus = eitherSomeData.right().value(); - log.error("Failed to add {} to graph. status is {}", defName, operationStatus); - return Either.right(operationStatus); - } - UniqueIdData uniqueIdData = new UniqueIdData(nodeType, nodeUniqueId); - log.debug("Before associating {} to {}.", uniqueIdData, defName); - - Either<GraphRelation, JanusGraphOperationStatus> eitherRelations = janusGraphGenericDao - .createRelation(uniqueIdData, eitherSomeData.left().value(), edgeType, null); - if (eitherRelations.isRight()) { - JanusGraphOperationStatus operationStatus = eitherRelations.right().value(); - BeEcompErrorManager.getInstance().logInternalFlowError("AddDefinitionToNodeType", "Failed to associate" + nodeType.getName() + " " + nodeUniqueId + "to " + defName + "in graph. status is " + operationStatus, ErrorSeverity.ERROR); - return Either.right(operationStatus); - } - return Either.left(eitherSomeData.left().value()); - } - - protected <SomeData extends GraphNode, SomeDefenition> JanusGraphOperationStatus addDefinitionToNodeType(JanusGraphVertex vertex, SomeDefenition someDefinition, NodeTypeEnum nodeType, String nodeUniqueId, final GraphEdgeLabels edgeType, - Supplier<SomeData> dataBuilder, Supplier<String> defNameGenerator) { - String defName = defNameGenerator.get(); - log.debug("Got {} {}", defName, someDefinition); - - SomeData someData = dataBuilder.get(); - - log.debug("Before adding {} to graph. data = {}", defName, someData); - - @SuppressWarnings("unchecked") - Either<JanusGraphVertex, JanusGraphOperationStatus> eitherSomeData = janusGraphGenericDao.createNode(someData); - - log.debug("After adding {} to graph. status is = {}", defName, eitherSomeData); - - if (eitherSomeData.isRight()) { - JanusGraphOperationStatus operationStatus = eitherSomeData.right().value(); - log.error("Failed to add {} to graph. status is {}", defName, operationStatus); - return operationStatus; - } - - JanusGraphOperationStatus - relations = janusGraphGenericDao - .createEdge(vertex, eitherSomeData.left().value(), edgeType, null); - if (!relations.equals(JanusGraphOperationStatus.OK)) { - BeEcompErrorManager.getInstance().logInternalFlowError("AddDefinitionToNodeType", "Failed to associate" + nodeType.getName() + " " + nodeUniqueId + "to " + defName + "in graph. status is " + relations, ErrorSeverity.ERROR); - return relations; - } - return relations; - } - interface NodeElementFetcher<ElementDefinition> { JanusGraphOperationStatus findAllNodeElements(String nodeId, List<ElementDefinition> listTofill); } 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 f247bbb74d..68fc5977c4 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 @@ -37,7 +37,6 @@ import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefini import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; 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; import org.openecomp.sdc.be.resources.data.AdditionalInfoParameterData; import org.openecomp.sdc.be.resources.data.ResourceMetadataData; @@ -53,7 +52,7 @@ import java.util.Map; import java.util.Map.Entry; @Component("additional-information-operation") -public class AdditionalInformationOperation implements IAdditionalInformationOperation { +public class AdditionalInformationOperation { private static final Logger log = Logger.getLogger(AdditionalInformationOperation.class.getName()); @@ -70,7 +69,6 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe } - @Override public Either<AdditionalInformationDefinition, JanusGraphOperationStatus> addAdditionalInformationParameter(NodeTypeEnum nodeType, String componentId, String key, String value) { JanusGraphOperationStatus @@ -128,7 +126,6 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe } - @Override public Either<AdditionalInformationDefinition, JanusGraphOperationStatus> updateAdditionalInformationParameter(NodeTypeEnum nodeType, String componentId, String id, String key, String value) { JanusGraphOperationStatus @@ -182,7 +179,6 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe } - @Override public Either<AdditionalInformationDefinition, JanusGraphOperationStatus> deleteAdditionalInformationParameter(NodeTypeEnum nodeType, String componentId, String id) { JanusGraphOperationStatus @@ -256,7 +252,6 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe return list; } - @Override public Either<AdditionalInfoParameterData, JanusGraphOperationStatus> addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId) { UniqueIdData from = new UniqueIdData(nodeType, componentId); @@ -287,7 +282,6 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe return Either.left(to); } - @Override public Either<JanusGraphVertex, JanusGraphOperationStatus> addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId, JanusGraphVertex metadataVertex) { String uniqueId = UniqueIdBuilder.buildAdditionalInformationUniqueId(componentId); @@ -385,7 +379,6 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe } - @Override public JanusGraphOperationStatus findResourceAllAdditionalInformationRecursively(String uniqueId, List<AdditionalInformationDefinition> properties) { log.trace("Going to fetch additional information under resource {}", uniqueId); @@ -421,7 +414,6 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe } - @Override public JanusGraphOperationStatus findServiceAllAdditionalInformationRecursively(String uniqueId, List<AdditionalInformationDefinition> properties) { log.trace("Going to fetch additional information under service {}", uniqueId); @@ -492,7 +484,6 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe return new AdditionalInformationDefinition(additionalInfoData.getAdditionalInfoParameterDataDefinition(), uniqueId, convertParameters(parameters, idToKey)); } - @Override public Either<AdditionalInformationDefinition, StorageOperationStatus> createAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String key, String value, boolean inTransaction) { Either<AdditionalInformationDefinition, StorageOperationStatus> result = null; @@ -518,7 +509,6 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe } - @Override public Either<AdditionalInformationDefinition, StorageOperationStatus> updateAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String id, String key, String value, boolean inTransaction) { Either<AdditionalInformationDefinition, StorageOperationStatus> result = null; @@ -543,7 +533,6 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe } - @Override public Either<AdditionalInformationDefinition, StorageOperationStatus> deleteAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String id, boolean inTransaction) { Either<AdditionalInformationDefinition, StorageOperationStatus> result = null; @@ -568,7 +557,6 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe } - @Override public Either<Integer, StorageOperationStatus> getNumberOfAdditionalInformationParameters(NodeTypeEnum nodeType, String resourceId, boolean inTransaction) { Either<Integer, StorageOperationStatus> result = null; @@ -600,7 +588,6 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe } - @Override public Either<Integer, JanusGraphOperationStatus> getNumberOfParameters(NodeTypeEnum nodeType, String resourceId) { Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, JanusGraphOperationStatus> getResult = janusGraphGenericDao @@ -625,7 +612,6 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe } - @Override public Either<AdditionalInfoParameterInfo, JanusGraphOperationStatus> getAdditionalInformationParameter(NodeTypeEnum nodeType, String componentId, String id) { JanusGraphOperationStatus @@ -674,7 +660,6 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe } - @Override public Either<AdditionalInformationDefinition, JanusGraphOperationStatus> getAllAdditionalInformationParameters(NodeTypeEnum nodeType, String componentId, boolean ignoreVerification) { if (!ignoreVerification) { @@ -708,7 +693,6 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe } - @Override public Either<AdditionalInformationDefinition, StorageOperationStatus> getAllAdditionalInformationParameters(NodeTypeEnum nodeType, String resourceId, boolean ignoreVerification, boolean inTransaction) { Either<AdditionalInformationDefinition, StorageOperationStatus> result = null; @@ -747,7 +731,6 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe } - @Override public Either<AdditionalInfoParameterInfo, StorageOperationStatus> getAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String id, boolean inTransaction) { Either<AdditionalInfoParameterInfo, StorageOperationStatus> result = null; @@ -771,7 +754,6 @@ public class AdditionalInformationOperation implements IAdditionalInformationOpe } } - @Override public Either<AdditionalInformationDefinition, StorageOperationStatus> deleteAllAdditionalInformationParameters(NodeTypeEnum nodeType, String resourceId, boolean inTransaction) { Either<AdditionalInformationDefinition, StorageOperationStatus> result = null; 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 4e65fa5d2b..f64f761873 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 @@ -42,13 +42,13 @@ 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.model.HeatParameterDefinition; -import org.openecomp.sdc.be.model.operations.api.IArtifactOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.resources.data.ArtifactData; import org.openecomp.sdc.be.resources.data.HeatParameterData; import org.openecomp.sdc.be.resources.data.HeatParameterValueData; import org.openecomp.sdc.be.resources.data.UniqueIdData; import org.openecomp.sdc.common.api.ArtifactTypeEnum; +import org.openecomp.sdc.common.log.api.ILogConfiguration; import org.openecomp.sdc.common.log.wrappers.Logger; import org.slf4j.MDC; import org.springframework.stereotype.Component; @@ -56,7 +56,7 @@ import org.springframework.stereotype.Component; import java.util.*; @Component("artifact-operation") -public class ArtifactOperation implements IArtifactOperation { +public class ArtifactOperation { private static final String THE_RETURNED_ARTIFACT_DEFINTION_IS = "The returned ArtifactDefintion is {}"; @@ -93,7 +93,6 @@ public class ArtifactOperation implements IArtifactOperation { this.heatParametersOperation = heatParametersOperation; } - @Override public Either<ArtifactDefinition, StorageOperationStatus> addArifactToComponent(ArtifactDefinition artifactInfo, String parentId, NodeTypeEnum type, boolean failIfExist, boolean inTransaction) { Either<ArtifactData, StorageOperationStatus> status = addArtifactToGraph(artifactInfo, parentId, type, failIfExist); @@ -118,7 +117,6 @@ public class ArtifactOperation implements IArtifactOperation { } - @Override public StorageOperationStatus addArifactToComponent(ArtifactDefinition artifactInfo, String parentId, NodeTypeEnum type, boolean failIfExist, JanusGraphVertex parentVertex) { StorageOperationStatus status = addArtifactToGraph(artifactInfo, parentId, type, failIfExist, parentVertex); @@ -291,7 +289,6 @@ public class ArtifactOperation implements IArtifactOperation { return propertyDefResult; } - @Override public Either<ArtifactDefinition, StorageOperationStatus> updateArifactOnResource(ArtifactDefinition artifactInfo, String id, String artifactId, NodeTypeEnum type, boolean inTransaction) { Either<ArtifactData, StorageOperationStatus> status = updateArtifactOnGraph(artifactInfo, artifactId, type, id); @@ -314,7 +311,6 @@ public class ArtifactOperation implements IArtifactOperation { } } - @Override public Either<ArtifactDefinition, StorageOperationStatus> removeArifactFromResource(String id, String artifactId, NodeTypeEnum type, boolean deleteMandatoryArtifact, boolean inTransaction) { Either<ArtifactData, StorageOperationStatus> status = removeArtifactOnGraph(id, artifactId, type, deleteMandatoryArtifact); @@ -751,7 +747,7 @@ public class ArtifactOperation implements IArtifactOperation { UUID uuid = UUID.randomUUID(); artifactData.setArtifactUUID(uuid.toString()); - MDC.put("serviceInstanceID", uuid.toString()); + MDC.put(ILogConfiguration.MDC_SERVICE_INSTANCE_ID, uuid.toString()); updateVersionAndDate(artifactData, oldVesrion); } 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 91b4e0a0ce..38ce067ee5 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 @@ -49,7 +49,6 @@ import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.IComponentInstanceConnectedElement; import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; -import org.openecomp.sdc.be.model.operations.api.IComponentInstanceOperation; import org.openecomp.sdc.be.model.operations.api.IInputsOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; @@ -63,7 +62,7 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.beans.factory.annotation.Autowired; @org.springframework.stereotype.Component("component-instance-operation") -public class ComponentInstanceOperation extends AbstractOperation implements IComponentInstanceOperation { +public class ComponentInstanceOperation extends AbstractOperation { public ComponentInstanceOperation() { super(); @@ -89,7 +88,6 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo this.janusGraphGenericDao = janusGraphGenericDao; } - @Override public Either<Integer, StorageOperationStatus> increaseAndGetResourceInstanceSpecificCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, boolean inTransaction) { Either<Integer, StorageOperationStatus> result = null; @@ -556,7 +554,6 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } - @Override public Either<ComponentInstanceProperty, StorageOperationStatus> addAttributeValueToResourceInstance(ComponentInstanceProperty resourceInstanceAttribute, String resourceInstanceId, Integer index, boolean inTransaction) { Either<ComponentInstanceProperty, StorageOperationStatus> result = null; @@ -590,7 +587,6 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo return new ComponentInstanceProperty(hidden, resourceInstanceAttribute, uid); } - @Override public Either<ComponentInstanceProperty, StorageOperationStatus> updateAttributeValueInResourceInstance(ComponentInstanceProperty resourceInstanceAttribute, String resourceInstanceId, boolean inTransaction) { Either<ComponentInstanceProperty, StorageOperationStatus> result = null; @@ -619,7 +615,6 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } - @Override public Either<ComponentInstanceInput, StorageOperationStatus> addInputValueToResourceInstance(ComponentInstanceInput resourceInstanceInput, String resourceInstanceId, Integer index, boolean inTransaction) { /// #RULES SUPPORT @@ -672,12 +667,10 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo } - @Override public Either<ComponentInstanceInput, StorageOperationStatus> updateInputValueInResourceInstance(ComponentInstanceInput input, String resourceInstanceId, boolean b) { return null; } - @Override public StorageOperationStatus updateCustomizationUUID(String componentInstanceId) { Either<JanusGraphVertex, JanusGraphOperationStatus> vertexByProperty = janusGraphGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), componentInstanceId); if (vertexByProperty.isRight()) { @@ -691,7 +684,6 @@ public class ComponentInstanceOperation extends AbstractOperation implements ICo return StorageOperationStatus.OK; } - @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()); 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 b429071572..4da2cb4d40 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 @@ -22,8 +22,8 @@ package org.openecomp.sdc.be.model.operations.impl; import fj.data.Either; import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao; -import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; +import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.operations.api.IConsumerOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; 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 ce9d320ed7..402129b8ba 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 @@ -25,6 +25,7 @@ import org.janusgraph.core.JanusGraphVertex; import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.openecomp.sdc.be.config.Configuration; import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; @@ -809,8 +810,8 @@ public class ElementOperation implements IElementOperation { } @Override - public Either<Integer, ActionStatus> getDefaultHeatTimeout() { - return Either.left(ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes()); + public Either<Configuration.HeatDeploymentArtifactTimeout, ActionStatus> getDefaultHeatTimeout() { + return Either.left(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatArtifactDeploymentTimeout()); } @Override 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 index 39d4c73afb..6e980f20ba 100644 --- 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 @@ -68,8 +68,6 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI @javax.annotation.Resource private ApplicationDataTypeCache dataTypeCache; - - @Override public Either<List<GroupInstance>, StorageOperationStatus> getAllGroupInstances(String parentId, NodeTypeEnum parentType) { Either<List<GroupInstance>, StorageOperationStatus> result = null; List<GroupInstance> groupInstanceRes = new ArrayList<>(); @@ -100,11 +98,6 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI if (childrenByEdgeCriteria.isRight()) { JanusGraphOperationStatus status = childrenByEdgeCriteria.right().value(); log.debug("Failed to find group instance {} on graph", childrenByEdgeCriteria.right().value()); - - if (status == JanusGraphOperationStatus.NOT_FOUND) { - return Either.left(groupInstanceRes); - } - return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); } @@ -159,12 +152,11 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI } - @Override + public Either<Integer, StorageOperationStatus> increaseAndGetGroupInstancePropertyCounter(String instanceId) { return propertyOperation.increaseAndGetObjInstancePropertyCounter(instanceId, NodeTypeEnum.GroupInstance); } - @Override public Either<ComponentInstanceProperty, StorageOperationStatus> addPropertyValueToGroupInstance(ComponentInstanceProperty groupInstanceProperty, String groupInstanceId, Integer index, boolean inTransaction) { /// #RULES SUPPORT /// Ignore rules received from client till support @@ -216,7 +208,6 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI } - @Override public Either<ComponentInstanceProperty, StorageOperationStatus> updatePropertyValueInGroupInstance(ComponentInstanceProperty gropuInstanceProperty, String groupInstanceId, boolean inTransaction) { // TODO Auto-generated method stub // change Propety class @@ -674,7 +665,6 @@ public class GroupInstanceOperation extends AbstractOperation implements IGroupI } - @Override public StorageOperationStatus dissociateAndAssociateGroupsInstanceFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact) { return this.dissociateAndAssociateGroupsInstanceFromArtifactOnGraph(componentId, componentTypeEnum, oldArtifactId, newArtifact); 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 c8135ad54b..164fa4d444 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 @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -240,7 +240,6 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation return Either.left(groupPropertiesList); } - @Override public Either<List<GraphRelation>, StorageOperationStatus> dissociateAllGroupsFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String artifactId) { List<GraphRelation> relations = new ArrayList<>(); @@ -387,7 +386,6 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation } - @Override public boolean isGroupExist(String groupName, boolean inTransaction) { Either<List<GroupData>, JanusGraphOperationStatus> eitherGroup = null; @@ -506,7 +504,6 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation return StorageOperationStatus.OK; } - @Override public StorageOperationStatus dissociateAndAssociateGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact, boolean inTransaction) { StorageOperationStatus result = null; @@ -571,7 +568,6 @@ public class GroupOperation extends AbstractOperation implements IGroupOperation } - @Override public StorageOperationStatus validateAndUpdatePropertyValue(GroupProperty property) { StorageOperationStatus result = null; 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 430ba59e75..a6538dcea1 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 @@ -83,7 +83,6 @@ public class GroupTypeOperation implements IGroupTypeOperation { this.operationUtils = operationUtils; } - @Override public Either<GroupTypeDefinition, StorageOperationStatus> addGroupType(GroupTypeDefinition groupTypeDefinition) { Either<GroupTypeDefinition, StorageOperationStatus> validationRes = validateUpdateProperties(groupTypeDefinition); if (validationRes.isRight()) { @@ -94,7 +93,6 @@ public class GroupTypeOperation implements IGroupTypeOperation { return addGroupType(groupTypeDefinition, true); } - @Override public Either<GroupTypeDefinition, StorageOperationStatus> addGroupType(GroupTypeDefinition groupTypeDefinition, boolean inTransaction) { Either<GroupTypeDefinition, StorageOperationStatus> result = null; @@ -119,7 +117,6 @@ public class GroupTypeOperation implements IGroupTypeOperation { } - @Override public Either<GroupTypeDefinition, StorageOperationStatus> updateGroupType(GroupTypeDefinition updatedGroupType, GroupTypeDefinition currGroupType) { log.debug("updating group type {}", updatedGroupType.getType()); return updateGroupTypeOnGraph(updatedGroupType, currGroupType); @@ -330,7 +327,6 @@ public class GroupTypeOperation implements IGroupTypeOperation { .bind(groupType -> buildGroupTypeDefinition(uniqueId, groupType)); } - @Override public Either<GroupTypeDefinition, StorageOperationStatus> getGroupType(String uniqueId, boolean inTransaction) { Either<GroupTypeDefinition, StorageOperationStatus> result = null; try { @@ -355,12 +351,10 @@ public class GroupTypeOperation implements IGroupTypeOperation { } - @Override public Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeByType(String type) { return getLatestGroupTypeByType(type, true); } - @Override public Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeByType(String type, boolean inTransaction) { Map<String, Object> mapCriteria = new HashMap<>(); mapCriteria.put(GraphPropertiesDictionary.TYPE.getProperty(), type); @@ -472,12 +466,10 @@ public class GroupTypeOperation implements IGroupTypeOperation { } - @Override 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) { Map<String, Object> mapCriteria = new HashMap<>(); mapCriteria.put(GraphPropertiesDictionary.TYPE.getProperty(), type); 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 b9e95c507f..5c5bf8939a 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 @@ -54,6 +54,8 @@ import java.util.stream.Collectors; public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation { private static final Logger log = Logger.getLogger(InterfaceLifecycleOperation.class.getName()); + private static final String FAILED_TO_FIND_OPERATION = "Failed to find operation {} on interface {}"; + private static final String FAILED_TO_FIND_ARTIFACT = "Failed to add artifact {} to interface {}"; public InterfaceLifecycleOperation() { super(); @@ -195,6 +197,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation return Either.left(createNodeResult.left().value()); } + @Override public Either<Map<String, InterfaceDefinition>, StorageOperationStatus> getAllInterfacesOfResource(String resourceIdn, boolean recursively) { return getAllInterfacesOfResource(resourceIdn, recursively, false); @@ -408,6 +411,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation @Override public Either<Operation, StorageOperationStatus> updateInterfaceOperation(String resourceId, String interfaceName, String operationName, Operation operation, boolean inTransaction) { + return updateOperationOnGraph(operation, resourceId, interfaceName, operationName); } @@ -443,7 +447,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation .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); + log.error(FAILED_TO_FIND_OPERATION, operationName, interfaceName); return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(operationRes.right().value())); } else { List<ImmutablePair<OperationData, GraphEdge>> operations = operationRes.left().value(); @@ -464,7 +468,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation } if (artStatus.isRight()) { janusGraphGenericDao.rollback(); - log.error("Failed to add artifact {} to interface {}", operationName, interfaceName); + log.error(FAILED_TO_FIND_ARTIFACT, operationName, interfaceName); return Either.right(artStatus.right().value()); } else { newOperation = this.convertOperationDataToOperation(opData); @@ -487,7 +491,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation .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); + log.error(FAILED_TO_FIND_OPERATION, operationName, interfaceName); return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(operationRes.right().value())); } else { @@ -534,7 +538,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation Either<ArtifactDefinition, StorageOperationStatus> artStatus = artifactOperation.addArifactToComponent(artifact, (String) operationStatus.left().value().getUniqueId(), NodeTypeEnum.InterfaceOperation, true, true); if (artStatus.isRight()) { janusGraphGenericDao.rollback(); - log.error("Failed to add artifact {} to interface {}", operationName, interfaceName); + log.error(FAILED_TO_FIND_ARTIFACT, operationName, interfaceName); } else { newOperation = this.convertOperationDataToOperation(opData); newOperation.setImplementation(artStatus.left().value()); @@ -581,7 +585,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation .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, operationName, interfaceName); return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(operationRes.right().value())); } else { @@ -676,7 +680,7 @@ public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation Either<ArtifactDefinition, StorageOperationStatus> artRes = artifactOperation.addArifactToComponent(art, (String) opData.getUniqueId(), NodeTypeEnum.InterfaceOperation, failIfExist, true); if (artRes.isRight()) { janusGraphGenericDao.rollback(); - log.error("Failed to add artifact {} to interface {}", operationName, interfaceName); + log.error(FAILED_TO_FIND_ARTIFACT, operationName, interfaceName); } else { newOperation.setImplementation(artRes.left().value()); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/Neo4jStatusConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/Neo4jStatusConverter.java deleted file mode 100644 index 6093eb0433..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/Neo4jStatusConverter.java +++ /dev/null @@ -1,78 +0,0 @@ -/*- - * ============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 org.openecomp.sdc.be.dao.neo4j.Neo4jOperationStatus; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; - -public class Neo4jStatusConverter { - - public static StorageOperationStatus convertNeo4jStatusToStorageStatus(Neo4jOperationStatus neo4jStatus) { - - if (neo4jStatus == null) { - return StorageOperationStatus.GENERAL_ERROR; - } - - switch (neo4jStatus) { - - case OK: - return StorageOperationStatus.OK; - - case NOT_CONNECTED: - return StorageOperationStatus.CONNECTION_FAILURE; - - case NOT_AUTHORIZED: - return StorageOperationStatus.PERMISSION_ERROR; - - case HTTP_PROTOCOL_ERROR: - return StorageOperationStatus.HTTP_PROTOCOL_ERROR; - case DB_NOT_AVAILABLE: - return StorageOperationStatus.STORAGE_NOT_AVAILABLE; - case DB_READ_ONLY: - return StorageOperationStatus.READ_ONLY_STORAGE; - case BAD_REQUEST: - return StorageOperationStatus.BAD_REQUEST; - case LEGACY_INDEX_ERROR: - return StorageOperationStatus.STORAGE_LEGACY_INDEX_ERROR; - case SCHEMA_ERROR: - return StorageOperationStatus.SCHEMA_ERROR; - case TRANSACTION_ERROR: - return StorageOperationStatus.TRANSACTION_ERROR; - case EXECUTION_FAILED: - return StorageOperationStatus.EXEUCTION_FAILED; - case ENTITY_ALREADY_EXIST: - return StorageOperationStatus.ENTITY_ALREADY_EXISTS; - case WRONG_INPUT: - return StorageOperationStatus.BAD_REQUEST; - case GENERAL_ERROR: - return StorageOperationStatus.GENERAL_ERROR; - case NOT_SUPPORTED: - return StorageOperationStatus.OPERATION_NOT_SUPPORTED; - case NOT_FOUND: - return StorageOperationStatus.NOT_FOUND; - - default: - return StorageOperationStatus.GENERAL_ERROR; - } - - } - -} 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 6772163b7f..2eeb55cc99 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 @@ -232,7 +232,13 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe } else { InRangeConstraint rangeConstraint = new InRangeConstraint(); String minValue = rangeArray.get(0).getAsString(); - String maxValue = rangeArray.get(1).getAsString(); + String maxValue; + JsonElement maxElement = rangeArray.get(1); + if(maxElement.isJsonNull()){ + maxValue = String.valueOf(maxElement.getAsJsonNull()); + } else { + maxValue = maxElement.getAsString(); + } rangeConstraint.setRangeMinValue(minValue); rangeConstraint.setRangeMaxValue(maxValue); propertyConstraint = rangeConstraint; @@ -288,24 +294,19 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe case VALID_VALUES: if (value != null) { - if (value instanceof JsonArray) { - JsonArray rangeArray = (JsonArray) value; - if (rangeArray.size() == 0) { - log.error("The valid values constraint content is invalid. value = {}", value); - } else { - ValidValuesConstraint vvConstraint = new ValidValuesConstraint(); - List<String> validValues = new ArrayList<>(); - for (JsonElement jsonElement : rangeArray) { - String item = jsonElement.getAsString(); - validValues.add(item); - } - vvConstraint.setValidValues(validValues); - propertyConstraint = vvConstraint; + JsonArray rangeArray = (JsonArray) value; + if (rangeArray.size() == 0) { + log.error("The valid values constraint content is invalid. value = {}", value); + } else { + ValidValuesConstraint vvConstraint = new ValidValuesConstraint(); + List<String> validValues = new ArrayList<>(); + for (JsonElement jsonElement : rangeArray) { + String item = jsonElement.getAsString(); + validValues.add(item); } + vvConstraint.setValidValues(validValues); + propertyConstraint = vvConstraint; } - - } else { - log.warn("The value of ValidValuesConstraint is null"); } break; 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 aa5ca81a31..07d5387576 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 @@ -74,12 +74,12 @@ public class UniqueIdBuilder { */ public static String getKeyByNodeType(NodeTypeEnum nodeTypeEnum) { - String key = nodeTypeToUniqueKeyMapper.get(nodeTypeEnum); - if (key == null) { - key = GraphPropertiesDictionary.UNIQUE_ID.getProperty(); + String uniqueID = nodeTypeToUniqueKeyMapper.get(nodeTypeEnum); + if (uniqueID == null) { + uniqueID = GraphPropertiesDictionary.UNIQUE_ID.getProperty(); } - return key; + return uniqueID; } public static String buildResourceUniqueId() { 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 bea9df9639..16073f4e3b 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 @@ -35,35 +35,39 @@ import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao; import org.openecomp.sdc.be.dao.utils.UserStatusEnum; import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.StorageException; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.resources.data.UserData; import org.openecomp.sdc.common.datastructure.Wrapper; +import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.util.MethodActivationStatusEnum; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.stereotype.Component; -import java.util.*; +import javax.validation.constraints.NotNull; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import static org.apache.commons.collections.CollectionUtils.isEmpty; -@Component("user-operation") -public class UserAdminOperation implements IUserAdminOperation { +@org.springframework.stereotype.Component +public class UserAdminOperation { - private JanusGraphGenericDao janusGraphGenericDao; + private final JanusGraphGenericDao janusGraphGenericDao; + private final ToscaOperationFacade toscaOperationFacade; - public UserAdminOperation(@Qualifier("janusgraph-generic-dao") - JanusGraphGenericDao janusGraphGenericDao) { - super(); + public UserAdminOperation(JanusGraphGenericDao janusGraphGenericDao, ToscaOperationFacade toscaOperationFacade) { this.janusGraphGenericDao = janusGraphGenericDao; - + this.toscaOperationFacade = toscaOperationFacade; } private static final Logger log = Logger.getLogger(UserAdminOperation.class.getName()); - @Override public Either<User, ActionStatus> getUserData(String id, boolean inTransaction) { return getUserData(id, true, inTransaction); } @@ -124,7 +128,7 @@ public class UserAdminOperation implements IUserAdminOperation { private void validateUserExists(Wrapper<Either<User, ActionStatus>> resultWrapper, Wrapper<UserData> userWrapper, String id) { if (id == null) { log.info("User userId is empty"); - resultWrapper.setInnerElement(Either.right(ActionStatus.MISSING_INFORMATION)); + resultWrapper.setInnerElement(Either.right(ActionStatus.MISSING_USER_ID)); return; } id = id.toLowerCase(); @@ -138,21 +142,19 @@ public class UserAdminOperation implements IUserAdminOperation { } } - @Override - public Either<User, StorageOperationStatus> saveUserData(User user) { + public User saveUserData(User user) { Either<UserData, JanusGraphOperationStatus> result = null; try { UserData userData = convertToUserData(user); result = janusGraphGenericDao.createNode(userData, UserData.class); if (result.isRight()) { - log.debug("Problem while saving User {}. Reason - {}", userData.getUserId(), result.right().value()); - return Either.right(StorageOperationStatus.GENERAL_ERROR); + log.error("Problem while saving User {}. Reason - {}", userData.getUserId(), result.right().value()); + throw new StorageException(StorageOperationStatus.GENERAL_ERROR); } log.debug("User {} saved successfully", userData.getUserId()); - return Either.left(convertToUser(result.left().value())); + return convertToUser(result.left().value()); } finally { - if (result == null || result.isRight()) { log.error("saveUserData - Failed"); janusGraphGenericDao.rollback(); @@ -163,24 +165,20 @@ public class UserAdminOperation implements IUserAdminOperation { } } - @Override - public Either<User, StorageOperationStatus> updateUserData(User user) { + public User updateUserData(User user) { Either<UserData, JanusGraphOperationStatus> result = null; try { log.debug("updateUserData - start"); UserData userData = convertToUserData(user); result = janusGraphGenericDao.updateNode(userData, UserData.class); if (result.isRight()) { - if (log.isDebugEnabled()) { - log.debug("Problem while updating User {}. Reason - {}", userData.toString(), result.right().value()); - } - return Either.right(StorageOperationStatus.GENERAL_ERROR); + log.error("Problem while updating User {}. Reason - {}", userData.toString(), result.right().value()); + throw new StorageException(StorageOperationStatus.GENERAL_ERROR); } log.debug("User {} updated successfully",userData.getUserId()); - return Either.left(convertToUser(result.left().value())); + return convertToUser(result.left().value()); } finally { - if (result == null || result.isRight()) { log.error("updateUserData - Failed"); janusGraphGenericDao.rollback(); @@ -192,20 +190,11 @@ public class UserAdminOperation implements IUserAdminOperation { } } - @Override - public Either<User, StorageOperationStatus> deActivateUser(User user) { - Either<User, StorageOperationStatus> result; + public User deActivateUser(User user) { user.setStatus(UserStatusEnum.INACTIVE); - Either<User, StorageOperationStatus> status = updateUserData(user); - if (status.isRight()) { - result = Either.right(status.right().value()); - } else { - result = Either.left(user); - } - return result; + return updateUserData(user); } - @Override public Either<User, ActionStatus> deleteUserData(String id) { Either<User, ActionStatus> result; Either<UserData, JanusGraphOperationStatus> eitherGet = janusGraphGenericDao @@ -269,34 +258,48 @@ public class UserAdminOperation implements IUserAdminOperation { } } - public Either<List<Edge>, StorageOperationStatus> getUserPendingTasksList(User user, Map<String, Object> properties) { + public @NotNull List<Edge> getUserPendingTasksList(User user, List<Object> states) { + + JanusGraphVertex userVertex = janusGraphGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), user.getUserId()) + .left() + .on(this::handleJanusGraphError); - Either<JanusGraphVertex, JanusGraphOperationStatus> vertexUser = janusGraphGenericDao - .getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), user.getUserId()); - if (vertexUser.isRight()) { - JanusGraphOperationStatus tos = vertexUser.right().value(); - log.debug("Failed to get User {} from graph while retrieving pending tasks. Reason - {}", user.getUserId(), tos); - return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(tos)); - } List<Edge> pendingTasks = new ArrayList<>(); - Either<List<Edge>, JanusGraphOperationStatus> edges = janusGraphGenericDao - .getOutgoingEdgesByCriteria(vertexUser.left().value(), GraphEdgeLabels.STATE, properties); - if (edges.isRight() || edges.left().value() == null) { - JanusGraphOperationStatus tos = edges.right().value(); - if (tos == JanusGraphOperationStatus.NOT_FOUND) { - return Either.left(pendingTasks); - } else { - log.debug("Failed while retrieving pending tasks for user {} . Reason - {}", user.getUserId(), tos); - return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(tos)); + for (Object state : states) { + Map<String, Object> property = new HashMap<>(); + property.put(GraphPropertiesDictionary.STATE.getProperty(), state); + List<Edge> edges = janusGraphGenericDao.getOutgoingEdgesByCriteria(userVertex, GraphEdgeLabels.STATE, property) + .left() + .on(this::handleJanusGraphError); + for (Edge edge : edges) { + Vertex vertex = edge.inVertex(); + if (!isComponentDeleted(vertex)) { + pendingTasks.add(edge); + } } } - for (Edge edge : edges.left().value()) { - if (!isComponentDeleted(edge.inVertex())) { - pendingTasks.add(edge); + logPendingTasks(user, pendingTasks); + return pendingTasks; + } + + public @NotNull List<Component> getUserActiveComponents(User user, List<Object> states) { + List<Component> components = new ArrayList<>(); + List<Edge> edges = getUserPendingTasksList(user, states); + for (Edge edge : edges) { + JanusGraphVertex componentVertex = (JanusGraphVertex) edge.inVertex(); + String componentId = (String) janusGraphGenericDao.getProperty(componentVertex, GraphPropertyEnum.UNIQUE_ID.getProperty()); + Either<Component, StorageOperationStatus> toscaFullElement = toscaOperationFacade.getToscaFullElement(componentId); + if (toscaFullElement.isLeft()) { + components.add(toscaFullElement.left().value()); + } else { + log.warn(EcompLoggerErrorCode.SCHEMA_ERROR, "", "", "Failed to retrieve component {} from graph db", componentId); } } - logPendingTasks(user, pendingTasks); - return Either.left(pendingTasks); + return components; + } + + private <T> T handleJanusGraphError(JanusGraphOperationStatus janusGraphOperationStatus) { + throw new StorageException(janusGraphOperationStatus); } private boolean isComponentDeleted(Vertex componentVertex) { @@ -318,7 +321,6 @@ public class UserAdminOperation implements IUserAdminOperation { } } - @Override public Either<List<User>, ActionStatus> getAllUsersWithRole(String role, String status) { try { Map<String, Object> propertiesToMatch = new HashMap<>(); 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 a0ff4bc09b..2f1372d8bd 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 @@ -30,7 +30,7 @@ import org.openecomp.sdc.be.model.tosca.validators.*; */ public enum ToscaPropertyType { - Root("tosca.datatypes.Root", null, null, null, true), + ROOT("tosca.datatypes.Root", null, null, null, true), STRING("string", StringValidator.getInstance(), StringConvertor.getInstance(), ToscaStringConvertor.getInstance()), @@ -84,42 +84,22 @@ public enum ToscaPropertyType { return type; } - public void setType(String type) { - this.type = type; - } - public PropertyTypeValidator getValidator() { return validator; } - public void setValidator(PropertyTypeValidator validator) { - this.validator = validator; - } - public PropertyValueConverter getConverter() { return converter; } - public void setConverter(PropertyValueConverter converter) { - this.converter = converter; - } - public boolean isAbstract() { return isAbstract; } - public void setAbstract(boolean isAbstract) { - this.isAbstract = isAbstract; - } - public ToscaValueConverter getValueConverter() { return valueConverter; } - public void setValueConverter(ToscaValueConverter valueConverter) { - this.valueConverter = valueConverter; - } - public static ToscaPropertyType isValidType(String typeName) { if (typeName == null) { return null; diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaType.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaType.java index da1b3c4ce8..87ad62195f 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaType.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/ToscaType.java @@ -61,7 +61,7 @@ public enum ToscaType { return type; } - public ToscaType getToscaType(String typeName) { + public static ToscaType getToscaType(String typeName) { if (typeName == null) { return null; } @@ -220,8 +220,10 @@ public enum ToscaType { return name().toLowerCase(); } - public static boolean isCollectionType(String type) { - return ToscaPropertyType.MAP.getType().equals(type) - || ToscaPropertyType.LIST.getType().equals(type); - } + public static boolean isCollectionType(String type) { + return ToscaPropertyType.MAP.getType().equals(type) + || ToscaPropertyType.LIST.getType().equals(type); + } + + } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/ConstraintType.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/ConstraintType.java index d1cc766525..bce2a41b98 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/ConstraintType.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/ConstraintType.java @@ -27,7 +27,7 @@ public enum ConstraintType { EQUAL("equal", "equal"), - IN_RANGE("inRange","in_range"), + IN_RANGE("inRange", "in_range"), GREATER_THAN("greaterThan", "greater_than"), diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/EqualConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/EqualConstraint.java index 206fc3dc82..01d9d3b252 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/EqualConstraint.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/EqualConstraint.java @@ -20,12 +20,13 @@ package org.openecomp.sdc.be.model.tosca.constraints; +import org.openecomp.sdc.be.model.PropertyConstraint; import java.io.Serializable; - import org.openecomp.sdc.be.model.tosca.ToscaType; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintFunctionalException; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintValueDoNotMatchPropertyTypeException; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintViolationException; +import org.openecomp.sdc.be.model.tosca.constraints.exception.PropertyConstraintException; import javax.validation.constraints.NotNull; @@ -71,6 +72,16 @@ public class EqualConstraint extends AbstractPropertyConstraint implements Seria } } + @Override + public ConstraintType getConstraintType() { + return null; + } + + @Override + public void validateValueOnUpdate(PropertyConstraint newConstraint) throws PropertyConstraintException { + + } + private void fail(Object propertyValue) throws ConstraintViolationException { throw new ConstraintViolationException("Equal constraint violation, the reference is <" + constraintValue + "> but the value to compare is <" + propertyValue + ">"); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/GreaterOrEqualConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/GreaterOrEqualConstraint.java index 6549bbc432..2b23445452 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/GreaterOrEqualConstraint.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/GreaterOrEqualConstraint.java @@ -20,10 +20,12 @@ package org.openecomp.sdc.be.model.tosca.constraints; +import org.openecomp.sdc.be.model.PropertyConstraint; import org.openecomp.sdc.be.model.tosca.ToscaType; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintFunctionalException; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintValueDoNotMatchPropertyTypeException; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintViolationException; +import org.openecomp.sdc.be.model.tosca.constraints.exception.PropertyConstraintException; import javax.validation.constraints.NotNull; @@ -42,6 +44,16 @@ public class GreaterOrEqualConstraint extends AbstractComparablePropertyConstrai } @Override + public ConstraintType getConstraintType() { + return ConstraintType.GREATER_OR_EQUAL; + } + + @Override + public void validateValueOnUpdate(PropertyConstraint newConstraint) throws PropertyConstraintException { + + } + + @Override protected void doValidate(Object propertyValue) throws ConstraintViolationException { if (getComparable().compareTo(propertyValue) > 0) { throw new ConstraintViolationException(propertyValue + " <= " + greaterOrEqual); @@ -52,4 +64,13 @@ public class GreaterOrEqualConstraint extends AbstractComparablePropertyConstrai public String getErrorMessage(ToscaType toscaType, ConstraintFunctionalException e, String propertyName) { return getErrorMessage(toscaType, e, propertyName, "%f property value must be >= %f", greaterOrEqual); } + + public String getGreaterOrEqual() { + return greaterOrEqual; + } + + public void setGreaterOrEqual(String greaterOrEqual) { + this.greaterOrEqual = greaterOrEqual; + } + } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/GreaterThanConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/GreaterThanConstraint.java index a278e8c7b9..e5f0779ed1 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/GreaterThanConstraint.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/GreaterThanConstraint.java @@ -20,10 +20,12 @@ package org.openecomp.sdc.be.model.tosca.constraints; +import org.openecomp.sdc.be.model.PropertyConstraint; import org.openecomp.sdc.be.model.tosca.ToscaType; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintFunctionalException; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintValueDoNotMatchPropertyTypeException; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintViolationException; +import org.openecomp.sdc.be.model.tosca.constraints.exception.PropertyConstraintException; import javax.validation.constraints.NotNull; @@ -42,6 +44,16 @@ public class GreaterThanConstraint extends AbstractComparablePropertyConstraint } @Override + public ConstraintType getConstraintType() { + return ConstraintType.GREATER_THAN; + } + + @Override + public void validateValueOnUpdate(PropertyConstraint newConstraint) throws PropertyConstraintException { + + } + + @Override protected void doValidate(Object propertyValue) throws ConstraintViolationException { if (getComparable().compareTo(propertyValue) >= 0) { throw new ConstraintViolationException(propertyValue + " < " + greaterThan); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/InRangeConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/InRangeConstraint.java index ad3d3525d0..f9b27d4953 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/InRangeConstraint.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/InRangeConstraint.java @@ -21,13 +21,13 @@ package org.openecomp.sdc.be.model.tosca.constraints; import com.google.common.collect.Lists; - +import org.openecomp.sdc.be.model.PropertyConstraint; import java.util.List; - import org.openecomp.sdc.be.model.tosca.ToscaType; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintFunctionalException; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintValueDoNotMatchPropertyTypeException; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintViolationException; +import org.openecomp.sdc.be.model.tosca.constraints.exception.PropertyConstraintException; import javax.validation.constraints.NotNull; @@ -80,6 +80,16 @@ public class InRangeConstraint extends AbstractPropertyConstraint { } } + @Override + public ConstraintType getConstraintType() { + return ConstraintType.IN_RANGE; + } + + @Override + public void validateValueOnUpdate(PropertyConstraint newConstraint) throws PropertyConstraintException { + + } + @NotNull public String getRangeMinValue() { if (inRange != null) { diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LengthConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LengthConstraint.java index 0c5317b10b..4b1da0ca66 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LengthConstraint.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LengthConstraint.java @@ -20,12 +20,14 @@ package org.openecomp.sdc.be.model.tosca.constraints; +import org.openecomp.sdc.be.model.PropertyConstraint; +import org.openecomp.sdc.be.model.tosca.ToscaType; +import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintViolationException; +import org.openecomp.sdc.be.model.tosca.constraints.exception.PropertyConstraintException; import java.util.List; import java.util.Map; - -import org.openecomp.sdc.be.model.tosca.ToscaType; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintFunctionalException; -import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintViolationException; + import javax.validation.constraints.NotNull; @@ -65,6 +67,16 @@ public class LengthConstraint extends AbstractPropertyConstraint { } @Override + public ConstraintType getConstraintType() { + return null; + } + + @Override + public void validateValueOnUpdate(PropertyConstraint newConstraint) throws PropertyConstraintException { + + } + + @Override public String getErrorMessage(ToscaType toscaType, ConstraintFunctionalException e, String propertyName) { return getErrorMessage(toscaType, e, propertyName, "%s length must be %s", String.valueOf(length)); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LessOrEqualConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LessOrEqualConstraint.java index 3f085ec596..c5e252b032 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LessOrEqualConstraint.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LessOrEqualConstraint.java @@ -20,10 +20,12 @@ package org.openecomp.sdc.be.model.tosca.constraints; +import org.openecomp.sdc.be.model.PropertyConstraint; import org.openecomp.sdc.be.model.tosca.ToscaType; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintFunctionalException; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintValueDoNotMatchPropertyTypeException; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintViolationException; +import org.openecomp.sdc.be.model.tosca.constraints.exception.PropertyConstraintException; import javax.validation.constraints.NotNull; @@ -41,6 +43,16 @@ public class LessOrEqualConstraint extends AbstractComparablePropertyConstraint } @Override + public ConstraintType getConstraintType() { + return ConstraintType.LESS_OR_EQUAL; + } + + @Override + public void validateValueOnUpdate(PropertyConstraint newConstraint) throws PropertyConstraintException { + + } + + @Override protected void doValidate(Object propertyValue) throws ConstraintViolationException { if (getComparable().compareTo(propertyValue) < 0) { throw new ConstraintViolationException(propertyValue + " >= " + lessOrEqual); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LessThanConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LessThanConstraint.java index 01eb6cdc32..55f6774a7f 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LessThanConstraint.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/LessThanConstraint.java @@ -20,10 +20,12 @@ package org.openecomp.sdc.be.model.tosca.constraints; +import org.openecomp.sdc.be.model.PropertyConstraint; import org.openecomp.sdc.be.model.tosca.ToscaType; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintFunctionalException; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintValueDoNotMatchPropertyTypeException; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintViolationException; +import org.openecomp.sdc.be.model.tosca.constraints.exception.PropertyConstraintException; import javax.validation.constraints.NotNull; @@ -42,6 +44,16 @@ public class LessThanConstraint extends AbstractComparablePropertyConstraint { } @Override + public ConstraintType getConstraintType() { + return ConstraintType.LESS_THAN; + } + + @Override + public void validateValueOnUpdate(PropertyConstraint newConstraint) throws PropertyConstraintException { + + } + + @Override protected void doValidate(Object propertyValue) throws ConstraintViolationException { if (getComparable().compareTo(propertyValue) <= 0) { throw new ConstraintViolationException(propertyValue + " > " + lessThan); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/MaxLengthConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/MaxLengthConstraint.java index c8fef91ea6..e1ad08faea 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/MaxLengthConstraint.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/MaxLengthConstraint.java @@ -20,14 +20,17 @@ package org.openecomp.sdc.be.model.tosca.constraints; -import java.util.List; -import java.util.Map; + import org.openecomp.sdc.be.model.tosca.ToscaType; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintFunctionalException; +import org.openecomp.sdc.be.model.PropertyConstraint; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintViolationException; +import org.openecomp.sdc.be.model.tosca.constraints.exception.PropertyConstraintException; import javax.validation.constraints.NotNull; +import java.util.List; +import java.util.Map; public class MaxLengthConstraint extends AbstractPropertyConstraint { @@ -60,6 +63,18 @@ public class MaxLengthConstraint extends AbstractPropertyConstraint { this.maxLength = maxLength; } + + @Override + public ConstraintType getConstraintType() { + return null; + } + + @Override + public void validateValueOnUpdate(PropertyConstraint newConstraint) throws PropertyConstraintException { + + } + + @Override public void validate(Object propertyValue) throws ConstraintViolationException { if (propertyValue == null) { @@ -77,4 +92,5 @@ public class MaxLengthConstraint extends AbstractPropertyConstraint { public String getErrorMessage(ToscaType toscaType, ConstraintFunctionalException e, String propertyName) { return getErrorMessage(toscaType, e, propertyName, "%s maximum length must be [%s]", String.valueOf(maxLength)); } + } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/MinLengthConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/MinLengthConstraint.java index 4f55970d79..b4a4255041 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/MinLengthConstraint.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/MinLengthConstraint.java @@ -23,9 +23,11 @@ package org.openecomp.sdc.be.model.tosca.constraints; import java.util.List; import java.util.Map; +import org.openecomp.sdc.be.model.PropertyConstraint; import org.openecomp.sdc.be.model.tosca.ToscaType; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintFunctionalException; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintViolationException; +import org.openecomp.sdc.be.model.tosca.constraints.exception.PropertyConstraintException; import javax.validation.constraints.NotNull; @@ -61,6 +63,16 @@ public class MinLengthConstraint extends AbstractPropertyConstraint { } @Override + public ConstraintType getConstraintType() { + return ConstraintType.MIN_LENGTH; + } + + @Override + public void validateValueOnUpdate(PropertyConstraint newConstraint) throws PropertyConstraintException { + + } + + @Override public void validate(Object propertyValue) throws ConstraintViolationException { if (propertyValue == null) { throw new ConstraintViolationException("Value to validate is null"); @@ -75,4 +87,5 @@ public class MinLengthConstraint extends AbstractPropertyConstraint { public String getErrorMessage(ToscaType toscaType, ConstraintFunctionalException e, String propertyName) { return getErrorMessage(toscaType, e, propertyName, "%s minimum length must be [%s]", String.valueOf(minLength)); } + } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/PatternConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/PatternConstraint.java index d3644c578d..49e40cf9c2 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/PatternConstraint.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/PatternConstraint.java @@ -24,7 +24,9 @@ import java.util.regex.Pattern; import org.openecomp.sdc.be.model.tosca.ToscaType; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintFunctionalException; +import org.openecomp.sdc.be.model.PropertyConstraint; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintViolationException; +import org.openecomp.sdc.be.model.tosca.constraints.exception.PropertyConstraintException; import javax.validation.constraints.NotNull; @@ -48,8 +50,20 @@ public class PatternConstraint extends AbstractStringPropertyConstraint { } @Override + public ConstraintType getConstraintType() { + return null; + } + + @Override + public void validateValueOnUpdate(PropertyConstraint newConstraint) throws PropertyConstraintException { + + } + + @Override public String getErrorMessage(ToscaType toscaType, ConstraintFunctionalException e, String propertyName) { return getErrorMessage(toscaType, e, propertyName, "%s property value must match the regular expression %s", pattern); } + + } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/ValidValuesConstraint.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/ValidValuesConstraint.java index 1ddf9c9e0e..2ab0673cfe 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/ValidValuesConstraint.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/ValidValuesConstraint.java @@ -21,22 +21,26 @@ package org.openecomp.sdc.be.model.tosca.constraints; import com.google.common.collect.Sets; - -import java.util.List; -import java.util.Set; - import org.openecomp.sdc.be.model.tosca.ToscaType; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintFunctionalException; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintValueDoNotMatchPropertyTypeException; import org.openecomp.sdc.be.model.tosca.constraints.exception.ConstraintViolationException; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.PropertyConstraint; +import org.openecomp.sdc.be.model.tosca.constraints.exception.PropertyConstraintException; import javax.validation.constraints.NotNull; +import java.util.List; +import java.util.Set; +import static java.util.stream.Collectors.toList; + public class ValidValuesConstraint extends AbstractPropertyConstraint { @NotNull private List<String> validValues; private Set<Object> validValuesTyped; + private static final String PROPERTY_TYPE_IS = "> property type is <"; public ValidValuesConstraint(List<String> validValues) { this.validValues = validValues; @@ -55,13 +59,43 @@ public class ValidValuesConstraint extends AbstractPropertyConstraint { for (String value : validValues) { if (!propertyType.isValidValue(value)) { throw new ConstraintValueDoNotMatchPropertyTypeException("validValues constraint has invalid value <" - + value + "> property type is <" + propertyType.toString() + ">"); + + value + PROPERTY_TYPE_IS + propertyType.toString() + ">"); } else { validValuesTyped.add(propertyType.convert(value)); } } } + public void validateType(String propertyType) throws ConstraintValueDoNotMatchPropertyTypeException { + ToscaType toscaType= ToscaType.getToscaType(propertyType); + if(toscaType == null){ + throw new ConstraintValueDoNotMatchPropertyTypeException("validValues constraint has invalid values <" + + validValues.toString() + PROPERTY_TYPE_IS + propertyType + ">"); + } + if (validValues == null) { + throw new ConstraintValueDoNotMatchPropertyTypeException( + "validValues constraint has invalid value <> property type is <" + propertyType + ">"); + } + for (String value : validValues) { + if (!toscaType.isValidValue(value)) { + throw new ConstraintValueDoNotMatchPropertyTypeException("validValues constraint has invalid value <" + + value + PROPERTY_TYPE_IS + propertyType + ">"); + } + } + } + + @Override + public void validateValueOnUpdate(PropertyConstraint newConstraint) throws PropertyConstraintException { + if(newConstraint.getConstraintType() == getConstraintType()){ + if(!((ValidValuesConstraint)newConstraint).getValidValues().containsAll(validValues)){ + throw new PropertyConstraintException("Deletion of exists value is not permitted", null, null, ActionStatus.CANNOT_DELETE_VALID_VALUES, getConstraintType().name(), + validValues.stream() + .filter(v->!((ValidValuesConstraint)newConstraint).getValidValues().contains(v)) + .collect(toList()).toString()); + } + } + } + @Override public void validate(Object propertyValue) throws ConstraintViolationException { if (propertyValue == null) { @@ -81,8 +115,14 @@ public class ValidValuesConstraint extends AbstractPropertyConstraint { } @Override + public ConstraintType getConstraintType() { + return ConstraintType.VALID_VALUES; + } + + @Override public String getErrorMessage(ToscaType toscaType, ConstraintFunctionalException e, String propertyName) { return getErrorMessage(toscaType, e, propertyName, "%s valid value must be one of the following: [%s]", String.join(",", validValues)); } + } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/PropertyConstraintException.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/PropertyConstraintException.java new file mode 100644 index 0000000000..3fbf4dd3d4 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/constraints/exception/PropertyConstraintException.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2020 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.tosca.constraints.exception; + +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.tosca.constraints.ConstraintUtil; + +public class PropertyConstraintException extends ConstraintFunctionalException { + + private final ActionStatus actionStatus; + private final String[] params; + + public PropertyConstraintException(String message, Throwable cause, ConstraintUtil.ConstraintInformation constraintInformation, ActionStatus actionStatus, String... params) { + super(message, cause, constraintInformation); + this.actionStatus = actionStatus; + this.params = params; + } + + public ActionStatus getActionStatus() { + return actionStatus; + } + + public String[] getParams() { + return params.clone(); + } +} 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 b2237d0f35..187793ee0b 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 @@ -20,7 +20,6 @@ package org.openecomp.sdc.be.model.tosca.converters; -import org.onap.sdc.tosca.datatypes.model.ScalarUnitValidator; import org.openecomp.sdc.be.model.DataTypeDefinition; import java.math.BigDecimal; @@ -34,23 +33,17 @@ public class HeatNumberConverter implements PropertyValueConverter { return numberConverter; } - private final ScalarUnitValidator scalarUnitValidator = ScalarUnitValidator.getInstance(); - - private HeatNumberConverter() { } @Override public String convert(String original, String innerType, Map<String, DataTypeDefinition> dataTypes) { + if (original == null || original.isEmpty()) { return null; } - if (scalarUnitValidator.isScalarUnit(original)) { - return original; - } - return new BigDecimal(original).toPlainString(); } 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 f53d95ceaf..3be610ec53 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 @@ -20,6 +20,7 @@ package org.openecomp.sdc.be.model.tosca.converters; +import com.google.common.base.Strings; import com.google.gson.*; import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; @@ -64,7 +65,7 @@ public class MapConverter implements PropertyValueConverter { public Either<String, Boolean> convertWithErrorResult(String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { - if (value == null || value == "" || innerType == null) { + if (Strings.isNullOrEmpty(value) || innerType == null) { return Either.left(value); } 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 f0b3ca25b9..5bbd38e2ba 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 @@ -124,7 +124,7 @@ public class ToscaMapValueConverter extends ToscaValueBaseConverter implements T 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()); + log.debug("try convert element "); boolean scalar = false; String propType = null; ToscaValueConverter innerConverterProp = innerConverterFinal; @@ -155,7 +155,7 @@ public class ToscaMapValueConverter extends ToscaValueBaseConverter implements T public Object convertDataTypeToToscaObject(String innerType, Map<String, DataTypeDefinition> dataTypes, ToscaValueConverter innerConverter, final boolean isScalarF, JsonElement entryValue, boolean preserveEmptyValue) { Object convertedValue = null; if (isScalarF && entryValue.isJsonPrimitive()) { - log.debug("try convert scalar value {}", entryValue.getAsString()); + log.debug("try convert scalar value "); if (entryValue.getAsString() == null) { convertedValue = null; } else { 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 e57650b8a6..fd987e8c9c 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 @@ -102,7 +102,7 @@ public class ToscaValueBaseConverter { if (elementValue.isJsonPrimitive()) { jsonValue = json2JavaPrimitive(elementValue.getAsJsonPrimitive()); } else { - log.debug("not supported json type {} ", elementValue); + log.debug("not supported json type "); } } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatNumberValidator.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatNumberValidator.java index ec281c0618..0ae3f74c85 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatNumberValidator.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/validators/HeatNumberValidator.java @@ -20,29 +20,27 @@ package org.openecomp.sdc.be.model.tosca.validators; -import java.util.Map; -import org.onap.sdc.tosca.datatypes.model.ScalarUnitValidator; import org.openecomp.sdc.be.model.DataTypeDefinition; +import java.util.Map; + public class HeatNumberValidator implements PropertyTypeValidator { private static HeatNumberValidator numberValidator = new HeatNumberValidator(); - private final FloatValidator floatValidator = FloatValidator.getInstance(); - private final IntegerValidator integerValidator = IntegerValidator.getInstance(); - private final ScalarUnitValidator scalarUnitValidator = ScalarUnitValidator.getInstance(); + private static FloatValidator floatValidator = FloatValidator.getInstance(); + private static IntegerValidator integerValidator = IntegerValidator.getInstance(); public static HeatNumberValidator getInstance() { return numberValidator; } private HeatNumberValidator() { + } @Override - public boolean isValid(final String value, - final String innerType, - final Map<String, DataTypeDefinition> allDataTypes) { + public boolean isValid(String value, String innerType, Map<String, DataTypeDefinition> allDataTypes) { if (value == null || value.isEmpty()) { return true; @@ -53,15 +51,11 @@ public class HeatNumberValidator implements PropertyTypeValidator { valid = floatValidator.isValid(value, null, allDataTypes); } - if(!valid) { - valid = scalarUnitValidator.isScalarUnit(value); - } - return valid; } @Override - public boolean isValid(final String value, final String innerType) { + public boolean isValid(String value, String innerType) { return isValid(value, innerType, null); } } 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 ed40964614..ac2e6fee73 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 @@ -20,6 +20,7 @@ package org.openecomp.sdc.be.model.tosca.validators; +import com.google.common.base.Strings; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonParser; @@ -50,7 +51,7 @@ public class ListValidator implements PropertyTypeValidator { log.debug("Going to validate value {} with inner type {}", value, innerType); - if (value == null || value == "") { + if (Strings.isNullOrEmpty(value)) { return true; } if (innerType == null) { diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/version/ComparableVersion.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/version/ComparableVersion.java index e3d8cf06f6..b0adb52919 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/version/ComparableVersion.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/tosca/version/ComparableVersion.java @@ -190,6 +190,8 @@ public class ComparableVersion implements Comparable<ComparableVersion> { case 'm': value = "milestone"; break; + default: + throw new RuntimeException("Invalid item"); } } this.value = ALIASES.getProperty(value, value); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/utils/ComponentUtilities.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/utils/ComponentUtilities.java index 664edaf2a4..7449ca4193 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/utils/ComponentUtilities.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/utils/ComponentUtilities.java @@ -54,6 +54,6 @@ public class ComponentUtilities { } public static boolean isNotUpdatedCapReqName(String prefix, String currName, String previousName) { - return StringUtils.isEmpty(previousName) || !currName.equals(prefix + previousName); + return StringUtils.isEmpty(previousName) || StringUtils.isEmpty(currName) || !currName.equals(prefix + previousName); } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/utils/GroupUtils.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/utils/GroupUtils.java index 33fd869b9a..7b396cbdda 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/utils/GroupUtils.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/utils/GroupUtils.java @@ -20,11 +20,66 @@ package org.openecomp.sdc.be.model.utils; +import org.openecomp.sdc.be.datatypes.enums.PromoteVersionEnum; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaElementLifecycleOperation; import org.openecomp.sdc.common.api.Constants; +import org.springframework.util.StringUtils; public class GroupUtils { public static boolean isVfModule(String type) { return type.equals(Constants.DEFAULT_GROUP_VF_MODULE); } + + /** + * The version of the group/poloces is an integer. In order to support BC, we might get a version in a float format. + * + * @param promoteVersion + * @return + */ + + public static String updateVersion(PromoteVersionEnum promoteVersion, String currentVesion) { + if(StringUtils.isEmpty(currentVesion)){ + return "0.0"; + } + String newVersion = currentVesion; + switch (promoteVersion){ + case MINOR: + newVersion = GroupUtils.increaseMainorVersion(currentVesion); + break; + case MAJOR: + newVersion = GroupUtils.increaseMajorVersion(currentVesion); + break; + default: + break; + } + return newVersion; + } + + private static String increaseMajorVersion(String version) { + + String[] versionParts = version.split(ToscaElementLifecycleOperation.VERSION_DELIMITER_REGEXP); + Integer majorVersion = Integer.parseInt(versionParts[0]); + + + Integer mainorVersion = versionParts.length > 1?Integer.parseInt(versionParts[1]):0; + + if(mainorVersion > 0 || majorVersion == 0){ + majorVersion++; + } + return String.valueOf(majorVersion); + + } + + private static String increaseMainorVersion(String version) { + + String[] versionParts = version.split(ToscaElementLifecycleOperation.VERSION_DELIMITER_REGEXP); + + Integer mainorVersion = versionParts.length > 1?Integer.parseInt(versionParts[1]):0; + + mainorVersion++; + + return versionParts[0] + ToscaElementLifecycleOperation.VERSION_DELIMITER + String.valueOf(mainorVersion); + + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiLeftPaletteComponent.java b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiLeftPaletteComponent.java new file mode 100644 index 0000000000..b0b01fad4e --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiLeftPaletteComponent.java @@ -0,0 +1,147 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2020 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.ui.model; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.common.util.ICategorizedElement; + +import java.util.List; + +public class UiLeftPaletteComponent implements ICategorizedElement { + private String uniqueId; + private String name; // archiveName + private String version; // archiveVersion + private String description; + private List<String> tags; + private String icon; + private String UUID; + private String systemName; + private String invariantUUID; + private ComponentTypeEnum componentType; + private String resourceType; + private String categoryName; + private String subCategoryName; + private String searchFilterTerms; + private List<CategoryDefinition> categories; + + public UiLeftPaletteComponent(Component component) { + this.uniqueId = component.getUniqueId(); + this.name = component.getName(); + this.version = component.getVersion(); + this.description = component.getDescription(); + this.tags = component.getTags(); + this.icon = component.getIcon(); + this.UUID = component.getUUID(); + this.systemName = component.getSystemName(); + this.invariantUUID = component.getInvariantUUID(); + this.componentType = component.getComponentType(); + this.resourceType = component.getActualComponentType(); + this.categories = component.getCategories(); + this.categoryName = getCategoryName(); + this.subCategoryName = getSubcategoryName(); + String tagString = convertListResultToString(tags); + setSearchFilterTerms(name + " " + description + " " + tagString + version); + this.searchFilterTerms = getSearchFilterTerms(); + } + + private String convertListResultToString(List<String> tags) { + StringBuilder sb = new StringBuilder(); + tags.forEach(t->sb.append(t + " ")); + return sb.toString().toLowerCase(); + } + + public String getUniqueId() { + return uniqueId; + } + + public String getName() { + return name; + } + + public String getVersion() { + return version; + } + + public String getDescription() { + return description; + } + + public List<String> getTags() { + return tags; + } + public String getIcon() { + return icon; + } + + public String getUUID() { + return UUID; + } + + public String getSystemName() { + return systemName; + } + + public String getInvariantUUID() { + return invariantUUID; + } + + public ComponentTypeEnum getComponentType() { + return componentType; + } + + public String getResourceType() { + return resourceType; + } + + public List<CategoryDefinition> getCategories() { + return categories; + } + + public String getSearchFilterTerms() { + return searchFilterTerms; + } + + public void setSearchFilterTerms(String searchFilterTerms) { + this.searchFilterTerms = searchFilterTerms; + } + + @JsonIgnore + @Override + public String getComponentTypeAsString() { + return getComponentType().name(); + } + + @JsonIgnore + public String getCategoryName() { + return getCategories().get(0).getName(); + } + + @JsonIgnore + public String getSubcategoryName() { + if(componentType == ComponentTypeEnum.SERVICE){ + return null; + } + return getCategories().get(0).getSubcategories().get(0).getName(); + } +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceMetadata.java b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceMetadata.java index 891ac1f5a8..454e970fd5 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceMetadata.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiServiceMetadata.java @@ -34,6 +34,7 @@ public class UiServiceMetadata extends UiComponentMetadata { private String serviceRole; private String environmentContext; private String instantiationType; + private String serviceFunction; public UiServiceMetadata(List<CategoryDefinition> categories, ServiceMetadataDataDefinition metadata) { super(categories, metadata); @@ -44,6 +45,7 @@ public class UiServiceMetadata extends UiComponentMetadata { this.serviceRole = metadata.getServiceRole(); this.environmentContext = metadata.getEnvironmentContext(); this.instantiationType = metadata.getInstantiationType(); + this.serviceFunction = metadata.getServiceFunction(); } public String getDistributionStatus() { @@ -97,4 +99,12 @@ public class UiServiceMetadata extends UiComponentMetadata { public String getEnvironmentContext() { return environmentContext; } public void setEnvironmentContext(String environmentContext) { this.environmentContext = environmentContext; } + + public String getServiceFunction() { + return serviceFunction; + } + + public void setServiceFunction(String serviceFunction) { + this.serviceFunction = serviceFunction; + } } |