diff options
Diffstat (limited to 'catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl')
28 files changed, 8646 insertions, 8036 deletions
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 f0e4056663..b42581aee4 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 @@ -20,13 +20,12 @@ package org.openecomp.sdc.be.model.operations.impl; -import java.lang.reflect.Type; -import java.util.List; -import java.util.Map; -import java.util.function.Function; -import java.util.function.Supplier; -import java.util.stream.Collectors; - +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; +import com.google.gson.reflect.TypeToken; +import com.thinkaurelius.titan.core.TitanVertex; +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; @@ -51,331 +50,303 @@ 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.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonElement; -import com.google.gson.reflect.TypeToken; -import com.thinkaurelius.titan.core.TitanVertex; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.springframework.beans.factory.annotation.Autowired; -import fj.data.Either; +import java.lang.reflect.Type; +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; +import java.util.stream.Collectors; public abstract class AbstractOperation { - private static Logger log = LoggerFactory.getLogger(AbstractOperation.class.getName()); - @javax.annotation.Resource - protected TitanGenericDao titanGenericDao; - public static final String EMPTY_VALUE = null; - protected Gson gson = new Gson(); + private static final Logger log = Logger.getLogger(AbstractOperation.class.getName()); + + @Autowired + protected TitanGenericDao titanGenericDao; + + public static final String EMPTY_VALUE = null; + + protected Gson gson = new Gson(); + + @Autowired + protected ApplicationDataTypeCache applicationDataTypeCache; + + protected DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance(); + + protected <SomeData extends GraphNode, SomeDefenition> Either<SomeData, TitanOperationStatus> 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, TitanOperationStatus> eitherSomeData = titanGenericDao.createNode(someData, (Class<SomeData>) someData.getClass()); + + log.debug("After adding {} to graph. status is = {}", defName, eitherSomeData); + + if (eitherSomeData.isRight()) { + TitanOperationStatus 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); - @javax.annotation.Resource - protected ApplicationDataTypeCache applicationDataTypeCache; - - protected DataTypeValidatorConverter dataTypeValidatorConverter = DataTypeValidatorConverter.getInstance(); - - protected <SomeData extends GraphNode, SomeDefenition> Either<SomeData, TitanOperationStatus> 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, TitanOperationStatus> eitherSomeData = titanGenericDao.createNode(someData, (Class<SomeData>) someData.getClass()); - - log.debug("After adding {} to graph. status is = {}", defName, eitherSomeData); - - if (eitherSomeData.isRight()) { - TitanOperationStatus 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, TitanOperationStatus> eitherRelations = titanGenericDao.createRelation(uniqueIdData, eitherSomeData.left().value(), edgeType, null); - if (eitherRelations.isRight()) { - TitanOperationStatus 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> TitanOperationStatus addDefinitionToNodeType(TitanVertex 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<TitanVertex, TitanOperationStatus> eitherSomeData = titanGenericDao.createNode(someData); - - log.debug("After adding {} to graph. status is = {}", defName, eitherSomeData); - - if (eitherSomeData.isRight()) { - TitanOperationStatus operationStatus = eitherSomeData.right().value(); - log.error("Failed to add {} to graph. status is {}", defName, operationStatus); - return operationStatus; - } + Either<GraphRelation, TitanOperationStatus> eitherRelations = titanGenericDao.createRelation(uniqueIdData, eitherSomeData.left().value(), edgeType, null); + if (eitherRelations.isRight()) { + TitanOperationStatus 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()); + } - TitanOperationStatus relations = titanGenericDao.createEdge(vertex, eitherSomeData.left().value(), edgeType, null); - if (!relations.equals(TitanOperationStatus.OK)) { - TitanOperationStatus operationStatus = relations; - BeEcompErrorManager.getInstance().logInternalFlowError("AddDefinitionToNodeType", "Failed to associate" + nodeType.getName() + " " + nodeUniqueId + "to " + defName + "in graph. status is " + operationStatus, ErrorSeverity.ERROR); - return operationStatus; - } - return relations; - } + protected <SomeData extends GraphNode, SomeDefenition> TitanOperationStatus addDefinitionToNodeType(TitanVertex 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); - interface NodeElementFetcher<ElementDefinition> { - TitanOperationStatus findAllNodeElements(String nodeId, List<ElementDefinition> listTofill); - } + SomeData someData = dataBuilder.get(); - public <ElementDefinition> TitanOperationStatus findAllResourceElementsDefinitionRecursively(String resourceId, List<ElementDefinition> elements, NodeElementFetcher<ElementDefinition> singleNodeFetcher) { + log.debug("Before adding {} to graph. data = {}", defName, someData); - if (log.isTraceEnabled()) - log.trace("Going to fetch elements under resource {}", resourceId); - TitanOperationStatus resourceAttributesStatus = singleNodeFetcher.findAllNodeElements(resourceId, elements); + @SuppressWarnings("unchecked") + Either<TitanVertex, TitanOperationStatus> eitherSomeData = titanGenericDao.createNode(someData); - if (resourceAttributesStatus != TitanOperationStatus.OK) { - return resourceAttributesStatus; - } + log.debug("After adding {} to graph. status is = {}", defName, eitherSomeData); - Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> parentNodes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource, - ResourceMetadataData.class); + if (eitherSomeData.isRight()) { + TitanOperationStatus operationStatus = eitherSomeData.right().value(); + log.error("Failed to add {} to graph. status is {}", defName, operationStatus); + return operationStatus; + } - if (parentNodes.isRight()) { - TitanOperationStatus parentNodesStatus = parentNodes.right().value(); - if (parentNodesStatus != TitanOperationStatus.NOT_FOUND) { - BeEcompErrorManager.getInstance().logInternalFlowError("findAllResourceElementsDefinitionRecursively", "Failed to find parent elements of resource " + resourceId + ". status is " + parentNodesStatus, ErrorSeverity.ERROR); - return parentNodesStatus; - } - } + TitanOperationStatus relations = titanGenericDao.createEdge(vertex, eitherSomeData.left().value(), edgeType, null); + if (!relations.equals(TitanOperationStatus.OK)) { + BeEcompErrorManager.getInstance().logInternalFlowError("AddDefinitionToNodeType", "Failed to associate" + nodeType.getName() + " " + nodeUniqueId + "to " + defName + "in graph. status is " + relations, ErrorSeverity.ERROR); + return relations; + } + return relations; + } - if (parentNodes.isLeft()) { - ImmutablePair<ResourceMetadataData, GraphEdge> parnetNodePair = parentNodes.left().value(); - String parentUniqueId = parnetNodePair.getKey().getMetadataDataDefinition().getUniqueId(); - TitanOperationStatus addParentIntStatus = findAllResourceElementsDefinitionRecursively(parentUniqueId, elements, singleNodeFetcher); - - if (addParentIntStatus != TitanOperationStatus.OK) { - BeEcompErrorManager.getInstance().logInternalFlowError("findAllResourceElementsDefinitionRecursively", "Failed to find all resource elements of resource " + parentUniqueId, ErrorSeverity.ERROR); + interface NodeElementFetcher<ElementDefinition> { + TitanOperationStatus findAllNodeElements(String nodeId, List<ElementDefinition> listTofill); + } - return addParentIntStatus; - } - } - return TitanOperationStatus.OK; - } + public <ElementDefinition> TitanOperationStatus findAllResourceElementsDefinitionRecursively(String resourceId, List<ElementDefinition> elements, NodeElementFetcher<ElementDefinition> singleNodeFetcher) { - protected <T, TStatus> void handleTransactionCommitRollback(boolean inTransaction, Either<T, TStatus> result) { - if (!inTransaction) { - if (result == null || result.isRight()) { - log.error("Going to execute rollback on graph."); - titanGenericDao.rollback(); - } else { - log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } + if (log.isTraceEnabled()) + log.trace("Going to fetch elements under resource {}", resourceId); + TitanOperationStatus resourceAttributesStatus = singleNodeFetcher.findAllNodeElements(resourceId, elements); - public <ElementTypeDefinition> Either<ElementTypeDefinition, StorageOperationStatus> getElementType(Function<String, Either<ElementTypeDefinition, TitanOperationStatus>> elementGetter, String uniqueId, boolean inTransaction) { - Either<ElementTypeDefinition, StorageOperationStatus> result = null; - try { - - Either<ElementTypeDefinition, TitanOperationStatus> ctResult = elementGetter.apply(uniqueId); + if (resourceAttributesStatus != TitanOperationStatus.OK) { + return resourceAttributesStatus; + } - if (ctResult.isRight()) { - TitanOperationStatus status = ctResult.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { - log.error("Failed to retrieve information on element uniqueId: {}. status is {}", uniqueId, status); - } - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(ctResult.right().value())); - return result; - } + Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> parentNodes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource, + ResourceMetadataData.class); - result = Either.left(ctResult.left().value()); + if (parentNodes.isRight()) { + TitanOperationStatus parentNodesStatus = parentNodes.right().value(); + if (parentNodesStatus != TitanOperationStatus.NOT_FOUND) { + BeEcompErrorManager.getInstance().logInternalFlowError("findAllResourceElementsDefinitionRecursively", "Failed to find parent elements of resource " + resourceId + ". status is " + parentNodesStatus, ErrorSeverity.ERROR); + return parentNodesStatus; + } + } - return result; - } finally { - handleTransactionCommitRollback(inTransaction, result); + if (parentNodes.isLeft()) { + ImmutablePair<ResourceMetadataData, GraphEdge> parnetNodePair = parentNodes.left().value(); + String parentUniqueId = parnetNodePair.getKey().getMetadataDataDefinition().getUniqueId(); + TitanOperationStatus addParentIntStatus = findAllResourceElementsDefinitionRecursively(parentUniqueId, elements, singleNodeFetcher); - } + if (addParentIntStatus != TitanOperationStatus.OK) { + BeEcompErrorManager.getInstance().logInternalFlowError("findAllResourceElementsDefinitionRecursively", "Failed to find all resource elements of resource " + parentUniqueId, ErrorSeverity.ERROR); - } + return addParentIntStatus; + } + } + return TitanOperationStatus.OK; + } - /** - * @param propertyDefinition - * @return - */ + protected <T, TStatus> void handleTransactionCommitRollback(boolean inTransaction, Either<T, TStatus> result) { + if (!inTransaction) { + if (result == null || result.isRight()) { + log.error("Going to execute rollback on graph."); + titanGenericDao.rollback(); + } else { + log.debug("Going to execute commit on graph."); + titanGenericDao.commit(); + } + } + } - protected StorageOperationStatus validateAndUpdateProperty(IComplexDefaultValue propertyDefinition, Map<String, DataTypeDefinition> dataTypes) { - log.trace("Going to validate property type and value. {}", propertyDefinition); + /** + * @param propertyDefinition + * @return + */ - String propertyType = propertyDefinition.getType(); - String value = propertyDefinition.getDefaultValue(); + protected StorageOperationStatus validateAndUpdateProperty(IComplexDefaultValue propertyDefinition, Map<String, DataTypeDefinition> dataTypes) { - ToscaPropertyType type = getType(propertyType); + log.trace("Going to validate property type and value. {}", propertyDefinition); - if (type == null) { + String propertyType = propertyDefinition.getType(); + String value = propertyDefinition.getDefaultValue(); - DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType); - if (dataTypeDefinition == null) { - log.debug("The type {} of property cannot be found.", propertyType); - return StorageOperationStatus.INVALID_TYPE; - } + ToscaPropertyType type = getType(propertyType); - StorageOperationStatus status = validateAndUpdateComplexValue(propertyDefinition, propertyType, value, dataTypeDefinition, dataTypes); + if (type == null) { - return status; + DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType); + if (dataTypeDefinition == null) { + log.debug("The type {} of property cannot be found.", propertyType); + return StorageOperationStatus.INVALID_TYPE; + } - } - String innerType = null; + return validateAndUpdateComplexValue(propertyDefinition, propertyType, value, dataTypeDefinition, dataTypes); - Either<String, TitanOperationStatus> checkInnerType = getInnerType(type, () -> propertyDefinition.getSchema()); - if (checkInnerType.isRight()) { - return StorageOperationStatus.INVALID_TYPE; - } - innerType = checkInnerType.left().value(); + } + String innerType = null; - log.trace("After validating property type {}", propertyType); + Either<String, TitanOperationStatus> checkInnerType = getInnerType(type, propertyDefinition::getSchema); + if (checkInnerType.isRight()) { + return StorageOperationStatus.INVALID_TYPE; + } + innerType = checkInnerType.left().value(); - boolean isValidProperty = isValidValue(type, value, innerType, dataTypes); - if (false == isValidProperty) { - log.info("The value {} of property from type {} is invalid", value, type); - return StorageOperationStatus.INVALID_VALUE; - } + log.trace("After validating property type {}", propertyType); - PropertyValueConverter converter = type.getConverter(); + boolean isValidProperty = isValidValue(type, value, innerType, dataTypes); + if (!isValidProperty) { + log.info("The value {} of property from type {} is invalid", value, type); + return StorageOperationStatus.INVALID_VALUE; + } - if (isEmptyValue(value)) { - log.debug("Default value was not sent for property {}. Set default value to {}", propertyDefinition.getName(), EMPTY_VALUE); - propertyDefinition.setDefaultValue(EMPTY_VALUE); - } else if (false == isEmptyValue(value)) { - String convertedValue = converter.convert(value, innerType, dataTypes); - propertyDefinition.setDefaultValue(convertedValue); - } - return StorageOperationStatus.OK; - } + PropertyValueConverter converter = type.getConverter(); - protected ToscaPropertyType getType(String propertyType) { + if (isEmptyValue(value)) { + log.debug("Default value was not sent for property {}. Set default value to {}", propertyDefinition.getName(), EMPTY_VALUE); + propertyDefinition.setDefaultValue(EMPTY_VALUE); + } else if (!isEmptyValue(value)) { + String convertedValue = converter.convert(value, innerType, dataTypes); + propertyDefinition.setDefaultValue(convertedValue); + } + return StorageOperationStatus.OK; + } - ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); + protected ToscaPropertyType getType(String propertyType) { - return type; + return ToscaPropertyType.isValidType(propertyType); - } + } - protected boolean isValidValue(ToscaPropertyType type, String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { - if (isEmptyValue(value)) { - return true; - } + protected boolean isValidValue(ToscaPropertyType type, String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { + if (isEmptyValue(value)) { + return true; + } - PropertyTypeValidator validator = type.getValidator(); + PropertyTypeValidator validator = type.getValidator(); - return validator.isValid(value, innerType, dataTypes); - } + return validator.isValid(value, innerType, dataTypes); + } - public boolean isEmptyValue(String value) { - return value == null; - } + public boolean isEmptyValue(String value) { + return value == null; + } - public boolean isNullParam(String value) { - return value == null; - } + public boolean isNullParam(String value) { + return value == null; + } - protected StorageOperationStatus validateAndUpdateComplexValue(IComplexDefaultValue propertyDefinition, String propertyType, + protected StorageOperationStatus validateAndUpdateComplexValue(IComplexDefaultValue propertyDefinition, String propertyType, - String value, DataTypeDefinition dataTypeDefinition, Map<String, DataTypeDefinition> dataTypes) { + String value, DataTypeDefinition dataTypeDefinition, Map<String, DataTypeDefinition> dataTypes) { - ImmutablePair<JsonElement, Boolean> validateResult = dataTypeValidatorConverter.validateAndUpdate(value, dataTypeDefinition, dataTypes); + ImmutablePair<JsonElement, Boolean> validateResult = dataTypeValidatorConverter.validateAndUpdate(value, dataTypeDefinition, dataTypes); - if (validateResult.right.booleanValue() == false) { - log.debug("The value {} of property from type {} is invalid", propertyType, propertyType); - return StorageOperationStatus.INVALID_VALUE; - } + if (!validateResult.right.booleanValue()) { + log.debug("The value {} of property from type {} is invalid", propertyType, propertyType); + return StorageOperationStatus.INVALID_VALUE; + } - JsonElement jsonElement = validateResult.left; + JsonElement jsonElement = validateResult.left; - log.trace("Going to update value in property definition {} {}" , propertyDefinition.getName() , (jsonElement != null ? jsonElement.toString() : null)); + log.trace("Going to update value in property definition {} {}" , propertyDefinition.getName() , (jsonElement != null ? jsonElement.toString() : null)); - updateValue(propertyDefinition, jsonElement); + updateValue(propertyDefinition, jsonElement); - return StorageOperationStatus.OK; - } + return StorageOperationStatus.OK; + } - protected void updateValue(IComplexDefaultValue propertyDefinition, JsonElement jsonElement) { + protected void updateValue(IComplexDefaultValue propertyDefinition, JsonElement jsonElement) { - propertyDefinition.setDefaultValue(getValueFromJsonElement(jsonElement)); + propertyDefinition.setDefaultValue(getValueFromJsonElement(jsonElement)); - } + } - protected String getValueFromJsonElement(JsonElement jsonElement) { - String value = null; + protected String getValueFromJsonElement(JsonElement jsonElement) { + String value = null; - if (jsonElement == null || jsonElement.isJsonNull()) { - value = EMPTY_VALUE; - } else { - value = jsonElement.toString(); - } + if (jsonElement == null || jsonElement.isJsonNull()) { + value = EMPTY_VALUE; + } else { + value = jsonElement.toString(); + } - return value; - } + return value; + } - protected Either<String, TitanOperationStatus> getInnerType(ToscaPropertyType type, Supplier<SchemaDefinition> schemeGen) { - String innerType = null; - if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { + protected Either<String, TitanOperationStatus> getInnerType(ToscaPropertyType type, Supplier<SchemaDefinition> schemeGen) { + String innerType = null; + if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { - SchemaDefinition def = schemeGen.get();// propDataDef.getSchema(); - if (def == null) { - log.debug("Schema doesn't exists for property of type {}", type); - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); - } - PropertyDataDefinition propDef = def.getProperty(); - if (propDef == null) { - log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); - } - innerType = propDef.getType(); - } - return Either.left(innerType); - } + SchemaDefinition def = schemeGen.get(); + if (def == null) { + log.debug("Schema doesn't exists for property of type {}", type); + return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + } + PropertyDataDefinition propDef = def.getProperty(); + if (propDef == null) { + log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); + return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + } + innerType = propDef.getType(); + } + return Either.left(innerType); + } - /** - * Convert Constarint object to json in order to add it to the Graph - * - * @param constraints - * @return - */ - public List<String> convertConstraintsToString(List<PropertyConstraint> constraints) { + /** + * Convert Constarint object to json in order to add it to the Graph + * + * @param constraints + * @return + */ + public List<String> convertConstraintsToString(List<PropertyConstraint> constraints) { - if (constraints == null || constraints.isEmpty()) { - return null; - } + if (constraints == null || constraints.isEmpty()) { + return null; + } - return constraints.stream().map(gson::toJson).collect(Collectors.toList()); - } + return constraints.stream().map(gson::toJson).collect(Collectors.toList()); + } - public List<PropertyConstraint> convertConstraints(List<String> constraints) { + public List<PropertyConstraint> convertConstraints(List<String> constraints) { - if (constraints == null || constraints.isEmpty()) { - return null; - } + if (constraints == null || constraints.isEmpty()) { + return null; + } - Type constraintType = new TypeToken<PropertyConstraint>() { - }.getType(); + Type constraintType = new TypeToken<PropertyConstraint>() { + }.getType(); - Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create(); + Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create(); - return constraints.stream().map(c -> gson.fromJson(c, PropertyConstraint.class)).collect(Collectors.toList()); - } + return constraints.stream().map(c -> gson.fromJson(c, PropertyConstraint.class)).collect(Collectors.toList()); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AdditionalInformationOperation.java index 8f34b3207e..349ee289b7 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 @@ -20,12 +20,8 @@ package org.openecomp.sdc.be.model.operations.impl; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - +import com.thinkaurelius.titan.core.TitanVertex; +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.openecomp.sdc.be.config.BeEcompErrorManager; @@ -47,775 +43,776 @@ import org.openecomp.sdc.be.resources.data.AdditionalInfoParameterData; import org.openecomp.sdc.be.resources.data.ResourceMetadataData; import org.openecomp.sdc.be.resources.data.ServiceMetadataData; import org.openecomp.sdc.be.resources.data.UniqueIdData; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.stereotype.Component; -import com.thinkaurelius.titan.core.TitanVertex; - -import fj.data.Either; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; @Component("additional-information-operation") public class AdditionalInformationOperation implements IAdditionalInformationOperation { + private static final String GOING_TO_EXECUTE_COMMIT_ON_GRAPH = "Going to execute commit on graph."; + private static final String GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH = "Going to execute rollback on graph."; + private static final String ADDITIONAL_INFORMATION_OF = "additional information of "; public static final String EMPTY_VALUE = null; - public AdditionalInformationOperation() { - super(); - } - - private static Logger log = LoggerFactory.getLogger(AdditionalInformationOperation.class.getName()); - - @javax.annotation.Resource - private TitanGenericDao titanGenericDao; - - @Override - public Either<AdditionalInformationDefinition, TitanOperationStatus> addAdditionalInformationParameter(NodeTypeEnum nodeType, String componentId, String key, String value) { - - TitanOperationStatus verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId); - if (verifyNodeTypeVsComponent != TitanOperationStatus.OK) { - return Either.right(verifyNodeTypeVsComponent); - } - - Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, GraphEdgeLabels.ADDITIONAL_INFORMATION, - NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class); + public AdditionalInformationOperation() { + super(); + } + + private static final Logger log = Logger.getLogger(AdditionalInformationOperation.class.getName()); + + @javax.annotation.Resource + private TitanGenericDao titanGenericDao; + + @Override + public Either<AdditionalInformationDefinition, TitanOperationStatus> addAdditionalInformationParameter(NodeTypeEnum nodeType, String componentId, String key, String value) { + + TitanOperationStatus verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId); + if (verifyNodeTypeVsComponent != TitanOperationStatus.OK) { + return Either.right(verifyNodeTypeVsComponent); + } - if (getResult.isRight()) { - TitanOperationStatus status = getResult.right().value(); - return Either.right(status); - } + Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, GraphEdgeLabels.ADDITIONAL_INFORMATION, + NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class); - ImmutablePair<AdditionalInfoParameterData, GraphEdge> immutablePair = getResult.left().value(); - AdditionalInfoParameterData parameterData = immutablePair.getLeft(); - Map<String, String> parameters = parameterData.getParameters(); - if (parameters == null) { - parameters = new HashMap<String, String>(); - parameterData.setParameters(parameters); - } - Map<String, String> idToKey = parameterData.getIdToKey(); - if (idToKey == null) { - idToKey = new HashMap<String, String>(); - parameterData.setIdToKey(idToKey); - } + if (getResult.isRight()) { + TitanOperationStatus status = getResult.right().value(); + return Either.right(status); + } - Integer lastCreatedCounter = parameterData.getAdditionalInfoParameterDataDefinition().getLastCreatedCounter(); - lastCreatedCounter++; + ImmutablePair<AdditionalInfoParameterData, GraphEdge> immutablePair = getResult.left().value(); + AdditionalInfoParameterData parameterData = immutablePair.getLeft(); + Map<String, String> parameters = parameterData.getParameters(); + if (parameters == null) { + parameters = new HashMap<>(); + parameterData.setParameters(parameters); + } + Map<String, String> idToKey = parameterData.getIdToKey(); + if (idToKey == null) { + idToKey = new HashMap<>(); + parameterData.setIdToKey(idToKey); + } - if (parameters.containsKey(key)) { - log.debug("The key {} already exists under component {}", key, componentId); - return Either.right(TitanOperationStatus.ALREADY_EXIST); - } + Integer lastCreatedCounter = parameterData.getAdditionalInfoParameterDataDefinition().getLastCreatedCounter(); + lastCreatedCounter++; - idToKey.put(String.valueOf(lastCreatedCounter), key); - parameters.put(key, value); - parameterData.getAdditionalInfoParameterDataDefinition().setLastCreatedCounter(lastCreatedCounter); + if (parameters.containsKey(key)) { + log.debug("The key {} already exists under component {}", key, componentId); + return Either.right(TitanOperationStatus.ALREADY_EXIST); + } - Either<AdditionalInfoParameterData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(parameterData, AdditionalInfoParameterData.class); - - if (updateNode.isRight()) { - TitanOperationStatus status = updateNode.right().value(); - BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("UpdateAdditionalInformationParameter", "additional information of " + nodeType.getName() + " " + componentId, String.valueOf(status)); - return Either.right(status); - } + idToKey.put(String.valueOf(lastCreatedCounter), key); + parameters.put(key, value); + parameterData.getAdditionalInfoParameterDataDefinition().setLastCreatedCounter(lastCreatedCounter); - AdditionalInformationDefinition informationDefinition = createInformationDefinitionFromNode(componentId, parameters, idToKey, updateNode.left().value()); + Either<AdditionalInfoParameterData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(parameterData, AdditionalInfoParameterData.class); + + if (updateNode.isRight()) { + TitanOperationStatus status = updateNode.right().value(); + BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("UpdateAdditionalInformationParameter", ADDITIONAL_INFORMATION_OF + nodeType.getName() + " " + componentId, String.valueOf(status)); + return Either.right(status); + } - return Either.left(informationDefinition); + AdditionalInformationDefinition informationDefinition = createInformationDefinitionFromNode(componentId, parameters, idToKey, updateNode.left().value()); - } + return Either.left(informationDefinition); - @Override - public Either<AdditionalInformationDefinition, TitanOperationStatus> updateAdditionalInformationParameter(NodeTypeEnum nodeType, String componentId, String id, String key, String value) { + } - TitanOperationStatus verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId); - if (verifyNodeTypeVsComponent != TitanOperationStatus.OK) { - return Either.right(verifyNodeTypeVsComponent); - } + @Override + public Either<AdditionalInformationDefinition, TitanOperationStatus> updateAdditionalInformationParameter(NodeTypeEnum nodeType, String componentId, String id, String key, String value) { - Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, GraphEdgeLabels.ADDITIONAL_INFORMATION, - NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class); + TitanOperationStatus verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId); + if (verifyNodeTypeVsComponent != TitanOperationStatus.OK) { + return Either.right(verifyNodeTypeVsComponent); + } - if (getResult.isRight()) { - TitanOperationStatus status = getResult.right().value(); - return Either.right(status); - } + Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, GraphEdgeLabels.ADDITIONAL_INFORMATION, + NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class); - ImmutablePair<AdditionalInfoParameterData, GraphEdge> immutablePair = getResult.left().value(); - AdditionalInfoParameterData parameterData = immutablePair.getLeft(); - Map<String, String> parameters = parameterData.getParameters(); - Map<String, String> idToKey = parameterData.getIdToKey(); - if (idToKey == null || false == idToKey.containsKey(id)) { - return Either.right(TitanOperationStatus.INVALID_ID); - } + if (getResult.isRight()) { + TitanOperationStatus status = getResult.right().value(); + return Either.right(status); + } - String origKey = idToKey.get(id); + ImmutablePair<AdditionalInfoParameterData, GraphEdge> immutablePair = getResult.left().value(); + AdditionalInfoParameterData parameterData = immutablePair.getLeft(); + Map<String, String> parameters = parameterData.getParameters(); + Map<String, String> idToKey = parameterData.getIdToKey(); + if (idToKey == null || !idToKey.containsKey(id)) { + return Either.right(TitanOperationStatus.INVALID_ID); + } - if (false == origKey.equals(key)) { - if (parameters.containsKey(key)) { - log.debug("The key {} already exists", key); - return Either.right(TitanOperationStatus.ALREADY_EXIST); - } - String removed = parameters.remove(origKey); - log.trace("The key-value {} = {} was removed from additionalInformation", origKey, removed); - } - parameters.put(key, value); - idToKey.put(id, key); + String origKey = idToKey.get(id); - Either<AdditionalInfoParameterData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(parameterData, AdditionalInfoParameterData.class); + if (!origKey.equals(key)) { + if (parameters.containsKey(key)) { + log.debug("The key {} already exists", key); + return Either.right(TitanOperationStatus.ALREADY_EXIST); + } + String removed = parameters.remove(origKey); + log.trace("The key-value {} = {} was removed from additionalInformation", origKey, removed); + } + parameters.put(key, value); + idToKey.put(id, key); - if (updateNode.isRight()) { - TitanOperationStatus status = updateNode.right().value(); - BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("UpdateAdditionalInformationParameter", "additional information of resource " + componentId, String.valueOf(status)); - return Either.right(status); - } + Either<AdditionalInfoParameterData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(parameterData, AdditionalInfoParameterData.class); - AdditionalInformationDefinition informationDefinition = createInformationDefinitionFromNode(componentId, parameters, idToKey, updateNode.left().value()); + if (updateNode.isRight()) { + TitanOperationStatus status = updateNode.right().value(); + BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("UpdateAdditionalInformationParameter", "additional information of resource " + componentId, String.valueOf(status)); + return Either.right(status); + } - return Either.left(informationDefinition); + AdditionalInformationDefinition informationDefinition = createInformationDefinitionFromNode(componentId, parameters, idToKey, updateNode.left().value()); - } + return Either.left(informationDefinition); - @Override - public Either<AdditionalInformationDefinition, TitanOperationStatus> deleteAdditionalInformationParameter(NodeTypeEnum nodeType, String componentId, String id) { + } - TitanOperationStatus verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId); - if (verifyNodeTypeVsComponent != TitanOperationStatus.OK) { - return Either.right(verifyNodeTypeVsComponent); - } + @Override + public Either<AdditionalInformationDefinition, TitanOperationStatus> deleteAdditionalInformationParameter(NodeTypeEnum nodeType, String componentId, String id) { - Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, GraphEdgeLabels.ADDITIONAL_INFORMATION, - NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class); + TitanOperationStatus verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId); + if (verifyNodeTypeVsComponent != TitanOperationStatus.OK) { + return Either.right(verifyNodeTypeVsComponent); + } - if (getResult.isRight()) { - TitanOperationStatus status = getResult.right().value(); - return Either.right(status); - } + Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, GraphEdgeLabels.ADDITIONAL_INFORMATION, + NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class); - ImmutablePair<AdditionalInfoParameterData, GraphEdge> immutablePair = getResult.left().value(); - AdditionalInfoParameterData parameterData = immutablePair.getLeft(); - Map<String, String> parameters = parameterData.getParameters(); - Map<String, String> idToKey = parameterData.getIdToKey(); + if (getResult.isRight()) { + TitanOperationStatus status = getResult.right().value(); + return Either.right(status); + } - if (idToKey == null || false == idToKey.containsKey(id)) { - return Either.right(TitanOperationStatus.INVALID_ID); - } + ImmutablePair<AdditionalInfoParameterData, GraphEdge> immutablePair = getResult.left().value(); + AdditionalInfoParameterData parameterData = immutablePair.getLeft(); + Map<String, String> parameters = parameterData.getParameters(); + Map<String, String> idToKey = parameterData.getIdToKey(); - String key = idToKey.get(id); - String removedKey = idToKey.remove(id); - String removedValue = parameters.remove(key); - log.trace("The key-value {} = {} was removed from additionalInformation", removedKey, removedValue); + if (idToKey == null || !idToKey.containsKey(id)) { + return Either.right(TitanOperationStatus.INVALID_ID); + } - Either<AdditionalInfoParameterData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(parameterData, AdditionalInfoParameterData.class); + String key = idToKey.get(id); + String removedKey = idToKey.remove(id); + String removedValue = parameters.remove(key); + log.trace("The key-value {} = {} was removed from additionalInformation", removedKey, removedValue); - if (updateNode.isRight()) { - TitanOperationStatus status = updateNode.right().value(); - BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("DeleteAdditionalInformationParameter", "additional information of " + nodeType.getName() + " " + componentId, String.valueOf(status)); - return Either.right(status); - } + Either<AdditionalInfoParameterData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(parameterData, AdditionalInfoParameterData.class); - AdditionalInformationDefinition informationDefinition = createInformationDefinitionFromNode(componentId, parameters, idToKey, updateNode.left().value()); + if (updateNode.isRight()) { + TitanOperationStatus status = updateNode.right().value(); + BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("DeleteAdditionalInformationParameter", ADDITIONAL_INFORMATION_OF + nodeType.getName() + " " + componentId, String.valueOf(status)); + return Either.right(status); + } - return Either.left(informationDefinition); + AdditionalInformationDefinition informationDefinition = createInformationDefinitionFromNode(componentId, parameters, idToKey, updateNode.left().value()); - } + return Either.left(informationDefinition); - private AdditionalInformationDefinition createInformationDefinitionFromNode(String resourceId, Map<String, String> parameters, Map<String, String> idToKey, AdditionalInfoParameterData additionalInfoParameterData) { - AdditionalInfoParameterDataDefinition dataDefinition = additionalInfoParameterData.getAdditionalInfoParameterDataDefinition(); + } - AdditionalInformationDefinition informationDefinition = new AdditionalInformationDefinition(dataDefinition, resourceId, convertParameters(parameters, idToKey)); - return informationDefinition; - } + private AdditionalInformationDefinition createInformationDefinitionFromNode(String resourceId, Map<String, String> parameters, Map<String, String> idToKey, AdditionalInfoParameterData additionalInfoParameterData) { + AdditionalInfoParameterDataDefinition dataDefinition = additionalInfoParameterData.getAdditionalInfoParameterDataDefinition(); - private List<AdditionalInfoParameterInfo> convertParameters(Map<String, String> parameters, Map<String, String> idToKey) { + return new AdditionalInformationDefinition(dataDefinition, resourceId, convertParameters(parameters, idToKey)); + } - List<AdditionalInfoParameterInfo> list = new ArrayList<AdditionalInfoParameterInfo>(); + private List<AdditionalInfoParameterInfo> convertParameters(Map<String, String> parameters, Map<String, String> idToKey) { - if (parameters != null) { - for (Entry<String, String> idToKeyEntry : idToKey.entrySet()) { + List<AdditionalInfoParameterInfo> list = new ArrayList<>(); - String id = idToKeyEntry.getKey(); - String key = idToKeyEntry.getValue(); + if (parameters != null) { + for (Entry<String, String> idToKeyEntry : idToKey.entrySet()) { - String value = parameters.get(key); + String id = idToKeyEntry.getKey(); + String key = idToKeyEntry.getValue(); - AdditionalInfoParameterInfo parameterInfo = new AdditionalInfoParameterInfo(id, key, value); - list.add(parameterInfo); - } + String value = parameters.get(key); - } + AdditionalInfoParameterInfo parameterInfo = new AdditionalInfoParameterInfo(id, key, value); + list.add(parameterInfo); + } - return list; - } + } - @Override - public Either<AdditionalInfoParameterData, TitanOperationStatus> addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId) { + return list; + } - UniqueIdData from = new UniqueIdData(nodeType, componentId); + @Override + public Either<AdditionalInfoParameterData, TitanOperationStatus> addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId) { - String uniqueId = UniqueIdBuilder.buildAdditionalInformationUniqueId(componentId); - AdditionalInfoParameterDataDefinition additionalInfoParameterDataDefinition = new AdditionalInfoParameterDataDefinition(); - additionalInfoParameterDataDefinition.setUniqueId(uniqueId); + UniqueIdData from = new UniqueIdData(nodeType, componentId); - AdditionalInfoParameterData additionalInfoParameterData = new AdditionalInfoParameterData(additionalInfoParameterDataDefinition, new HashMap<String, String>(), new HashMap<String, String>()); + String uniqueId = UniqueIdBuilder.buildAdditionalInformationUniqueId(componentId); + AdditionalInfoParameterDataDefinition additionalInfoParameterDataDefinition = new AdditionalInfoParameterDataDefinition(); + additionalInfoParameterDataDefinition.setUniqueId(uniqueId); - Either<AdditionalInfoParameterData, TitanOperationStatus> createNode = titanGenericDao.createNode(additionalInfoParameterData, AdditionalInfoParameterData.class); - if (createNode.isRight()) { - TitanOperationStatus status = createNode.right().value(); - BeEcompErrorManager.getInstance().logBeFailedCreateNodeError("AddAdditionalInformationNode", uniqueId, String.valueOf(status)); - return Either.right(status); - } + AdditionalInfoParameterData additionalInfoParameterData = new AdditionalInfoParameterData(additionalInfoParameterDataDefinition, new HashMap<>(), new HashMap<>()); - AdditionalInfoParameterData to = createNode.left().value(); + Either<AdditionalInfoParameterData, TitanOperationStatus> createNode = titanGenericDao.createNode(additionalInfoParameterData, AdditionalInfoParameterData.class); + if (createNode.isRight()) { + TitanOperationStatus status = createNode.right().value(); + BeEcompErrorManager.getInstance().logBeFailedCreateNodeError("AddAdditionalInformationNode", uniqueId, String.valueOf(status)); + return Either.right(status); + } - Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(from, to, GraphEdgeLabels.ADDITIONAL_INFORMATION, null); - if (createRelation.isRight()) { - TitanOperationStatus status = createRelation.right().value(); - return Either.right(status); - } + AdditionalInfoParameterData to = createNode.left().value(); - return Either.left(to); - } + Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(from, to, GraphEdgeLabels.ADDITIONAL_INFORMATION, null); + if (createRelation.isRight()) { + TitanOperationStatus status = createRelation.right().value(); + return Either.right(status); + } - @Override - public Either<TitanVertex, TitanOperationStatus> addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId, TitanVertex metadataVertex) { + return Either.left(to); + } - String uniqueId = UniqueIdBuilder.buildAdditionalInformationUniqueId(componentId); - AdditionalInfoParameterDataDefinition additionalInfoParameterDataDefinition = new AdditionalInfoParameterDataDefinition(); - additionalInfoParameterDataDefinition.setUniqueId(uniqueId); + @Override + public Either<TitanVertex, TitanOperationStatus> addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId, TitanVertex metadataVertex) { - AdditionalInfoParameterData additionalInfoParameterData = new AdditionalInfoParameterData(additionalInfoParameterDataDefinition, new HashMap<String, String>(), new HashMap<String, String>()); + String uniqueId = UniqueIdBuilder.buildAdditionalInformationUniqueId(componentId); + AdditionalInfoParameterDataDefinition additionalInfoParameterDataDefinition = new AdditionalInfoParameterDataDefinition(); + additionalInfoParameterDataDefinition.setUniqueId(uniqueId); - Either<TitanVertex, TitanOperationStatus> createNode = titanGenericDao.createNode(additionalInfoParameterData); - if (createNode.isRight()) { - TitanOperationStatus status = createNode.right().value(); - BeEcompErrorManager.getInstance().logBeFailedCreateNodeError("AddAdditionalInformationNode", uniqueId, String.valueOf(status)); - return Either.right(status); - } + AdditionalInfoParameterData additionalInfoParameterData = new AdditionalInfoParameterData(additionalInfoParameterDataDefinition, new HashMap<>(), new HashMap<>()); - TitanVertex additionalInfoVertex = createNode.left().value(); + Either<TitanVertex, TitanOperationStatus> createNode = titanGenericDao.createNode(additionalInfoParameterData); + if (createNode.isRight()) { + TitanOperationStatus status = createNode.right().value(); + BeEcompErrorManager.getInstance().logBeFailedCreateNodeError("AddAdditionalInformationNode", uniqueId, String.valueOf(status)); + return Either.right(status); + } - TitanOperationStatus createRelation = titanGenericDao.createEdge(metadataVertex, additionalInfoVertex, GraphEdgeLabels.ADDITIONAL_INFORMATION, null); + TitanVertex additionalInfoVertex = createNode.left().value(); - if (!createRelation.equals(TitanOperationStatus.OK)) { - return Either.right(createRelation); - } - return Either.left(additionalInfoVertex); - } + TitanOperationStatus createRelation = titanGenericDao.createEdge(metadataVertex, additionalInfoVertex, GraphEdgeLabels.ADDITIONAL_INFORMATION, null); - public Either<AdditionalInformationDefinition, TitanOperationStatus> addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId, AdditionalInformationDefinition parameters) { + if (!createRelation.equals(TitanOperationStatus.OK)) { + return Either.right(createRelation); + } + return Either.left(additionalInfoVertex); + } - Either<AdditionalInfoParameterData, TitanOperationStatus> status = this.addAdditionalInformationNode(nodeType, componentId); + public Either<AdditionalInformationDefinition, TitanOperationStatus> addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId, AdditionalInformationDefinition parameters) { - if (status.isRight()) { - return Either.right(status.right().value()); - } + Either<AdditionalInfoParameterData, TitanOperationStatus> status = this.addAdditionalInformationNode(nodeType, componentId); - AdditionalInfoParameterData parameterData = status.left().value(); + if (status.isRight()) { + return Either.right(status.right().value()); + } - populateParameterNodeWithParameters(parameterData, parameters); + AdditionalInfoParameterData parameterData = status.left().value(); - Either<AdditionalInfoParameterData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(parameterData, AdditionalInfoParameterData.class); + populateParameterNodeWithParameters(parameterData, parameters); - if (updateNode.isRight()) { - return Either.right(updateNode.right().value()); - } + Either<AdditionalInfoParameterData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(parameterData, AdditionalInfoParameterData.class); - AdditionalInformationDefinition informationDefinition = convertAdditionalInformationDataToDefinition(updateNode.left().value(), componentId); + if (updateNode.isRight()) { + return Either.right(updateNode.right().value()); + } - return Either.left(informationDefinition); - } + AdditionalInformationDefinition informationDefinition = convertAdditionalInformationDataToDefinition(updateNode.left().value(), componentId); - public TitanOperationStatus addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId, AdditionalInformationDefinition parameters, TitanVertex metadataVertex) { + return Either.left(informationDefinition); + } - Either<TitanVertex, TitanOperationStatus> status = this.addAdditionalInformationNode(nodeType, componentId, metadataVertex); + public TitanOperationStatus addAdditionalInformationNode(NodeTypeEnum nodeType, String componentId, AdditionalInformationDefinition parameters, TitanVertex metadataVertex) { - if (status.isRight()) { - return status.right().value(); - } - TitanVertex additionalInfoVertex = status.left().value(); + Either<TitanVertex, TitanOperationStatus> status = this.addAdditionalInformationNode(nodeType, componentId, metadataVertex); - Map<String, Object> newProp = titanGenericDao.getProperties(additionalInfoVertex); - AdditionalInfoParameterData parameterData = GraphElementFactory.createElement(NodeTypeEnum.AdditionalInfoParameters.getName(), GraphElementTypeEnum.Node, newProp, AdditionalInfoParameterData.class); + if (status.isRight()) { + return status.right().value(); + } + TitanVertex additionalInfoVertex = status.left().value(); - populateParameterNodeWithParameters(parameterData, parameters); + Map<String, Object> newProp = titanGenericDao.getProperties(additionalInfoVertex); + AdditionalInfoParameterData parameterData = GraphElementFactory.createElement(NodeTypeEnum.AdditionalInfoParameters.getName(), GraphElementTypeEnum.Node, newProp, AdditionalInfoParameterData.class); - TitanOperationStatus updateNode = titanGenericDao.updateVertex(parameterData, additionalInfoVertex); + populateParameterNodeWithParameters(parameterData, parameters); - return updateNode; - } + return titanGenericDao.updateVertex(parameterData, additionalInfoVertex); + } - private void populateParameterNodeWithParameters(AdditionalInfoParameterData parameterData, AdditionalInformationDefinition aiDefinition) { + private void populateParameterNodeWithParameters(AdditionalInfoParameterData parameterData, AdditionalInformationDefinition aiDefinition) { - if (aiDefinition != null) { + if (aiDefinition != null) { - Integer lastCreatedCounter = aiDefinition.getLastCreatedCounter(); - parameterData.getAdditionalInfoParameterDataDefinition().setLastCreatedCounter(lastCreatedCounter); - log.trace("Set last created counter of additional information to {}", lastCreatedCounter); + Integer lastCreatedCounter = aiDefinition.getLastCreatedCounter(); + parameterData.getAdditionalInfoParameterDataDefinition().setLastCreatedCounter(lastCreatedCounter); + log.trace("Set last created counter of additional information to {}", lastCreatedCounter); - List<AdditionalInfoParameterInfo> parameters = aiDefinition.getParameters(); - if (parameters != null) { + List<AdditionalInfoParameterInfo> parameters = aiDefinition.getParameters(); + if (parameters != null) { - Map<String, String> idToKey = new HashMap<String, String>(); - Map<String, String> parametersMap = new HashMap<String, String>(); - for (AdditionalInfoParameterInfo additionalInfoParameterInfo : parameters) { - String uniqueId = additionalInfoParameterInfo.getUniqueId(); - String key = additionalInfoParameterInfo.getKey(); - String value = additionalInfoParameterInfo.getValue(); + Map<String, String> idToKey = new HashMap<>(); + Map<String, String> parametersMap = new HashMap<>(); + for (AdditionalInfoParameterInfo additionalInfoParameterInfo : parameters) { + String uniqueId = additionalInfoParameterInfo.getUniqueId(); + String key = additionalInfoParameterInfo.getKey(); + String value = additionalInfoParameterInfo.getValue(); - if (key != null && false == key.isEmpty()) { - idToKey.put(uniqueId, key); - parametersMap.put(key, value); - } - } - parameterData.setIdToKey(idToKey); - parameterData.setParameters(parametersMap); - } - } + if (key != null && !key.isEmpty()) { + idToKey.put(uniqueId, key); + parametersMap.put(key, value); + } + } + parameterData.setIdToKey(idToKey); + parameterData.setParameters(parametersMap); + } + } - } + } - @Override - public TitanOperationStatus findResourceAllAdditionalInformationRecursively(String uniqueId, List<AdditionalInformationDefinition> properties) { + @Override + public TitanOperationStatus findResourceAllAdditionalInformationRecursively(String uniqueId, List<AdditionalInformationDefinition> properties) { - log.trace("Going to fetch additional information under resource {}", uniqueId); - TitanOperationStatus resourceCapabilitiesStatus = findAdditionalInformationOfNode(NodeTypeEnum.Resource, uniqueId, properties); + log.trace("Going to fetch additional information under resource {}", uniqueId); + TitanOperationStatus resourceCapabilitiesStatus = findAdditionalInformationOfNode(NodeTypeEnum.Resource, uniqueId, properties); - if (!resourceCapabilitiesStatus.equals(TitanOperationStatus.OK)) { - return resourceCapabilitiesStatus; - } + if (!resourceCapabilitiesStatus.equals(TitanOperationStatus.OK)) { + return resourceCapabilitiesStatus; + } - Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> parentNodes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), uniqueId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource, - ResourceMetadataData.class); + Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> parentNodes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), uniqueId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource, + ResourceMetadataData.class); - if (parentNodes.isRight()) { - TitanOperationStatus parentNodesStatus = parentNodes.right().value(); - if (false == parentNodesStatus.equals(TitanOperationStatus.NOT_FOUND)) { - log.error("Failed to find parent additional information of resource {}. status is {}", uniqueId, parentNodesStatus); - return parentNodesStatus; - } - } + if (parentNodes.isRight()) { + TitanOperationStatus parentNodesStatus = parentNodes.right().value(); + if (!parentNodesStatus.equals(TitanOperationStatus.NOT_FOUND)) { + log.error("Failed to find parent additional information of resource {}. status is {}", uniqueId, parentNodesStatus); + return parentNodesStatus; + } + } - if (parentNodes.isLeft()) { - ImmutablePair<ResourceMetadataData, GraphEdge> parnetNodePair = parentNodes.left().value(); - String parentUniqueId = parnetNodePair.getKey().getMetadataDataDefinition().getUniqueId(); - TitanOperationStatus addParentIntStatus = findResourceAllAdditionalInformationRecursively(parentUniqueId, properties); + if (parentNodes.isLeft()) { + ImmutablePair<ResourceMetadataData, GraphEdge> parnetNodePair = parentNodes.left().value(); + String parentUniqueId = parnetNodePair.getKey().getMetadataDataDefinition().getUniqueId(); + TitanOperationStatus addParentIntStatus = findResourceAllAdditionalInformationRecursively(parentUniqueId, properties); - if (addParentIntStatus != TitanOperationStatus.OK) { - log.error("Failed to find all resource additional information of resource {}", parentUniqueId); - return addParentIntStatus; - } - } - return TitanOperationStatus.OK; + if (addParentIntStatus != TitanOperationStatus.OK) { + log.error("Failed to find all resource additional information of resource {}", parentUniqueId); + return addParentIntStatus; + } + } + return TitanOperationStatus.OK; - } + } - @Override - public TitanOperationStatus findServiceAllAdditionalInformationRecursively(String uniqueId, List<AdditionalInformationDefinition> properties) { + @Override + public TitanOperationStatus findServiceAllAdditionalInformationRecursively(String uniqueId, List<AdditionalInformationDefinition> properties) { - log.trace("Going to fetch additional information under service {}", uniqueId); - TitanOperationStatus resourceCapabilitiesStatus = findAdditionalInformationOfNode(NodeTypeEnum.Service, uniqueId, properties); + log.trace("Going to fetch additional information under service {}", uniqueId); + TitanOperationStatus resourceCapabilitiesStatus = findAdditionalInformationOfNode(NodeTypeEnum.Service, uniqueId, properties); - if (!resourceCapabilitiesStatus.equals(TitanOperationStatus.OK)) { - return resourceCapabilitiesStatus; - } + if (!resourceCapabilitiesStatus.equals(TitanOperationStatus.OK)) { + return resourceCapabilitiesStatus; + } - Either<ImmutablePair<ServiceMetadataData, GraphEdge>, TitanOperationStatus> parentNodes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Service), uniqueId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Service, - ServiceMetadataData.class); + Either<ImmutablePair<ServiceMetadataData, GraphEdge>, TitanOperationStatus> parentNodes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Service), uniqueId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Service, + ServiceMetadataData.class); - if (parentNodes.isRight()) { - TitanOperationStatus parentNodesStatus = parentNodes.right().value(); - if (false == parentNodesStatus.equals(TitanOperationStatus.NOT_FOUND)) { - log.error("Failed to find parent additional information of resource {}. status is {}", uniqueId, parentNodesStatus); - return parentNodesStatus; - } - } + if (parentNodes.isRight()) { + TitanOperationStatus parentNodesStatus = parentNodes.right().value(); + if (!parentNodesStatus.equals(TitanOperationStatus.NOT_FOUND)) { + log.error("Failed to find parent additional information of resource {}. status is {}", uniqueId, parentNodesStatus); + return parentNodesStatus; + } + } - if (parentNodes.isLeft()) { - ImmutablePair<ServiceMetadataData, GraphEdge> parnetNodePair = parentNodes.left().value(); - String parentUniqueId = parnetNodePair.getKey().getMetadataDataDefinition().getUniqueId(); - TitanOperationStatus addParentIntStatus = findServiceAllAdditionalInformationRecursively(parentUniqueId, properties); + if (parentNodes.isLeft()) { + ImmutablePair<ServiceMetadataData, GraphEdge> parnetNodePair = parentNodes.left().value(); + String parentUniqueId = parnetNodePair.getKey().getMetadataDataDefinition().getUniqueId(); + TitanOperationStatus addParentIntStatus = findServiceAllAdditionalInformationRecursively(parentUniqueId, properties); - if (addParentIntStatus != TitanOperationStatus.OK) { - log.error("Failed to find all resource additional information of resource {}", parentUniqueId); - return addParentIntStatus; - } - } - return TitanOperationStatus.OK; + if (addParentIntStatus != TitanOperationStatus.OK) { + log.error("Failed to find all resource additional information of resource {}", parentUniqueId); + return addParentIntStatus; + } + } + return TitanOperationStatus.OK; - } + } - private TitanOperationStatus findAdditionalInformationOfNode(NodeTypeEnum nodeType, String uniqueId, List<AdditionalInformationDefinition> properties) { + private TitanOperationStatus findAdditionalInformationOfNode(NodeTypeEnum nodeType, String uniqueId, List<AdditionalInformationDefinition> properties) { - Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> childNode = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, GraphEdgeLabels.ADDITIONAL_INFORMATION, - NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class); + Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> childNode = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, GraphEdgeLabels.ADDITIONAL_INFORMATION, + NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class); - if (childNode.isRight()) { - TitanOperationStatus status = childNode.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.OK; - } - return status; - } + if (childNode.isRight()) { + TitanOperationStatus status = childNode.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.OK; + } + return status; + } - ImmutablePair<AdditionalInfoParameterData, GraphEdge> immutablePair = childNode.left().value(); - AdditionalInfoParameterData propertyData = immutablePair.getKey(); + ImmutablePair<AdditionalInfoParameterData, GraphEdge> immutablePair = childNode.left().value(); + AdditionalInfoParameterData propertyData = immutablePair.getKey(); - Map<String, String> parameters = propertyData.getParameters(); - if (parameters != null && false == parameters.isEmpty()) { - AdditionalInformationDefinition additionalInfoDef = this.convertAdditionalInformationDataToDefinition(propertyData, uniqueId); - properties.add(additionalInfoDef); - } + Map<String, String> parameters = propertyData.getParameters(); + if (parameters != null && !parameters.isEmpty()) { + AdditionalInformationDefinition additionalInfoDef = this.convertAdditionalInformationDataToDefinition(propertyData, uniqueId); + properties.add(additionalInfoDef); + } - return TitanOperationStatus.OK; + return TitanOperationStatus.OK; - } + } - private AdditionalInformationDefinition convertAdditionalInformationDataToDefinition(AdditionalInfoParameterData additionalInfoData, String uniqueId) { + private AdditionalInformationDefinition convertAdditionalInformationDataToDefinition(AdditionalInfoParameterData additionalInfoData, String uniqueId) { - Map<String, String> parameters = additionalInfoData.getParameters(); - Map<String, String> idToKey = additionalInfoData.getIdToKey(); + Map<String, String> parameters = additionalInfoData.getParameters(); + Map<String, String> idToKey = additionalInfoData.getIdToKey(); - AdditionalInformationDefinition definition = new AdditionalInformationDefinition(additionalInfoData.getAdditionalInfoParameterDataDefinition(), uniqueId, convertParameters(parameters, idToKey)); - return definition; - } + 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) { + @Override + public Either<AdditionalInformationDefinition, StorageOperationStatus> createAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String key, String value, boolean inTransaction) { - Either<AdditionalInformationDefinition, StorageOperationStatus> result = null; + Either<AdditionalInformationDefinition, StorageOperationStatus> result = null; - try { + try { - Either<AdditionalInformationDefinition, TitanOperationStatus> either = this.addAdditionalInformationParameter(nodeType, resourceId, key, value); + Either<AdditionalInformationDefinition, TitanOperationStatus> either = this.addAdditionalInformationParameter(nodeType, resourceId, key, value); - if (either.isRight()) { - TitanOperationStatus status = either.right().value(); - log.debug("Failed to add additional information property {} to component {}. Status is {}", key, resourceId, status); - BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("CreateAdditionalInformationParameter", "additional information of " + nodeType.getName() + " " + resourceId, String.valueOf(status)); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } else { - AdditionalInformationDefinition additionalInformationDefinition = either.left().value(); - result = Either.left(additionalInformationDefinition); - } + if (either.isRight()) { + TitanOperationStatus status = either.right().value(); + log.debug("Failed to add additional information property {} to component {}. Status is {}", key, resourceId, status); + BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("CreateAdditionalInformationParameter", ADDITIONAL_INFORMATION_OF + nodeType.getName() + " " + resourceId, String.valueOf(status)); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } else { + AdditionalInformationDefinition additionalInformationDefinition = either.left().value(); + result = Either.left(additionalInformationDefinition); + } - return result; - } finally { - commitOrRollback(inTransaction, result); - } + return result; + } finally { + commitOrRollback(inTransaction, result); + } - } + } - @Override - public Either<AdditionalInformationDefinition, StorageOperationStatus> updateAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String id, String key, String value, boolean inTransaction) { + @Override + public Either<AdditionalInformationDefinition, StorageOperationStatus> updateAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String id, String key, String value, boolean inTransaction) { - Either<AdditionalInformationDefinition, StorageOperationStatus> result = null; + Either<AdditionalInformationDefinition, StorageOperationStatus> result = null; - try { + try { - Either<AdditionalInformationDefinition, TitanOperationStatus> either = this.updateAdditionalInformationParameter(nodeType, resourceId, id, key, value); + Either<AdditionalInformationDefinition, TitanOperationStatus> either = this.updateAdditionalInformationParameter(nodeType, resourceId, id, key, value); - if (either.isRight()) { - log.info("Failed to update additional information property {} to component {}", key, resourceId); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(either.right().value())); - } else { - AdditionalInformationDefinition additionalInformationDefinition = either.left().value(); - result = Either.left(additionalInformationDefinition); - } + if (either.isRight()) { + log.info("Failed to update additional information property {} to component {}", key, resourceId); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(either.right().value())); + } else { + AdditionalInformationDefinition additionalInformationDefinition = either.left().value(); + result = Either.left(additionalInformationDefinition); + } - return result; + return result; - } finally { - commitOrRollback(inTransaction, result); - } + } finally { + commitOrRollback(inTransaction, result); + } - } + } - @Override - public Either<AdditionalInformationDefinition, StorageOperationStatus> deleteAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String id, boolean inTransaction) { + @Override + public Either<AdditionalInformationDefinition, StorageOperationStatus> deleteAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String id, boolean inTransaction) { - Either<AdditionalInformationDefinition, StorageOperationStatus> result = null; + Either<AdditionalInformationDefinition, StorageOperationStatus> result = null; - try { + try { - Either<AdditionalInformationDefinition, TitanOperationStatus> either = this.deleteAdditionalInformationParameter(nodeType, resourceId, id); + Either<AdditionalInformationDefinition, TitanOperationStatus> either = this.deleteAdditionalInformationParameter(nodeType, resourceId, id); - if (either.isRight()) { - log.error("Failed to delete additional information id {} to component {}", id, resourceId); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(either.right().value())); - } else { - AdditionalInformationDefinition additionalInformationDefinition = either.left().value(); - result = Either.left(additionalInformationDefinition); - } + if (either.isRight()) { + log.error("Failed to delete additional information id {} to component {}", id, resourceId); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(either.right().value())); + } else { + AdditionalInformationDefinition additionalInformationDefinition = either.left().value(); + result = Either.left(additionalInformationDefinition); + } - return result; + return result; - } finally { - commitOrRollback(inTransaction, result); - } + } finally { + commitOrRollback(inTransaction, result); + } - } + } - @Override - public Either<Integer, StorageOperationStatus> getNumberOfAdditionalInformationParameters(NodeTypeEnum nodeType, String resourceId, boolean inTransaction) { + @Override + public Either<Integer, StorageOperationStatus> getNumberOfAdditionalInformationParameters(NodeTypeEnum nodeType, String resourceId, boolean inTransaction) { - Either<Integer, StorageOperationStatus> result = null; + Either<Integer, StorageOperationStatus> result = null; - try { + try { - Either<Integer, TitanOperationStatus> either = this.getNumberOfParameters(nodeType, resourceId); + Either<Integer, TitanOperationStatus> either = this.getNumberOfParameters(nodeType, resourceId); - if (either.isRight()) { - log.error("Failed to get the number of additional information properties in component {}", resourceId); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(either.right().value())); - } else { - Integer counter = either.left().value(); - result = Either.left(counter); - } + if (either.isRight()) { + log.error("Failed to get the number of additional information properties in component {}", resourceId); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(either.right().value())); + } else { + Integer counter = either.left().value(); + result = Either.left(counter); + } - return result; - } finally { - if (false == inTransaction) { - if (result == null || result.isRight()) { - log.error("Going to execute rollback on graph."); - titanGenericDao.rollback(); - } else { - log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } + return result; + } finally { + if (!inTransaction) { + if (result == null || result.isRight()) { + log.error(GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH); + titanGenericDao.rollback(); + } else { + log.debug(GOING_TO_EXECUTE_COMMIT_ON_GRAPH); + titanGenericDao.commit(); + } + } + } - } + } - @Override - public Either<Integer, TitanOperationStatus> getNumberOfParameters(NodeTypeEnum nodeType, String resourceId) { + @Override + public Either<Integer, TitanOperationStatus> getNumberOfParameters(NodeTypeEnum nodeType, String resourceId) { - Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), resourceId, GraphEdgeLabels.ADDITIONAL_INFORMATION, - NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class); + Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), resourceId, GraphEdgeLabels.ADDITIONAL_INFORMATION, + NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class); - if (getResult.isRight()) { - TitanOperationStatus status = getResult.right().value(); - return Either.right(status); - } + if (getResult.isRight()) { + TitanOperationStatus status = getResult.right().value(); + return Either.right(status); + } - ImmutablePair<AdditionalInfoParameterData, GraphEdge> immutablePair = getResult.left().value(); - AdditionalInfoParameterData parameterData = immutablePair.getLeft(); - Map<String, String> parameters = parameterData.getParameters(); + ImmutablePair<AdditionalInfoParameterData, GraphEdge> immutablePair = getResult.left().value(); + AdditionalInfoParameterData parameterData = immutablePair.getLeft(); + Map<String, String> parameters = parameterData.getParameters(); - Integer counter = 0; - if (parameters != null) { - counter = parameters.size(); - } + Integer counter = 0; + if (parameters != null) { + counter = parameters.size(); + } - return Either.left(counter); + return Either.left(counter); - } + } - @Override - public Either<AdditionalInfoParameterInfo, TitanOperationStatus> getAdditionalInformationParameter(NodeTypeEnum nodeType, String componentId, String id) { + @Override + public Either<AdditionalInfoParameterInfo, TitanOperationStatus> getAdditionalInformationParameter(NodeTypeEnum nodeType, String componentId, String id) { - TitanOperationStatus verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId); - if (verifyNodeTypeVsComponent != TitanOperationStatus.OK) { - return Either.right(verifyNodeTypeVsComponent); - } + TitanOperationStatus verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId); + if (verifyNodeTypeVsComponent != TitanOperationStatus.OK) { + return Either.right(verifyNodeTypeVsComponent); + } - Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, GraphEdgeLabels.ADDITIONAL_INFORMATION, - NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class); + Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, GraphEdgeLabels.ADDITIONAL_INFORMATION, + NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class); - if (getResult.isRight()) { - TitanOperationStatus status = getResult.right().value(); - return Either.right(status); - } + if (getResult.isRight()) { + TitanOperationStatus status = getResult.right().value(); + return Either.right(status); + } - ImmutablePair<AdditionalInfoParameterData, GraphEdge> immutablePair = getResult.left().value(); - AdditionalInfoParameterData parameterData = immutablePair.getLeft(); - Map<String, String> parameters = parameterData.getParameters(); - Map<String, String> idToKey = parameterData.getIdToKey(); + ImmutablePair<AdditionalInfoParameterData, GraphEdge> immutablePair = getResult.left().value(); + AdditionalInfoParameterData parameterData = immutablePair.getLeft(); + Map<String, String> parameters = parameterData.getParameters(); + Map<String, String> idToKey = parameterData.getIdToKey(); - if (idToKey == null || false == idToKey.containsKey(id)) { - return Either.right(TitanOperationStatus.INVALID_ID); - } + if (idToKey == null || !idToKey.containsKey(id)) { + return Either.right(TitanOperationStatus.INVALID_ID); + } - String key = idToKey.get(id); - String value = parameters.get(key); + String key = idToKey.get(id); + String value = parameters.get(key); - log.trace("The key-value {} = {} was retrieved for id {}", key, value, id); + log.trace("The key-value {} = {} was retrieved for id {}", key, value, id); - Either<AdditionalInfoParameterData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(parameterData, AdditionalInfoParameterData.class); + Either<AdditionalInfoParameterData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(parameterData, AdditionalInfoParameterData.class); - if (updateNode.isRight()) { - TitanOperationStatus status = updateNode.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { - BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("GetAdditionnalInformationParameter", "additional information of " + nodeType.getName() + " " + componentId, String.valueOf(status)); - } - return Either.right(status); - } + if (updateNode.isRight()) { + TitanOperationStatus status = updateNode.right().value(); + if (status != TitanOperationStatus.NOT_FOUND) { + BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("GetAdditionnalInformationParameter", ADDITIONAL_INFORMATION_OF + nodeType.getName() + " " + componentId, String.valueOf(status)); + } + return Either.right(status); + } - AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(id, key, value); + AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(id, key, value); - return Either.left(additionalInfoParameterInfo); + return Either.left(additionalInfoParameterInfo); - } + } - @Override - public Either<AdditionalInformationDefinition, TitanOperationStatus> getAllAdditionalInformationParameters(NodeTypeEnum nodeType, String componentId, boolean ignoreVerification) { + @Override + public Either<AdditionalInformationDefinition, TitanOperationStatus> getAllAdditionalInformationParameters(NodeTypeEnum nodeType, String componentId, boolean ignoreVerification) { - if (false == ignoreVerification) { - TitanOperationStatus verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId); - if (verifyNodeTypeVsComponent != TitanOperationStatus.OK) { - return Either.right(verifyNodeTypeVsComponent); - } - } + if (!ignoreVerification) { + TitanOperationStatus verifyNodeTypeVsComponent = verifyNodeTypeVsComponent(nodeType, componentId); + if (verifyNodeTypeVsComponent != TitanOperationStatus.OK) { + return Either.right(verifyNodeTypeVsComponent); + } + } - Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, GraphEdgeLabels.ADDITIONAL_INFORMATION, - NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class); + Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId, GraphEdgeLabels.ADDITIONAL_INFORMATION, + NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class); - if (getResult.isRight()) { - TitanOperationStatus status = getResult.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { - BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("GetAdditionnalInformationParameters", "additional information of " + nodeType.getName() + " " + componentId, String.valueOf(status)); - } - return Either.right(status); - } + if (getResult.isRight()) { + TitanOperationStatus status = getResult.right().value(); + if (status != TitanOperationStatus.NOT_FOUND) { + BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("GetAdditionnalInformationParameters", ADDITIONAL_INFORMATION_OF + nodeType.getName() + " " + componentId, String.valueOf(status)); + } + return Either.right(status); + } - ImmutablePair<AdditionalInfoParameterData, GraphEdge> immutablePair = getResult.left().value(); - AdditionalInfoParameterData parameterData = immutablePair.getLeft(); - Map<String, String> parameters = parameterData.getParameters(); - Map<String, String> idToKey = parameterData.getIdToKey(); + ImmutablePair<AdditionalInfoParameterData, GraphEdge> immutablePair = getResult.left().value(); + AdditionalInfoParameterData parameterData = immutablePair.getLeft(); + Map<String, String> parameters = parameterData.getParameters(); + Map<String, String> idToKey = parameterData.getIdToKey(); - AdditionalInformationDefinition informationDefinition = createInformationDefinitionFromNode(componentId, parameters, idToKey, parameterData); + AdditionalInformationDefinition informationDefinition = createInformationDefinitionFromNode(componentId, parameters, idToKey, parameterData); - return Either.left(informationDefinition); + return Either.left(informationDefinition); - } + } - @Override - public Either<AdditionalInformationDefinition, StorageOperationStatus> getAllAdditionalInformationParameters(NodeTypeEnum nodeType, String resourceId, boolean ignoreVerification, boolean inTransaction) { + @Override + public Either<AdditionalInformationDefinition, StorageOperationStatus> getAllAdditionalInformationParameters(NodeTypeEnum nodeType, String resourceId, boolean ignoreVerification, boolean inTransaction) { - Either<AdditionalInformationDefinition, StorageOperationStatus> result = null; + Either<AdditionalInformationDefinition, StorageOperationStatus> result = null; - try { + try { - Either<AdditionalInformationDefinition, TitanOperationStatus> either = this.getAllAdditionalInformationParameters(nodeType, resourceId, ignoreVerification); + Either<AdditionalInformationDefinition, TitanOperationStatus> either = this.getAllAdditionalInformationParameters(nodeType, resourceId, ignoreVerification); - if (either.isRight()) { - TitanOperationStatus status = either.right().value(); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } else { - AdditionalInformationDefinition additionalInformationDefinition = either.left().value(); - result = Either.left(additionalInformationDefinition); - } + if (either.isRight()) { + TitanOperationStatus status = either.right().value(); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } else { + AdditionalInformationDefinition additionalInformationDefinition = either.left().value(); + result = Either.left(additionalInformationDefinition); + } - return result; + return result; - } finally { - commitOrRollback(inTransaction, result); - } - - } - - private void commitOrRollback(boolean inTransaction, Either<? extends Object, StorageOperationStatus> result) { - - if (false == inTransaction) { - if (result == null || result.isRight()) { - log.error("Going to execute rollback on graph."); - titanGenericDao.rollback(); - } else { - log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } - - @Override - public Either<AdditionalInfoParameterInfo, StorageOperationStatus> getAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String id, boolean inTransaction) { - - Either<AdditionalInfoParameterInfo, StorageOperationStatus> result = null; - - try { - - Either<AdditionalInfoParameterInfo, TitanOperationStatus> either = this.getAdditionalInformationParameter(nodeType, resourceId, id); - - if (either.isRight()) { - log.error("Failed to fetch additional information property with id {} of component {}", id, resourceId); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(either.right().value())); - } else { - AdditionalInfoParameterInfo additionalInformationDefinition = either.left().value(); - result = Either.left(additionalInformationDefinition); - } - - return result; - - } finally { - commitOrRollback(inTransaction, result); - } - } - - @Override - public Either<AdditionalInformationDefinition, StorageOperationStatus> deleteAllAdditionalInformationParameters(NodeTypeEnum nodeType, String resourceId, boolean inTransaction) { - - Either<AdditionalInformationDefinition, StorageOperationStatus> result = null; - - try { - - Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), resourceId, GraphEdgeLabels.ADDITIONAL_INFORMATION, - NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class); - - if (getResult.isRight()) { - TitanOperationStatus status = getResult.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - return Either.right(StorageOperationStatus.OK); - } else { - BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError("DeleteAdditionalInformationNode", "additional information of " + nodeType.getName() + " " + resourceId, String.valueOf(status)); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - return result; - } - - ImmutablePair<AdditionalInfoParameterData, GraphEdge> value = getResult.left().value(); - AdditionalInfoParameterData parameterData = value.getLeft(); - - Either<AdditionalInfoParameterData, TitanOperationStatus> deleteNodeRes = titanGenericDao.deleteNode(parameterData, AdditionalInfoParameterData.class); - if (deleteNodeRes.isRight()) { - TitanOperationStatus status = getResult.right().value(); - BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError("DeleteAdditionalInformationNode", (String) parameterData.getUniqueId(), String.valueOf(status)); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - - AdditionalInformationDefinition informationDefinition = convertAdditionalInformationDataToDefinition(deleteNodeRes.left().value(), resourceId); - - result = Either.left(informationDefinition); - - return result; - - } finally { - commitOrRollback(inTransaction, result); - } - } - - private TitanOperationStatus verifyNodeTypeVsComponent(NodeTypeEnum nodeType, String componentId) { - Either<TitanVertex, TitanOperationStatus> vertexByProperty = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId); - if (vertexByProperty.isRight()) { - TitanOperationStatus status = vertexByProperty.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - return status; - } else { - Vertex v = vertexByProperty.left().value(); - String label = (String) v.property(GraphPropertiesDictionary.LABEL.getProperty()).value(); - if (label != null) { - if (false == label.equals(nodeType.getName())) { - log.debug("The node type {} is not appropriate to component {}", nodeType, componentId); - return TitanOperationStatus.INVALID_ID; - } - } else { - log.debug("The node type {} with id {} does not have a label property.", nodeType, componentId); - return TitanOperationStatus.INVALID_ID; - } - } - return TitanOperationStatus.OK; - } + } finally { + commitOrRollback(inTransaction, result); + } + + } + + private void commitOrRollback(boolean inTransaction, Either<? extends Object, StorageOperationStatus> result) { + + if (!inTransaction) { + if (result == null || result.isRight()) { + log.error(GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH); + titanGenericDao.rollback(); + } else { + log.debug(GOING_TO_EXECUTE_COMMIT_ON_GRAPH); + titanGenericDao.commit(); + } + } + } + + + @Override + public Either<AdditionalInfoParameterInfo, StorageOperationStatus> getAdditionalInformationParameter(NodeTypeEnum nodeType, String resourceId, String id, boolean inTransaction) { + + Either<AdditionalInfoParameterInfo, StorageOperationStatus> result = null; + + try { + + Either<AdditionalInfoParameterInfo, TitanOperationStatus> either = this.getAdditionalInformationParameter(nodeType, resourceId, id); + + if (either.isRight()) { + log.error("Failed to fetch additional information property with id {} of component {}", id, resourceId); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(either.right().value())); + } else { + AdditionalInfoParameterInfo additionalInformationDefinition = either.left().value(); + result = Either.left(additionalInformationDefinition); + } + + return result; + + } finally { + commitOrRollback(inTransaction, result); + } + } + + @Override + public Either<AdditionalInformationDefinition, StorageOperationStatus> deleteAllAdditionalInformationParameters(NodeTypeEnum nodeType, String resourceId, boolean inTransaction) { + + Either<AdditionalInformationDefinition, StorageOperationStatus> result = null; + + try { + + Either<ImmutablePair<AdditionalInfoParameterData, GraphEdge>, TitanOperationStatus> getResult = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(nodeType), resourceId, GraphEdgeLabels.ADDITIONAL_INFORMATION, + NodeTypeEnum.AdditionalInfoParameters, AdditionalInfoParameterData.class); + + if (getResult.isRight()) { + TitanOperationStatus status = getResult.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + return Either.right(StorageOperationStatus.OK); + } else { + BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError("DeleteAdditionalInformationNode", ADDITIONAL_INFORMATION_OF + nodeType.getName() + " " + resourceId, String.valueOf(status)); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + return result; + } + + ImmutablePair<AdditionalInfoParameterData, GraphEdge> value = getResult.left().value(); + AdditionalInfoParameterData parameterData = value.getLeft(); + + Either<AdditionalInfoParameterData, TitanOperationStatus> deleteNodeRes = titanGenericDao.deleteNode(parameterData, AdditionalInfoParameterData.class); + if (deleteNodeRes.isRight()) { + TitanOperationStatus status = getResult.right().value(); + BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError("DeleteAdditionalInformationNode", (String) parameterData.getUniqueId(), String.valueOf(status)); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + return result; + } + + AdditionalInformationDefinition informationDefinition = convertAdditionalInformationDataToDefinition(deleteNodeRes.left().value(), resourceId); + + result = Either.left(informationDefinition); + + return result; + + } finally { + commitOrRollback(inTransaction, result); + } + } + + private TitanOperationStatus verifyNodeTypeVsComponent(NodeTypeEnum nodeType, String componentId) { + Either<TitanVertex, TitanOperationStatus> vertexByProperty = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(nodeType), componentId); + if (vertexByProperty.isRight()) { + TitanOperationStatus status = vertexByProperty.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + return status; + } else { + Vertex v = vertexByProperty.left().value(); + String label = (String) v.property(GraphPropertiesDictionary.LABEL.getProperty()).value(); + if (label != null) { + if (!label.equals(nodeType.getName())) { + log.debug("The node type {} is not appropriate to component {}", nodeType, componentId); + return TitanOperationStatus.INVALID_ID; + } + } else { + log.debug("The node type {} with id {} does not have a label property.", nodeType, componentId); + return TitanOperationStatus.INVALID_ID; + } + } + return TitanOperationStatus.OK; + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AnnotationTypeOperations.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AnnotationTypeOperations.java new file mode 100644 index 0000000000..988ff3c127 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/AnnotationTypeOperations.java @@ -0,0 +1,64 @@ +package org.openecomp.sdc.be.model.operations.impl; + +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.model.AnnotationTypeDefinition; +import org.openecomp.sdc.be.model.operations.api.TypeOperations; +import org.openecomp.sdc.be.resources.data.AnnotationTypeData; +import org.springframework.stereotype.Component; + +import javax.validation.constraints.NotNull; + +@Component +public class AnnotationTypeOperations implements TypeOperations<AnnotationTypeDefinition> { + + private final CommonTypeOperations commonTypeOperations; + + public AnnotationTypeOperations(CommonTypeOperations commonTypeOperations) { + this.commonTypeOperations = commonTypeOperations; + } + + @Override + public AnnotationTypeDefinition addType(AnnotationTypeDefinition newTypeDefinition) { + AnnotationTypeData annotationTypeData = new AnnotationTypeData(newTypeDefinition); + String uniqueId = UniqueIdBuilder.buildTypeUid(newTypeDefinition.getType(), newTypeDefinition.getVersion(), "annotationtype"); + annotationTypeData.setInitialCreationProperties(uniqueId); + commonTypeOperations.addType(annotationTypeData, AnnotationTypeData.class); + commonTypeOperations.addProperties(uniqueId, NodeTypeEnum.AnnotationType, newTypeDefinition.getProperties()); + return getType(uniqueId); + } + + @Override + public AnnotationTypeDefinition getType(String uniqueId) { + return commonTypeOperations.getType(uniqueId, AnnotationTypeData.class, NodeTypeEnum.AnnotationType) + .map(this::populateTypeDefinition) + .orElse(null); + } + + private AnnotationTypeDefinition populateTypeDefinition(@NotNull AnnotationTypeData annotationTypeData) { + AnnotationTypeDefinition annotationTypeDefinition = new AnnotationTypeDefinition(annotationTypeData.getAnnotationTypeDataDefinition()); + commonTypeOperations.fillProperties(annotationTypeDefinition.getUniqueId(), NodeTypeEnum.AnnotationType, annotationTypeDefinition::setProperties); + return annotationTypeDefinition; + } + + @Override + public AnnotationTypeDefinition getLatestType(String type) { + return commonTypeOperations.getLatestType(type, AnnotationTypeData.class, NodeTypeEnum.AnnotationType) + .map(this::populateTypeDefinition) + .orElse(null); + } + + @Override + public boolean isSameType(AnnotationTypeDefinition type1, AnnotationTypeDefinition type2) { + return type1.isSameDefinition(type2); + } + + @Override + public AnnotationTypeDefinition updateType(AnnotationTypeDefinition currentTypeDefinition, + AnnotationTypeDefinition updatedTypeDefinition) { + AnnotationTypeData updatedTypeData = new AnnotationTypeData(updatedTypeDefinition); + updatedTypeData.setUpdateProperties(currentTypeDefinition); + commonTypeOperations.updateType(updatedTypeData, updatedTypeDefinition.getProperties(), AnnotationTypeData.class, NodeTypeEnum.AnnotationType); + return getType(updatedTypeData.getUniqueId()); + } + +} 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 0c8abdaa39..9beb2053a3 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 @@ -20,13 +20,9 @@ package org.openecomp.sdc.be.model.operations.impl; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.UUID; - +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.TitanVertex; +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.tinkerpop.gremlin.structure.Direction; import org.apache.tinkerpop.gremlin.structure.Edge; @@ -53,702 +49,703 @@ 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.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.slf4j.MDC; import org.springframework.stereotype.Component; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanVertex; - -import fj.data.Either; +import java.util.*; @Component("artifact-operation") public class ArtifactOperation implements IArtifactOperation { - @javax.annotation.Resource - private TitanGenericDao titanGenericDao; - - @javax.annotation.Resource - private HeatParametersOperation heatParametersOperation; + private static final String THE_RETURNED_ARTIFACT_DEFINTION_IS = "The returned ArtifactDefintion is {}"; @javax.annotation.Resource - private GroupOperation groupOperation; - @javax.annotation.Resource - private GroupInstanceOperation groupInstanceOperation; - - private static Logger log = LoggerFactory.getLogger(ArtifactOperation.class.getName()); - - public ArtifactOperation() { - super(); - } - - public TitanGenericDao getTitanGenericDao() { - return titanGenericDao; - } - - public void setTitanGenericDao(TitanGenericDao titanGenericDao) { - this.titanGenericDao = titanGenericDao; - } - - public HeatParametersOperation getHeatParametersOperation() { - return heatParametersOperation; - } - - public void setHeatParametersOperation(HeatParametersOperation heatParametersOperation) { - 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); - - if (status.isRight()) { - if (false == inTransaction) { - titanGenericDao.rollback(); - } - log.debug("Failed to add artifact {} to {} {}", artifactInfo.getArtifactName(), type , parentId); - return Either.right(status.right().value()); - } else { - if (false == inTransaction) { - titanGenericDao.commit(); - } - ArtifactData artifactData = status.left().value(); - - ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(artifactData); - - log.debug("The returned ArtifactDefintion is {}", artifactDefResult); - return Either.left(artifactDefResult); - } - - } - - @Override - public StorageOperationStatus addArifactToComponent(ArtifactDefinition artifactInfo, String parentId, NodeTypeEnum type, boolean failIfExist, TitanVertex parentVertex) { - - StorageOperationStatus status = addArtifactToGraph(artifactInfo, parentId, type, failIfExist, parentVertex); - - if (status.equals(StorageOperationStatus.OK)) { - log.debug("Failed to add artifact {} {} to {}", artifactInfo.getArtifactName(), type, parentId); - } - return status; - } - - private StorageOperationStatus addArtifactToGraph(ArtifactDefinition artifactInfo, String id, NodeTypeEnum type, boolean failIfexist, TitanVertex parentVertex) { - - if (artifactInfo.getUniqueId() == null || artifactInfo.getUniqueId().isEmpty()) { - String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(id, artifactInfo.getArtifactLabel()); - artifactInfo.setUniqueId(uniqueId); - } - - if (validateParentType(type) == false) { - return StorageOperationStatus.GENERAL_ERROR; - } - - ArtifactData artifactData = new ArtifactData(artifactInfo); - - Either<TitanVertex, TitanOperationStatus> existArtifact = titanGenericDao.getVertexByProperty(artifactData.getUniqueIdKey(), artifactData.getUniqueId()); - if (existArtifact.isRight()) { - if (existArtifact.right().value().equals(TitanOperationStatus.NOT_FOUND)) { - // create new node - log.debug("Before adding artifact to graph {}", artifactData); - if (artifactData.getArtifactDataDefinition().getArtifactUUID() == null || artifactData.getArtifactDataDefinition().getArtifactUUID().isEmpty()) - updateUUID(artifactData.getArtifactDataDefinition(), null, artifactData.getArtifactDataDefinition().getArtifactVersion()); - Either<TitanVertex, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(artifactData); - - if (createNodeResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); - log.debug("Failed to add artifact {} to graph. status is {}", artifactData.getArtifactDataDefinition().getArtifactName(), operationStatus); - BeEcompErrorManager.getInstance().logBeFailedCreateNodeError("Add artifact", artifactData.getArtifactDataDefinition().getArtifactName(), String.valueOf(operationStatus)); - return DaoStatusConverter.convertTitanStatusToStorageStatus(operationStatus); - } - - // add heat parameters - if (artifactInfo.getHeatParameters() != null && !artifactInfo.getHeatParameters().isEmpty() && !artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT_ENV.getType())) { - StorageOperationStatus addPropertiesStatus = heatParametersOperation.addPropertiesToGraph(artifactInfo.getListHeatParameters(), artifactData.getUniqueId().toString(), NodeTypeEnum.ArtifactRef); - if (addPropertiesStatus != StorageOperationStatus.OK) { - log.debug("Failed to create heat parameters on graph for artifact {}", artifactInfo.getArtifactName()); - return addPropertiesStatus; - } - } - - } else { - log.debug("Failed to check existance of artifact in graph for id {}", artifactData.getUniqueId()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(existArtifact.right().value()); - } - } else if (failIfexist) { - log.debug("Artifact {} already exist", artifactData.getUniqueId()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ALREADY_EXIST); - } - - // save logical artifact ref name on edge as property - Map<String, Object> properties = new HashMap<String, Object>(); - properties.put(GraphEdgePropertiesDictionary.NAME.getProperty(), artifactInfo.getArtifactLabel()); - if (artifactInfo.getArtifactGroupType() != null) - properties.put(GraphEdgePropertiesDictionary.GROUP_TYPE.getProperty(), artifactInfo.getArtifactGroupType().getType()); - TitanOperationStatus relation = titanGenericDao.createEdge(parentVertex, artifactData, GraphEdgeLabels.ARTIFACT_REF, properties); - if (!relation.equals(TitanOperationStatus.OK)) { - log.debug("Failed to create relation in graph for id {} to new artifact", id); - return DaoStatusConverter.convertTitanStatusToStorageStatus(relation); - } - - return StorageOperationStatus.OK; - } - - private Either<ArtifactData, StorageOperationStatus> addArtifactToGraph(ArtifactDefinition artifactInfo, String id, NodeTypeEnum type, boolean failIfexist) { - - if (artifactInfo.getUniqueId() == null || artifactInfo.getUniqueId().isEmpty()) { - String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(id, artifactInfo.getArtifactLabel()); - artifactInfo.setUniqueId(uniqueId); - } - - if (validateParentType(type) == false) { - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - - ArtifactData artifactData = new ArtifactData(artifactInfo); - - Either<ArtifactData, TitanOperationStatus> existArtifact = titanGenericDao.getNode(artifactData.getUniqueIdKey(), artifactData.getUniqueId(), ArtifactData.class); - if (existArtifact.isRight()) { - if (existArtifact.right().value().equals(TitanOperationStatus.NOT_FOUND)) { - // create new node - log.debug("Before adding artifact to graph {}" , artifactData); - if (artifactData.getArtifactDataDefinition().getArtifactUUID() == null || artifactData.getArtifactDataDefinition().getArtifactUUID().isEmpty()) - updateUUID(artifactData.getArtifactDataDefinition(), null, artifactData.getArtifactDataDefinition().getArtifactVersion()); - Either<ArtifactData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(artifactData, ArtifactData.class); - log.debug("After adding artifact to graph {}", artifactData); - - if (createNodeResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); - log.debug("Failed to add artifact {} to graph. status is {}", artifactData.getArtifactDataDefinition().getArtifactName(), operationStatus); - BeEcompErrorManager.getInstance().logBeFailedCreateNodeError("Add artifact", artifactData.getArtifactDataDefinition().getArtifactName(), String.valueOf(operationStatus)); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationStatus)); - } - artifactData = createNodeResult.left().value(); - - // add heat parameters - if (artifactInfo.getHeatParameters() != null && !artifactInfo.getHeatParameters().isEmpty() && !artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT_ENV.getType())) { - StorageOperationStatus addPropertiesStatus = heatParametersOperation.addPropertiesToGraph(artifactInfo.getListHeatParameters(), artifactData.getUniqueId().toString(), NodeTypeEnum.ArtifactRef); - if (addPropertiesStatus != StorageOperationStatus.OK) { - log.debug("Failed to create heat parameters on graph for artifact {}", artifactInfo.getArtifactName()); - return Either.right(addPropertiesStatus); - } - } - - } else { - log.debug("Failed to check existance of artifact in graph for id {}", artifactData.getUniqueId()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(existArtifact.right().value())); - } - } else if (failIfexist) { - log.debug("Artifact {} already exist", artifactData.getUniqueId()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ALREADY_EXIST)); - } else { - artifactData = existArtifact.left().value(); - } - - UniqueIdData parent = new UniqueIdData(type, id); - - // save logical artifact ref name on edge as property - Map<String, Object> properties = new HashMap<String, Object>(); - properties.put(GraphEdgePropertiesDictionary.NAME.getProperty(), artifactInfo.getArtifactLabel()); - if (artifactInfo.getArtifactGroupType() != null) - properties.put(GraphEdgePropertiesDictionary.GROUP_TYPE.getProperty(), artifactInfo.getArtifactGroupType().getType()); - Either<GraphRelation, TitanOperationStatus> relation = titanGenericDao.createRelation(parent, artifactData, GraphEdgeLabels.ARTIFACT_REF, properties); - if (relation.isRight()) { - log.debug("Failed to create relation in graph fro id {} to new artifact", id); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(relation.right().value())); - } - - return Either.left(artifactData); - } - - private boolean validateParentType(NodeTypeEnum type) { - boolean isValid = false; - switch (type) { - case Resource: - case InterfaceOperation: - case Service: - case ResourceInstance: - isValid = true; - break; - default: - log.debug("Not supported node type for artifact relation : {} ", type); - } - return isValid; - } - - - protected ArtifactDefinition convertArtifactDataToArtifactDefinition(ArtifactData artifactDefResult) { - log.debug("The object returned after create property is {}" ,artifactDefResult); - - ArtifactDefinition propertyDefResult = new ArtifactDefinition(artifactDefResult.getArtifactDataDefinition()); - List<HeatParameterDefinition> parameters = new ArrayList<HeatParameterDefinition>(); - StorageOperationStatus heatParametersOfNode = heatParametersOperation.getHeatParametersOfNode(NodeTypeEnum.ArtifactRef, artifactDefResult.getUniqueId().toString(), parameters); - if ((heatParametersOfNode.equals(StorageOperationStatus.OK)) && !parameters.isEmpty()) { - propertyDefResult.setListHeatParameters(parameters); - } - 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); - - if (status.isRight()) { - if (false == inTransaction) { - titanGenericDao.rollback(); - } - log.debug("Failed to update artifact {} of {} {}. status is {}", artifactId, type.getName(), id, status.right().value()); - BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("Update Artifact", artifactId, String.valueOf(status.right().value())); - return Either.right(status.right().value()); - } else { - if (false == inTransaction) { - titanGenericDao.commit(); - } - ArtifactData artifactData = status.left().value(); - - ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(artifactData); - log.debug("The returned ArtifactDefintion is {}", artifactDefResult); - return Either.left(artifactDefResult); - } - } - - @Override - public Either<ArtifactDefinition, StorageOperationStatus> removeArifactFromResource(String id, String artifactId, NodeTypeEnum type, boolean deleteMandatoryArtifact, boolean inTransaction) { - Either<ArtifactData, TitanOperationStatus> status = removeArtifactOnGraph(id, artifactId, type, deleteMandatoryArtifact); - - if (status.isRight()) { - if (false == inTransaction) { - titanGenericDao.rollback(); - } - log.debug("Failed to delete artifact {} of resource {}", artifactId, id); - - BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError("Delete Artifact", artifactId, String.valueOf(status.right().value())); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status.right().value())); - } else { - if (false == inTransaction) { - titanGenericDao.commit(); - } - ArtifactData artifactData = status.left().value(); - - ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(artifactData); - log.debug("The returned ArtifactDefintion is {}" , artifactDefResult); - return Either.left(artifactDefResult); - } - } - - @SuppressWarnings("null") - private Either<ArtifactData, StorageOperationStatus> updateArtifactOnGraph(ArtifactDefinition artifactInfo, String artifactId, NodeTypeEnum type, String id) { - - Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph(); - if (graph.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value())); - } - - TitanGraph tGraph = graph.left().value(); - - @SuppressWarnings("unchecked") - Iterable<TitanVertex> verticesArtifact = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId).vertices(); - Iterator<TitanVertex> iterator = verticesArtifact.iterator(); - if (!iterator.hasNext()) { - log.debug("No artifact node for id = {}", artifactId); - return Either.right(StorageOperationStatus.NOT_FOUND); - } - TitanVertex artifactV = iterator.next(); - - Iterator<Edge> iterEdge = artifactV.edges(Direction.IN, GraphEdgeLabels.ARTIFACT_REF.getProperty()); - - int edgeCount = 0; - Edge edgeFromTo = null; - while (iterEdge.hasNext()) { - Edge edge = iterEdge.next(); - Vertex vertexFrom = edge.outVertex(); - String vertexId = vertexFrom.value(UniqueIdBuilder.getKeyByNodeType(type)); - if (id.equals(vertexId)) { - edgeFromTo = edge; - } - ++edgeCount; - } - - if (isNeedUpdateHeatTime(artifactInfo)) { - artifactInfo.setHeatParamsUpdateDate(System.currentTimeMillis()); - } - - ArtifactData artifactData = new ArtifactData(artifactInfo); - if (edgeFromTo == null) { - log.debug("No relation between artifact = {} and node with id = {}", artifactId, id); - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - - Either<Boolean, StorageOperationStatus> setRelevantHeatParamIdRes = null; - if (edgeCount > 1) { - // need to remove relation, create new node - log.debug("artifactRef have more connection. Need to clone node"); - log.debug("remove edge {}", edgeFromTo); - edgeFromTo.remove(); - // update resource id in new artifact node - String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(id, artifactInfo.getArtifactLabel()); - artifactInfo.setUniqueId(uniqueId); - // update UUID and artifact version - String oldChecksum = artifactV.valueOrNull(titanGenericDao.getGraph().left().value().getPropertyKey(GraphPropertiesDictionary.ARTIFACT_CHECKSUM.getProperty())); - String oldVersion = artifactV.valueOrNull(titanGenericDao.getGraph().left().value().getPropertyKey(GraphPropertiesDictionary.ARTIFACT_VERSION.getProperty())); - updateUUID(artifactInfo, oldChecksum, oldVersion); - log.debug("try to create new artifact ref node for id {}", uniqueId); - Either<ArtifactData, StorageOperationStatus> addedArtifactRes = addArtifactToGraph(artifactInfo, id, type, true); - - if (addedArtifactRes.isLeft()) { - // remove all relations between groups to the old artifact - // add relation between the same groups to the new artifact - StorageOperationStatus reassociateGroupsFromArtifact = groupOperation.dissociateAndAssociateGroupsFromArtifact(id, type, artifactId, addedArtifactRes.left().value(), true); - if (reassociateGroupsFromArtifact != StorageOperationStatus.OK) { - BeEcompErrorManager.getInstance().logInternalFlowError("UpdateArtifact", "Failed to reassociate groups to the new artifact", ErrorSeverity.ERROR); - return Either.right(reassociateGroupsFromArtifact); - } - - StorageOperationStatus reassociateGroupInstancesFromArtifact = groupInstanceOperation.dissociateAndAssociateGroupsInstanceFromArtifact(id, type, artifactId, addedArtifactRes.left().value()); - if (reassociateGroupInstancesFromArtifact != StorageOperationStatus.OK) { - BeEcompErrorManager.getInstance().logInternalFlowError("UpdateArtifact", "Failed to reassociate group instances to the new artifact", ErrorSeverity.ERROR); - return Either.right(reassociateGroupsFromArtifact); - } - - // If artifact is heat env - if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT_ENV.getType())) { - ArtifactData addedArtifact = addedArtifactRes.left().value(); - String newArtifactUniqueId = (String) addedArtifact.getUniqueId(); - Either<HeatParameterValueData, StorageOperationStatus> updateResult = null; - - setRelevantHeatParamIdRes = setRelevantHeatParamId(artifactV, artifactInfo); - if (setRelevantHeatParamIdRes.isRight()) { - log.error("Failed to set relevant id to heat parameters for heat env artifact {}. Status is {}", artifactInfo.getUniqueId(), setRelevantHeatParamIdRes.right().value()); - return Either.right(setRelevantHeatParamIdRes.right().value()); - } - for (HeatParameterDefinition heatEnvParam : artifactInfo.getListHeatParameters()) { - updateResult = heatParametersOperation.updateHeatParameterValue(heatEnvParam, newArtifactUniqueId, id, artifactInfo.getArtifactLabel()); - if (updateResult.isRight()) { - log.error("Failed to update heat parameter {}. Status is {}", heatEnvParam.getName(), updateResult.right().value()); - return Either.right(updateResult.right().value()); - } - } - - Iterator<Edge> iterEdgeGeneratedFrom = artifactV.edges(Direction.OUT, GraphEdgeLabels.GENERATED_FROM.getProperty()); - - if (!iterEdgeGeneratedFrom.hasNext()) { - log.error("No heat artifact node for id = {}", artifactId); - return Either.right(StorageOperationStatus.NOT_FOUND); - } - Edge edgeToHeat = iterEdgeGeneratedFrom.next(); - Vertex vertexIn = edgeToHeat.inVertex(); - String generatedFromArtifactId = vertexIn.value(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef)); - UniqueIdData generatedFromArtifactNode = new UniqueIdData(NodeTypeEnum.ArtifactRef, generatedFromArtifactId); - Either<GraphRelation, TitanOperationStatus> createRelationToGeneratedFromArtifactRes = titanGenericDao.createRelation(addedArtifact, generatedFromArtifactNode, GraphEdgeLabels.GENERATED_FROM, null); - if (createRelationToGeneratedFromArtifactRes.isRight()) { - log.error("Failed to create relation from heat_env {} to heat {}", addedArtifact.getUniqueId(), generatedFromArtifactNode); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createRelationToGeneratedFromArtifactRes.right().value())); - } - } - } - return addedArtifactRes; - - } else { - if (edgeCount == 1) { - String oldChecksum = artifactV.valueOrNull(titanGenericDao.getGraph().left().value().getPropertyKey(GraphPropertiesDictionary.ARTIFACT_CHECKSUM.getProperty())); - String oldVersion = artifactV.valueOrNull(titanGenericDao.getGraph().left().value().getPropertyKey(GraphPropertiesDictionary.ARTIFACT_VERSION.getProperty())); - updateUUID(artifactInfo, oldChecksum, oldVersion); - // update exist - Either<ArtifactData, TitanOperationStatus> updatedArtifact = titanGenericDao.updateNode(artifactData, ArtifactData.class); - if (updatedArtifact.isRight()) { - log.debug("failed to update artifact node for id {}", artifactData.getUniqueId()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updatedArtifact.right().value())); - } - - if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT_ENV.getType())) { - Either<HeatParameterValueData, StorageOperationStatus> updateResult = null; - String artifactUniqueId = artifactInfo.getUniqueId(); - setRelevantHeatParamIdRes = setRelevantHeatParamId(artifactV, artifactInfo); - if (setRelevantHeatParamIdRes.isRight()) { - log.error("Failed to set relevant id to heat parameters for heat env artifact {}. Status is {}", artifactInfo.getUniqueId(), setRelevantHeatParamIdRes.right().value()); - return Either.right(setRelevantHeatParamIdRes.right().value()); - } - for (HeatParameterDefinition heatEnvParam : artifactInfo.getListHeatParameters()) { - updateResult = heatParametersOperation.updateHeatParameterValue(heatEnvParam, artifactUniqueId, id, artifactInfo.getArtifactLabel()); - if (updateResult.isRight()) { - log.error("Failed to update heat parameter {}. Status is {}", heatEnvParam.getName(), updateResult.right().value()); - return Either.right(updateResult.right().value()); - } - } - } else { - if (artifactData.getArtifactDataDefinition().getArtifactChecksum() == null) { - // update heat parameters only if it is not heat env - if (artifactInfo.getGeneratedFromId() == null) { - StorageOperationStatus operationStatus = heatParametersOperation.updateHeatParameters(artifactInfo.getListHeatParameters()); - if (operationStatus != StorageOperationStatus.OK) { - return Either.right(operationStatus); - } - } - } else { - Either<List<HeatParameterDefinition>, StorageOperationStatus> deleteParameters = heatParametersOperation.deleteAllHeatParametersAssociatedToNode(NodeTypeEnum.ArtifactRef, artifactInfo.getUniqueId()); - if (deleteParameters.isRight()) { - log.debug("failed to update heat parameters for artifact id {}", artifactData.getUniqueId()); - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - - StorageOperationStatus addParameters = heatParametersOperation.addPropertiesToGraph(artifactInfo.getListHeatParameters(), artifactId, NodeTypeEnum.ArtifactRef); - if (!addParameters.equals(StorageOperationStatus.OK)) { - log.debug("failed to update heat parameters for artifact id {}", artifactData.getUniqueId()); - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - - } - } - - return Either.left(updatedArtifact.left().value()); - } else { - log.debug("No relevent edges for artifact = {}", artifactId); - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - } - } - - private boolean isNeedUpdateHeatTime(ArtifactDefinition artifactInfo) { - if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT_NET.getType()) || artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT_VOL.getType())) { - return true; - } - return false; - } - - private Either<Boolean, StorageOperationStatus> setRelevantHeatParamId(TitanVertex artifactV, ArtifactDefinition artifactInfo) { - - Map<String, String> heatParametersHM = new HashMap<String, String>(); - - Iterator<Edge> iterHeat = artifactV.edges(Direction.OUT, GraphEdgeLabels.GENERATED_FROM.getProperty()); - if (!iterHeat.hasNext()) { - log.debug("No edges with label GENERATED_FROM for the node {}" , artifactInfo.getUniqueId()); - return Either.right(StorageOperationStatus.NOT_FOUND); - } - Edge heat = iterHeat.next(); - Vertex heatVertex = heat.inVertex(); - String heatUniqueId = (String) heatVertex.value(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef)); - - Either<List<ImmutablePair<HeatParameterData, GraphEdge>>, TitanOperationStatus> getHeatParametersRes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), heatUniqueId, GraphEdgeLabels.HEAT_PARAMETER, - NodeTypeEnum.HeatParameter, HeatParameterData.class); - if (getHeatParametersRes.isRight()) { - log.debug("No heat parameters for heat artifact {}", heatUniqueId); - return Either.right(StorageOperationStatus.NOT_FOUND); - } - List<ImmutablePair<HeatParameterData, GraphEdge>> heatParameters = getHeatParametersRes.left().value(); - if (heatParameters == null) { - log.debug("No heat parameters for heat artifact {}", heatUniqueId); - return Either.right(StorageOperationStatus.NOT_FOUND); - } - for (ImmutablePair<HeatParameterData, GraphEdge> heatParamEdge : heatParameters) { - HeatParameterData heatParam = heatParamEdge.getLeft(); - heatParametersHM.put(heatParam.getName(), (String) heatParam.getUniqueId()); - } - String curName = null; - for (HeatParameterDefinition heatEnvParam : artifactInfo.getListHeatParameters()) { - curName = heatEnvParam.getName(); - if (heatParametersHM.containsKey(curName)) { - heatEnvParam.setUniqueId(heatParametersHM.get(curName)); - } - } - return Either.left(true); - } - - private Either<ArtifactData, TitanOperationStatus> removeArtifactOnGraph(String id, String artifactId, NodeTypeEnum type, boolean deleteMandatoryArtifact) { - Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph(); - if (graph.isRight()) { - return Either.right(graph.right().value()); - } - - TitanGraph tGraph = graph.left().value(); - Either<ArtifactData, TitanOperationStatus> artifactData = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId, ArtifactData.class); - if (artifactData.isRight()) { - log.debug("Failed to retrieve artifact for id = {}", artifactId); - return Either.right(artifactData.right().value()); - } - ArtifactDataDefinition artifactDefinition = artifactData.left().value().getArtifactDataDefinition(); - boolean isMandatory = false; - if ((artifactDefinition.getMandatory() || artifactDefinition.getServiceApi()) && !deleteMandatoryArtifact) { - // return Either.left(artifactData.left().value()); - isMandatory = true; - } - - @SuppressWarnings("unchecked") - Iterable<TitanVertex> verticesArtifact = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId).vertices(); - Iterator<TitanVertex> iterator = verticesArtifact.iterator(); - if (!iterator.hasNext()) { - log.debug("No artifact node for id = {}", artifactId); - return Either.right(TitanOperationStatus.NOT_FOUND); - } - Vertex artifactV = iterator.next(); - Iterator<Edge> iterEdge = artifactV.edges(Direction.IN, GraphEdgeLabels.ARTIFACT_REF.getProperty()); - int edgeCount = 0; - Edge edgeFromTo = null; - while (iterEdge.hasNext()) { - Edge edge = iterEdge.next(); - Vertex vertexFrom = edge.outVertex(); - String vertexId = vertexFrom.value(UniqueIdBuilder.getKeyByNodeType(type)); - if (id.equals(vertexId)) { - edgeFromTo = edge; - } - ++edgeCount; - } - if (edgeFromTo == null) { - log.debug("No relation between artifact = {} and node with id = {}", artifactId, id); - return Either.right(TitanOperationStatus.GENERAL_ERROR); - } - - // need to remove relation from resource/interface - - log.debug("remove edge {}", edgeFromTo); - if (!isMandatory || (isMandatory && edgeCount > 1)) { - edgeFromTo.remove(); - } - - // delete edges from all groups under the component id which related to - // this artifact. - // Also in case it is a mandatory artifact. - Either<List<GraphRelation>, TitanOperationStatus> dissociateAllGroups = groupOperation.dissociateAllGroupsFromArtifactOnGraph(id, type, artifactId); - if (dissociateAllGroups.isRight()) { - TitanOperationStatus status = dissociateAllGroups.right().value(); - if (status != TitanOperationStatus.NOT_FOUND && status != TitanOperationStatus.OK) { - return Either.right(status); - } - } - - if (edgeCount == 1) { - // remove artifactRef node - log.debug("Remove artifactRef node from graph"); - Either<List<HeatParameterDefinition>, StorageOperationStatus> deleteStatus = heatParametersOperation.deleteAllHeatParametersAssociatedToNode(NodeTypeEnum.ArtifactRef, artifactId); - if (deleteStatus.isRight()) { - log.error("failed to delete heat parameters of artifact {}", artifactId); - return Either.right(TitanOperationStatus.GENERAL_ERROR); - } - - StorageOperationStatus deleteValuesStatus = heatParametersOperation.deleteAllHeatValuesAssociatedToNode(NodeTypeEnum.ArtifactRef, artifactId); - if (!deleteValuesStatus.equals(StorageOperationStatus.OK)) { - log.error("failed to delete heat values of artifact {}", artifactId); - return Either.right(TitanOperationStatus.GENERAL_ERROR); - } - if (!isMandatory) { - artifactV.remove(); - } - } else { - log.debug("artifactRef have more connection. ArtifactRef node will not be removed "); - } - - return Either.left(artifactData.left().value()); - - } - - /** - * - * @param parentId - * @param parentType - * @param inTransaction - * @return - */ - public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, boolean inTransaction) { - Either<Map<String, ArtifactDefinition>, StorageOperationStatus> result = null; - try { - Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph(); - if (graph.isRight()) { - log.debug("Failed to work with graph {}", graph.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value())); - } - TitanGraph tGraph = graph.left().value(); - @SuppressWarnings("unchecked") - Iterable<TitanVertex> vertices = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(parentType), parentId).vertices(); - if (vertices == null) { - log.debug("No nodes for type {} for id = {}", parentType, parentId); - result = Either.right(StorageOperationStatus.NOT_FOUND); - return result; - } - Iterator<TitanVertex> iterator = vertices.iterator(); - - Map<String, ArtifactDefinition> artifactMap = new HashMap<String, ArtifactDefinition>(); - while (iterator.hasNext()) { - Vertex vertex = iterator.next(); - Iterator<Edge> iteratorEdge = vertex.edges(Direction.OUT, GraphEdgeLabels.ARTIFACT_REF.getProperty()); - - if (iteratorEdge != null) { - - while (iteratorEdge.hasNext()) { - Edge edge = iteratorEdge.next(); - - Vertex artifactV = edge.inVertex(); - - Map<String, Object> properties = this.titanGenericDao.getProperties(artifactV); - ArtifactData artifact = GraphElementFactory.createElement(NodeTypeEnum.ArtifactRef.getName(), GraphElementTypeEnum.Node, properties, ArtifactData.class); - if (artifact != null) { - - ArtifactDefinition artifactDefinition = new ArtifactDefinition(artifact.getArtifactDataDefinition()); - Iterator<Edge> edgesGeneratedFrom = artifactV.edges(Direction.OUT, GraphEdgeLabels.GENERATED_FROM.getProperty()); - if (edgesGeneratedFrom != null && edgesGeneratedFrom.hasNext()) { - TitanVertex inVertex = (TitanVertex) edgesGeneratedFrom.next().inVertex(); - String artifactIdGeneratedFrom = (String) titanGenericDao.getProperty(inVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty()); - artifactDefinition.setGeneratedFromId(artifactIdGeneratedFrom); - } - List<HeatParameterDefinition> heatParams = new ArrayList<HeatParameterDefinition>(); - StorageOperationStatus heatParametersStatus = heatParametersOperation.getHeatParametersOfNode(NodeTypeEnum.ArtifactRef, artifactDefinition.getUniqueId(), heatParams); - if (!heatParametersStatus.equals(StorageOperationStatus.OK)) { - log.debug("failed to get heat parameters for node {} {}", parentType.getName(), parentId); - return Either.right(heatParametersStatus); - } - if (!heatParams.isEmpty()) { - artifactDefinition.setListHeatParameters(heatParams); - } - artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); - log.debug("Artifact was added to list {}", artifact.getUniqueId()); - } - } - } - } - result = Either.left(artifactMap); - return result; - } finally { - if (inTransaction == false) { - if (result == null || result.isRight()) { - this.titanGenericDao.rollback(); - } else { - this.titanGenericDao.commit(); - } - - } - } - - } - - private void updateUUID(ArtifactDataDefinition artifactData, String oldChecksum, String oldVesrion) { - if (oldVesrion == null || oldVesrion.isEmpty()) - oldVesrion = "0"; - - String currentChecksum = artifactData.getArtifactChecksum(); - if (oldChecksum == null || oldChecksum.isEmpty()) { - if (currentChecksum != null) { - generateUUID(artifactData, oldVesrion); - } - } else if ((currentChecksum != null && !currentChecksum.isEmpty()) && !oldChecksum.equals(currentChecksum)) { - generateUUID(artifactData, oldVesrion); - } - - } - - private void generateUUID(ArtifactDataDefinition artifactData, String oldVesrion) { - - UUID uuid = UUID.randomUUID(); - artifactData.setArtifactUUID(uuid.toString()); - MDC.put("serviceInstanceID", uuid.toString()); - updateVersionAndDate(artifactData, oldVesrion); - } - - private void updateVersionAndDate(ArtifactDataDefinition artifactData, String oldVesrion) { - long time = System.currentTimeMillis(); - artifactData.setPayloadUpdateDate(time); - int newVersion = new Integer(oldVesrion).intValue(); - newVersion++; - artifactData.setArtifactVersion(String.valueOf(newVersion)); - } + private TitanGenericDao titanGenericDao; + + @javax.annotation.Resource + private HeatParametersOperation heatParametersOperation; + + @javax.annotation.Resource + private GroupOperation groupOperation; + @javax.annotation.Resource + private GroupInstanceOperation groupInstanceOperation; + + private static final Logger log = Logger.getLogger(ArtifactOperation.class.getName()); + + public ArtifactOperation() { + super(); + } + + public TitanGenericDao getTitanGenericDao() { + return titanGenericDao; + } + + public void setTitanGenericDao(TitanGenericDao titanGenericDao) { + this.titanGenericDao = titanGenericDao; + } + + public HeatParametersOperation getHeatParametersOperation() { + return heatParametersOperation; + } + + public void setHeatParametersOperation(HeatParametersOperation heatParametersOperation) { + 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); + + if (status.isRight()) { + if (!inTransaction) { + titanGenericDao.rollback(); + } + log.debug("Failed to add artifact {} to {} {}", artifactInfo.getArtifactName(), type , parentId); + return Either.right(status.right().value()); + } else { + if (!inTransaction) { + titanGenericDao.commit(); + } + ArtifactData artifactData = status.left().value(); + + ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(artifactData); + + log.debug(THE_RETURNED_ARTIFACT_DEFINTION_IS, artifactDefResult); + return Either.left(artifactDefResult); + } + + } + + @Override + public StorageOperationStatus addArifactToComponent(ArtifactDefinition artifactInfo, String parentId, NodeTypeEnum type, boolean failIfExist, TitanVertex parentVertex) { + + StorageOperationStatus status = addArtifactToGraph(artifactInfo, parentId, type, failIfExist, parentVertex); + + if (status.equals(StorageOperationStatus.OK)) { + log.debug("Failed to add artifact {} {} to {}", artifactInfo.getArtifactName(), type, parentId); + } + return status; + } + + private StorageOperationStatus addArtifactToGraph(ArtifactDefinition artifactInfo, String id, NodeTypeEnum type, boolean failIfexist, TitanVertex parentVertex) { + + if (artifactInfo.getUniqueId() == null || artifactInfo.getUniqueId().isEmpty()) { + String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(id, artifactInfo.getArtifactLabel()); + artifactInfo.setUniqueId(uniqueId); + } + + if (!validateParentType(type)) { + return StorageOperationStatus.GENERAL_ERROR; + } + + ArtifactData artifactData = new ArtifactData(artifactInfo); + + Either<TitanVertex, TitanOperationStatus> existArtifact = titanGenericDao.getVertexByProperty(artifactData.getUniqueIdKey(), artifactData.getUniqueId()); + if (existArtifact.isRight()) { + if (existArtifact.right().value().equals(TitanOperationStatus.NOT_FOUND)) { + // create new node + log.debug("Before adding artifact to graph {}", artifactData); + if (artifactData.getArtifactDataDefinition().getArtifactUUID() == null || artifactData.getArtifactDataDefinition().getArtifactUUID().isEmpty()) + updateUUID(artifactData.getArtifactDataDefinition(), null, artifactData.getArtifactDataDefinition().getArtifactVersion()); + Either<TitanVertex, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(artifactData); + + if (createNodeResult.isRight()) { + TitanOperationStatus operationStatus = createNodeResult.right().value(); + log.debug("Failed to add artifact {} to graph. status is {}", artifactData.getArtifactDataDefinition().getArtifactName(), operationStatus); + BeEcompErrorManager.getInstance().logBeFailedCreateNodeError("Add artifact", artifactData.getArtifactDataDefinition().getArtifactName(), String.valueOf(operationStatus)); + return DaoStatusConverter.convertTitanStatusToStorageStatus(operationStatus); + } + + // add heat parameters + if (artifactInfo.getHeatParameters() != null && !artifactInfo.getHeatParameters().isEmpty() && !artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT_ENV.getType())) { + StorageOperationStatus addPropertiesStatus = heatParametersOperation.addPropertiesToGraph(artifactInfo.getListHeatParameters(), artifactData.getUniqueId().toString(), NodeTypeEnum.ArtifactRef); + if (addPropertiesStatus != StorageOperationStatus.OK) { + log.debug("Failed to create heat parameters on graph for artifact {}", artifactInfo.getArtifactName()); + return addPropertiesStatus; + } + } + + } else { + log.debug("Failed to check existance of artifact in graph for id {}", artifactData.getUniqueId()); + return DaoStatusConverter.convertTitanStatusToStorageStatus(existArtifact.right().value()); + } + } else if (failIfexist) { + log.debug("Artifact {} already exist", artifactData.getUniqueId()); + return DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ALREADY_EXIST); + } + + // save logical artifact ref name on edge as property + Map<String, Object> properties = new HashMap<>(); + properties.put(GraphEdgePropertiesDictionary.NAME.getProperty(), artifactInfo.getArtifactLabel()); + if (artifactInfo.getArtifactGroupType() != null) + properties.put(GraphEdgePropertiesDictionary.GROUP_TYPE.getProperty(), artifactInfo.getArtifactGroupType().getType()); + TitanOperationStatus relation = titanGenericDao.createEdge(parentVertex, artifactData, GraphEdgeLabels.ARTIFACT_REF, properties); + if (!relation.equals(TitanOperationStatus.OK)) { + log.debug("Failed to create relation in graph for id {} to new artifact", id); + return DaoStatusConverter.convertTitanStatusToStorageStatus(relation); + } + + return StorageOperationStatus.OK; + } + + private Either<ArtifactData, StorageOperationStatus> addArtifactToGraph(ArtifactDefinition artifactInfo, String id, NodeTypeEnum type, boolean failIfexist) { + + if (artifactInfo.getUniqueId() == null || artifactInfo.getUniqueId().isEmpty()) { + String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(id, artifactInfo.getArtifactLabel()); + artifactInfo.setUniqueId(uniqueId); + } + + if (!validateParentType(type)) { + return Either.right(StorageOperationStatus.GENERAL_ERROR); + } + + ArtifactData artifactData = new ArtifactData(artifactInfo); + + Either<ArtifactData, TitanOperationStatus> existArtifact = titanGenericDao.getNode(artifactData.getUniqueIdKey(), artifactData.getUniqueId(), ArtifactData.class); + if (existArtifact.isRight()) { + if (existArtifact.right().value().equals(TitanOperationStatus.NOT_FOUND)) { + // create new node + log.debug("Before adding artifact to graph {}" , artifactData); + if (artifactData.getArtifactDataDefinition().getArtifactUUID() == null || artifactData.getArtifactDataDefinition().getArtifactUUID().isEmpty()) + updateUUID(artifactData.getArtifactDataDefinition(), null, artifactData.getArtifactDataDefinition().getArtifactVersion()); + Either<ArtifactData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(artifactData, ArtifactData.class); + log.debug("After adding artifact to graph {}", artifactData); + + if (createNodeResult.isRight()) { + TitanOperationStatus operationStatus = createNodeResult.right().value(); + log.debug("Failed to add artifact {} to graph. status is {}", artifactData.getArtifactDataDefinition().getArtifactName(), operationStatus); + BeEcompErrorManager.getInstance().logBeFailedCreateNodeError("Add artifact", artifactData.getArtifactDataDefinition().getArtifactName(), String.valueOf(operationStatus)); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationStatus)); + } + artifactData = createNodeResult.left().value(); + + // add heat parameters + if (artifactInfo.getHeatParameters() != null && !artifactInfo.getHeatParameters().isEmpty() && !artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT_ENV.getType())) { + StorageOperationStatus addPropertiesStatus = heatParametersOperation.addPropertiesToGraph(artifactInfo.getListHeatParameters(), artifactData.getUniqueId().toString(), NodeTypeEnum.ArtifactRef); + if (addPropertiesStatus != StorageOperationStatus.OK) { + log.debug("Failed to create heat parameters on graph for artifact {}", artifactInfo.getArtifactName()); + return Either.right(addPropertiesStatus); + } + } + + } else { + log.debug("Failed to check existance of artifact in graph for id {}", artifactData.getUniqueId()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(existArtifact.right().value())); + } + } else if (failIfexist) { + log.debug("Artifact {} already exist", artifactData.getUniqueId()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ALREADY_EXIST)); + } else { + artifactData = existArtifact.left().value(); + } + + UniqueIdData parent = new UniqueIdData(type, id); + + // save logical artifact ref name on edge as property + Map<String, Object> properties = new HashMap<>(); + properties.put(GraphEdgePropertiesDictionary.NAME.getProperty(), artifactInfo.getArtifactLabel()); + if (artifactInfo.getArtifactGroupType() != null) + properties.put(GraphEdgePropertiesDictionary.GROUP_TYPE.getProperty(), artifactInfo.getArtifactGroupType().getType()); + Either<GraphRelation, TitanOperationStatus> relation = titanGenericDao.createRelation(parent, artifactData, GraphEdgeLabels.ARTIFACT_REF, properties); + if (relation.isRight()) { + log.debug("Failed to create relation in graph fro id {} to new artifact", id); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(relation.right().value())); + } + + return Either.left(artifactData); + } + + private boolean validateParentType(NodeTypeEnum type) { + boolean isValid = false; + switch (type) { + case Resource: + case InterfaceOperation: + case Service: + case ResourceInstance: + isValid = true; + break; + default: + log.debug("Not supported node type for artifact relation : {} ", type); + } + return isValid; + } + + + protected ArtifactDefinition convertArtifactDataToArtifactDefinition(ArtifactData artifactDefResult) { + log.debug("The object returned after create property is {}" ,artifactDefResult); + + ArtifactDefinition propertyDefResult = new ArtifactDefinition(artifactDefResult.getArtifactDataDefinition()); + List<HeatParameterDefinition> parameters = new ArrayList<>(); + StorageOperationStatus heatParametersOfNode = heatParametersOperation.getHeatParametersOfNode(NodeTypeEnum.ArtifactRef, artifactDefResult.getUniqueId().toString(), parameters); + if ((heatParametersOfNode.equals(StorageOperationStatus.OK)) && !parameters.isEmpty()) { + propertyDefResult.setListHeatParameters(parameters); + } + 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); + + if (status.isRight()) { + if (!inTransaction) { + titanGenericDao.rollback(); + } + log.debug("Failed to update artifact {} of {} {}. status is {}", artifactId, type.getName(), id, status.right().value()); + BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("Update Artifact", artifactId, String.valueOf(status.right().value())); + return Either.right(status.right().value()); + } else { + if (!inTransaction) { + titanGenericDao.commit(); + } + ArtifactData artifactData = status.left().value(); + + ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(artifactData); + log.debug(THE_RETURNED_ARTIFACT_DEFINTION_IS, artifactDefResult); + return Either.left(artifactDefResult); + } + } + + @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); + + if (status.isRight()) { + if (!inTransaction) { + titanGenericDao.rollback(); + } + log.debug("Failed to delete artifact {} of resource {}", artifactId, id); + + BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError("Delete Artifact", artifactId, String.valueOf(status.right().value())); + return Either.right(status.right().value()); + } else { + if (!inTransaction) { + titanGenericDao.commit(); + } + ArtifactData artifactData = status.left().value(); + + ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(artifactData); + log.debug(THE_RETURNED_ARTIFACT_DEFINTION_IS , artifactDefResult); + return Either.left(artifactDefResult); + } + } + + @SuppressWarnings("null") + private Either<ArtifactData, StorageOperationStatus> updateArtifactOnGraph(ArtifactDefinition artifactInfo, String artifactId, NodeTypeEnum type, String id) { + + Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph(); + if (graph.isRight()) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value())); + } + + TitanGraph tGraph = graph.left().value(); + + @SuppressWarnings("unchecked") + Iterable<TitanVertex> verticesArtifact = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId).vertices(); + Iterator<TitanVertex> iterator = verticesArtifact.iterator(); + if (!iterator.hasNext()) { + log.debug("No artifact node for id = {}", artifactId); + return Either.right(StorageOperationStatus.NOT_FOUND); + } + TitanVertex artifactV = iterator.next(); + + Iterator<Edge> iterEdge = artifactV.edges(Direction.IN, GraphEdgeLabels.ARTIFACT_REF.getProperty()); + + int edgeCount = 0; + Edge edgeFromTo = null; + while (iterEdge.hasNext()) { + Edge edge = iterEdge.next(); + Vertex vertexFrom = edge.outVertex(); + String vertexId = vertexFrom.value(UniqueIdBuilder.getKeyByNodeType(type)); + if (id.equals(vertexId)) { + edgeFromTo = edge; + } + ++edgeCount; + } + + if (isNeedUpdateHeatTime(artifactInfo)) { + artifactInfo.setHeatParamsUpdateDate(System.currentTimeMillis()); + } + + ArtifactData artifactData = new ArtifactData(artifactInfo); + if (edgeFromTo == null) { + log.debug("No relation between artifact = {} and node with id = {}", artifactId, id); + return Either.right(StorageOperationStatus.GENERAL_ERROR); + } + + Either<Boolean, StorageOperationStatus> setRelevantHeatParamIdRes = null; + if (edgeCount > 1) { + // need to remove relation, create new node + log.debug("artifactRef have more connection. Need to clone node"); + log.debug("remove edge {}", edgeFromTo); + edgeFromTo.remove(); + // update resource id in new artifact node + String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(id, artifactInfo.getArtifactLabel()); + artifactInfo.setUniqueId(uniqueId); + // update UUID and artifact version + String oldChecksum = artifactV.valueOrNull(titanGenericDao.getGraph().left().value().getPropertyKey(GraphPropertiesDictionary.ARTIFACT_CHECKSUM.getProperty())); + String oldVersion = artifactV.valueOrNull(titanGenericDao.getGraph().left().value().getPropertyKey(GraphPropertiesDictionary.ARTIFACT_VERSION.getProperty())); + updateUUID(artifactInfo, oldChecksum, oldVersion); + log.debug("try to create new artifact ref node for id {}", uniqueId); + Either<ArtifactData, StorageOperationStatus> addedArtifactRes = addArtifactToGraph(artifactInfo, id, type, true); + + if (addedArtifactRes.isLeft()) { + // remove all relations between groups to the old artifact + // add relation between the same groups to the new artifact + StorageOperationStatus reassociateGroupsFromArtifact = groupOperation.dissociateAndAssociateGroupsFromArtifact(id, type, artifactId, addedArtifactRes.left().value(), true); + if (reassociateGroupsFromArtifact != StorageOperationStatus.OK) { + BeEcompErrorManager.getInstance().logInternalFlowError("UpdateArtifact", "Failed to reassociate groups to the new artifact", ErrorSeverity.ERROR); + return Either.right(reassociateGroupsFromArtifact); + } + + StorageOperationStatus reassociateGroupInstancesFromArtifact = groupInstanceOperation.dissociateAndAssociateGroupsInstanceFromArtifact(id, type, artifactId, addedArtifactRes.left().value()); + if (reassociateGroupInstancesFromArtifact != StorageOperationStatus.OK) { + BeEcompErrorManager.getInstance().logInternalFlowError("UpdateArtifact", "Failed to reassociate group instances to the new artifact", ErrorSeverity.ERROR); + return Either.right(reassociateGroupsFromArtifact); + } + + // If artifact is heat env + if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT_ENV.getType())) { + ArtifactData addedArtifact = addedArtifactRes.left().value(); + String newArtifactUniqueId = addedArtifact.getUniqueId(); + Either<HeatParameterValueData, StorageOperationStatus> updateResult = null; + + setRelevantHeatParamIdRes = setRelevantHeatParamId(artifactV, artifactInfo); + if (setRelevantHeatParamIdRes.isRight()) { + log.error("Failed to set relevant id to heat parameters for heat env artifact {}. Status is {}", artifactInfo.getUniqueId(), setRelevantHeatParamIdRes.right().value()); + return Either.right(setRelevantHeatParamIdRes.right().value()); + } + for (HeatParameterDefinition heatEnvParam : artifactInfo.getListHeatParameters()) { + updateResult = heatParametersOperation.updateHeatParameterValue(heatEnvParam, newArtifactUniqueId, id, artifactInfo.getArtifactLabel()); + if (updateResult.isRight()) { + log.error("Failed to update heat parameter {}. Status is {}", heatEnvParam.getName(), updateResult.right().value()); + return Either.right(updateResult.right().value()); + } + } + + Iterator<Edge> iterEdgeGeneratedFrom = artifactV.edges(Direction.OUT, GraphEdgeLabels.GENERATED_FROM.getProperty()); + + if (!iterEdgeGeneratedFrom.hasNext()) { + log.error("No heat artifact node for id = {}", artifactId); + return Either.right(StorageOperationStatus.NOT_FOUND); + } + Edge edgeToHeat = iterEdgeGeneratedFrom.next(); + Vertex vertexIn = edgeToHeat.inVertex(); + String generatedFromArtifactId = vertexIn.value(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef)); + UniqueIdData generatedFromArtifactNode = new UniqueIdData(NodeTypeEnum.ArtifactRef, generatedFromArtifactId); + Either<GraphRelation, TitanOperationStatus> createRelationToGeneratedFromArtifactRes = titanGenericDao.createRelation(addedArtifact, generatedFromArtifactNode, GraphEdgeLabels.GENERATED_FROM, null); + if (createRelationToGeneratedFromArtifactRes.isRight()) { + log.error("Failed to create relation from heat_env {} to heat {}", addedArtifact.getUniqueId(), generatedFromArtifactNode); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createRelationToGeneratedFromArtifactRes.right().value())); + } + } + } + return addedArtifactRes; + + } else { + if (edgeCount == 1) { + String oldChecksum = artifactV.valueOrNull(titanGenericDao.getGraph().left().value().getPropertyKey(GraphPropertiesDictionary.ARTIFACT_CHECKSUM.getProperty())); + String oldVersion = artifactV.valueOrNull(titanGenericDao.getGraph().left().value().getPropertyKey(GraphPropertiesDictionary.ARTIFACT_VERSION.getProperty())); + updateUUID(artifactInfo, oldChecksum, oldVersion); + // update exist + Either<ArtifactData, TitanOperationStatus> updatedArtifact = titanGenericDao.updateNode(artifactData, ArtifactData.class); + if (updatedArtifact.isRight()) { + log.debug("failed to update artifact node for id {}", artifactData.getUniqueId()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updatedArtifact.right().value())); + } + + if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT_ENV.getType())) { + Either<HeatParameterValueData, StorageOperationStatus> updateResult = null; + String artifactUniqueId = artifactInfo.getUniqueId(); + setRelevantHeatParamIdRes = setRelevantHeatParamId(artifactV, artifactInfo); + if (setRelevantHeatParamIdRes.isRight()) { + log.error("Failed to set relevant id to heat parameters for heat env artifact {}. Status is {}", artifactInfo.getUniqueId(), setRelevantHeatParamIdRes.right().value()); + return Either.right(setRelevantHeatParamIdRes.right().value()); + } + for (HeatParameterDefinition heatEnvParam : artifactInfo.getListHeatParameters()) { + updateResult = heatParametersOperation.updateHeatParameterValue(heatEnvParam, artifactUniqueId, id, artifactInfo.getArtifactLabel()); + if (updateResult.isRight()) { + log.error("Failed to update heat parameter {}. Status is {}", heatEnvParam.getName(), updateResult.right().value()); + return Either.right(updateResult.right().value()); + } + } + } else { + if (artifactData.getArtifactDataDefinition().getArtifactChecksum() == null) { + // update heat parameters only if it is not heat env + if (artifactInfo.getGeneratedFromId() == null) { + StorageOperationStatus operationStatus = heatParametersOperation.updateHeatParameters(artifactInfo.getListHeatParameters()); + if (operationStatus != StorageOperationStatus.OK) { + return Either.right(operationStatus); + } + } + } else { + Either<List<HeatParameterDefinition>, StorageOperationStatus> deleteParameters = heatParametersOperation.deleteAllHeatParametersAssociatedToNode(NodeTypeEnum.ArtifactRef, artifactInfo.getUniqueId()); + if (deleteParameters.isRight()) { + log.debug("failed to update heat parameters for artifact id {}", artifactData.getUniqueId()); + return Either.right(StorageOperationStatus.GENERAL_ERROR); + } + + StorageOperationStatus addParameters = heatParametersOperation.addPropertiesToGraph(artifactInfo.getListHeatParameters(), artifactId, NodeTypeEnum.ArtifactRef); + if (!addParameters.equals(StorageOperationStatus.OK)) { + log.debug("failed to update heat parameters for artifact id {}", artifactData.getUniqueId()); + return Either.right(StorageOperationStatus.GENERAL_ERROR); + } + + } + } + + return Either.left(updatedArtifact.left().value()); + } else { + log.debug("No relevent edges for artifact = {}", artifactId); + return Either.right(StorageOperationStatus.GENERAL_ERROR); + } + } + } + + private boolean isNeedUpdateHeatTime(ArtifactDefinition artifactInfo) { + if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT_NET.getType()) || artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT_VOL.getType())) { + return true; + } + return false; + } + + private Either<Boolean, StorageOperationStatus> setRelevantHeatParamId(TitanVertex artifactV, ArtifactDefinition artifactInfo) { + + Map<String, String> heatParametersHM = new HashMap<>(); + + Iterator<Edge> iterHeat = artifactV.edges(Direction.OUT, GraphEdgeLabels.GENERATED_FROM.getProperty()); + if (!iterHeat.hasNext()) { + log.debug("No edges with label GENERATED_FROM for the node {}" , artifactInfo.getUniqueId()); + return Either.right(StorageOperationStatus.NOT_FOUND); + } + Edge heat = iterHeat.next(); + Vertex heatVertex = heat.inVertex(); + String heatUniqueId = (String) heatVertex.value(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef)); + + Either<List<ImmutablePair<HeatParameterData, GraphEdge>>, TitanOperationStatus> getHeatParametersRes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), heatUniqueId, GraphEdgeLabels.HEAT_PARAMETER, + NodeTypeEnum.HeatParameter, HeatParameterData.class); + if (getHeatParametersRes.isRight()) { + log.debug("No heat parameters for heat artifact {}", heatUniqueId); + return Either.right(StorageOperationStatus.NOT_FOUND); + } + List<ImmutablePair<HeatParameterData, GraphEdge>> heatParameters = getHeatParametersRes.left().value(); + if (heatParameters == null) { + log.debug("No heat parameters for heat artifact {}", heatUniqueId); + return Either.right(StorageOperationStatus.NOT_FOUND); + } + for (ImmutablePair<HeatParameterData, GraphEdge> heatParamEdge : heatParameters) { + HeatParameterData heatParam = heatParamEdge.getLeft(); + heatParametersHM.put(heatParam.getName(), (String) heatParam.getUniqueId()); + } + String curName = null; + for (HeatParameterDefinition heatEnvParam : artifactInfo.getListHeatParameters()) { + curName = heatEnvParam.getName(); + if (heatParametersHM.containsKey(curName)) { + heatEnvParam.setUniqueId(heatParametersHM.get(curName)); + } + } + return Either.left(true); + } + + private Either<ArtifactData, StorageOperationStatus> removeArtifactOnGraph(String id, String artifactId, NodeTypeEnum type, boolean deleteMandatoryArtifact) { + Either<TitanGraph, StorageOperationStatus> graph = titanGenericDao.getGraph() + .right() + .map(DaoStatusConverter::convertTitanStatusToStorageStatus); + if (graph.isRight()) { + return Either.right(graph.right().value()); + } + + TitanGraph tGraph = graph.left().value(); + Either<ArtifactData, StorageOperationStatus> artifactData = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId, ArtifactData.class) + .right() + .map(DaoStatusConverter::convertTitanStatusToStorageStatus); + if (artifactData.isRight()) { + log.debug("Failed to retrieve artifact for id = {}", artifactId); + return Either.right(artifactData.right().value()); + } + ArtifactDataDefinition artifactDefinition = artifactData.left().value().getArtifactDataDefinition(); + boolean isMandatory = false; + if ((artifactDefinition.getMandatory() || artifactDefinition.getServiceApi()) && !deleteMandatoryArtifact) { + isMandatory = true; + } + + @SuppressWarnings("unchecked") + Iterable<TitanVertex> verticesArtifact = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId).vertices(); + Iterator<TitanVertex> iterator = verticesArtifact.iterator(); + if (!iterator.hasNext()) { + log.debug("No artifact node for id = {}", artifactId); + return Either.right(StorageOperationStatus.NOT_FOUND); + } + Vertex artifactV = iterator.next(); + Iterator<Edge> iterEdge = artifactV.edges(Direction.IN, GraphEdgeLabels.ARTIFACT_REF.getProperty()); + int edgeCount = 0; + Edge edgeFromTo = null; + while (iterEdge.hasNext()) { + Edge edge = iterEdge.next(); + Vertex vertexFrom = edge.outVertex(); + String vertexId = vertexFrom.value(UniqueIdBuilder.getKeyByNodeType(type)); + if (id.equals(vertexId)) { + edgeFromTo = edge; + } + ++edgeCount; + } + if (edgeFromTo == null) { + log.debug("No relation between artifact = {} and node with id = {}", artifactId, id); + return Either.right(StorageOperationStatus.GENERAL_ERROR); + } + + // need to remove relation from resource/interface + + log.debug("remove edge {}", edgeFromTo); + if (!isMandatory || (isMandatory && edgeCount > 1)) { + edgeFromTo.remove(); + } + + // delete edges from all groups under the component id which related to + // this artifact. + // Also in case it is a mandatory artifact. + Either<List<GraphRelation>, StorageOperationStatus> dissociateAllGroups = groupOperation.dissociateAllGroupsFromArtifactOnGraph(id, type, artifactId); + if (dissociateAllGroups.isRight()) { + StorageOperationStatus status = dissociateAllGroups.right().value(); + if (status != StorageOperationStatus.NOT_FOUND && status != StorageOperationStatus.OK) { + return Either.right(status); + } + } + + if (edgeCount == 1) { + // remove artifactRef node + log.debug("Remove artifactRef node from graph"); + Either<List<HeatParameterDefinition>, StorageOperationStatus> deleteStatus = heatParametersOperation.deleteAllHeatParametersAssociatedToNode(NodeTypeEnum.ArtifactRef, artifactId); + if (deleteStatus.isRight()) { + log.error("failed to delete heat parameters of artifact {}", artifactId); + return Either.right(StorageOperationStatus.GENERAL_ERROR); + } + + StorageOperationStatus deleteValuesStatus = heatParametersOperation.deleteAllHeatValuesAssociatedToNode(NodeTypeEnum.ArtifactRef, artifactId); + if (!deleteValuesStatus.equals(StorageOperationStatus.OK)) { + log.error("failed to delete heat values of artifact {}", artifactId); + return Either.right(StorageOperationStatus.GENERAL_ERROR); + } + if (!isMandatory) { + artifactV.remove(); + } + } else { + log.debug("artifactRef have more connection. ArtifactRef node will not be removed "); + } + + return Either.left(artifactData.left().value()); + + } + + /** + * + * @param parentId + * @param parentType + * @param inTransaction + * @return + */ + public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, boolean inTransaction) { + Either<Map<String, ArtifactDefinition>, StorageOperationStatus> result = null; + try { + Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph(); + if (graph.isRight()) { + log.debug("Failed to work with graph {}", graph.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value())); + } + TitanGraph tGraph = graph.left().value(); + @SuppressWarnings("unchecked") + Iterable<TitanVertex> vertices = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(parentType), parentId).vertices(); + if (vertices == null) { + log.debug("No nodes for type {} for id = {}", parentType, parentId); + result = Either.right(StorageOperationStatus.NOT_FOUND); + return result; + } + Iterator<TitanVertex> iterator = vertices.iterator(); + + Map<String, ArtifactDefinition> artifactMap = new HashMap<>(); + while (iterator.hasNext()) { + Vertex vertex = iterator.next(); + Iterator<Edge> iteratorEdge = vertex.edges(Direction.OUT, GraphEdgeLabels.ARTIFACT_REF.getProperty()); + + if (iteratorEdge != null) { + + while (iteratorEdge.hasNext()) { + Edge edge = iteratorEdge.next(); + + Vertex artifactV = edge.inVertex(); + + Map<String, Object> properties = this.titanGenericDao.getProperties(artifactV); + ArtifactData artifact = GraphElementFactory.createElement(NodeTypeEnum.ArtifactRef.getName(), GraphElementTypeEnum.Node, properties, ArtifactData.class); + if (artifact != null) { + + ArtifactDefinition artifactDefinition = new ArtifactDefinition(artifact.getArtifactDataDefinition()); + Iterator<Edge> edgesGeneratedFrom = artifactV.edges(Direction.OUT, GraphEdgeLabels.GENERATED_FROM.getProperty()); + if (edgesGeneratedFrom != null && edgesGeneratedFrom.hasNext()) { + TitanVertex inVertex = (TitanVertex) edgesGeneratedFrom.next().inVertex(); + String artifactIdGeneratedFrom = (String) titanGenericDao.getProperty(inVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty()); + artifactDefinition.setGeneratedFromId(artifactIdGeneratedFrom); + } + List<HeatParameterDefinition> heatParams = new ArrayList<>(); + StorageOperationStatus heatParametersStatus = heatParametersOperation.getHeatParametersOfNode(NodeTypeEnum.ArtifactRef, artifactDefinition.getUniqueId(), heatParams); + if (!heatParametersStatus.equals(StorageOperationStatus.OK)) { + log.debug("failed to get heat parameters for node {} {}", parentType.getName(), parentId); + return Either.right(heatParametersStatus); + } + if (!heatParams.isEmpty()) { + artifactDefinition.setListHeatParameters(heatParams); + } + artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition); + log.debug("Artifact was added to list {}", artifact.getUniqueId()); + } + } + } + } + result = Either.left(artifactMap); + return result; + } finally { + if (!inTransaction) { + if (result == null || result.isRight()) { + this.titanGenericDao.rollback(); + } else { + this.titanGenericDao.commit(); + } + + } + } + + } + + private void updateUUID(ArtifactDataDefinition artifactData, String oldChecksum, String oldVesrion) { + if (oldVesrion == null || oldVesrion.isEmpty()) + oldVesrion = "0"; + + String currentChecksum = artifactData.getArtifactChecksum(); + if (oldChecksum == null || oldChecksum.isEmpty()) { + if (currentChecksum != null) { + generateUUID(artifactData, oldVesrion); + } + } else if ((currentChecksum != null && !currentChecksum.isEmpty()) && !oldChecksum.equals(currentChecksum)) { + generateUUID(artifactData, oldVesrion); + } + + } + + private void generateUUID(ArtifactDataDefinition artifactData, String oldVesrion) { + + UUID uuid = UUID.randomUUID(); + artifactData.setArtifactUUID(uuid.toString()); + MDC.put("serviceInstanceID", uuid.toString()); + updateVersionAndDate(artifactData, oldVesrion); + } + + private void updateVersionAndDate(ArtifactDataDefinition artifactData, String oldVesrion) { + long time = System.currentTimeMillis(); + artifactData.setPayloadUpdateDate(time); + int newVersion = new Integer(oldVesrion).intValue(); + newVersion++; + artifactData.setArtifactVersion(String.valueOf(newVersion)); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CacheMangerOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CacheMangerOperation.java index d677a7e257..758e46544d 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CacheMangerOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CacheMangerOperation.java @@ -20,185 +20,172 @@ package org.openecomp.sdc.be.model.operations.impl; -import java.util.LinkedList; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - +import com.google.common.util.concurrent.ThreadFactoryBuilder; import org.openecomp.sdc.be.config.Configuration; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.titan.TitanGenericDao; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.cache.ComponentCache; import org.openecomp.sdc.be.model.cache.DaoInfo; -import org.openecomp.sdc.be.model.cache.jobs.CheckAndUpdateJob; -import org.openecomp.sdc.be.model.cache.jobs.DeleteJob; -import org.openecomp.sdc.be.model.cache.jobs.Job; -import org.openecomp.sdc.be.model.cache.jobs.OverrideJob; -import org.openecomp.sdc.be.model.cache.jobs.StoreJob; +import org.openecomp.sdc.be.model.cache.jobs.*; import org.openecomp.sdc.be.model.cache.workers.CacheWorker; import org.openecomp.sdc.be.model.cache.workers.IWorker; import org.openecomp.sdc.be.model.cache.workers.SyncWorker; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.ICacheMangerOperation; -import org.openecomp.sdc.be.workers.Manager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import com.google.common.util.concurrent.ThreadFactoryBuilder; +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import java.util.LinkedList; +import java.util.concurrent.*; /** * Created by mlando on 9/5/2016. the class is responsible for handling all cache update operations asynchronously including sync between the graph and cache and on demand update requests */ @Component("cacheManger-operation") public class CacheMangerOperation implements ICacheMangerOperation { - @Autowired - private ToscaOperationFacade toscaOperationFacade; - @Autowired - private TitanGenericDao titanGenericDao; - @Autowired - private ComponentCache componentCache; - - private static Logger log = LoggerFactory.getLogger(Manager.class.getName()); - private LinkedBlockingQueue<Job> jobQueue = null; - private int waitOnShutDownInMinutes; - private ScheduledExecutorService syncExecutor; - private ExecutorService workerExecutor; - private LinkedList<IWorker> workerList = new LinkedList<>(); - private DaoInfo daoInfo; - - /** - * constructor - */ - public CacheMangerOperation() { - } - - /** - * the method checks in the cache is enabled, if it is, it initializes all the workers according to the configuration values. - */ - @PostConstruct - public void init() { - - daoInfo = new DaoInfo(toscaOperationFacade, componentCache); - - Configuration.ApplicationL2CacheConfig applicationL2CacheConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getApplicationL2Cache(); - if (applicationL2CacheConfig != null && applicationL2CacheConfig.isEnabled()) { - Integer numberOfWorkers = applicationL2CacheConfig.getQueue().getNumberOfCacheWorkers(); - this.waitOnShutDownInMinutes = applicationL2CacheConfig.getQueue().getWaitOnShutDownInMinutes(); - jobQueue = new LinkedBlockingQueue<>(); - log.info("L2 Cache is enabled inishilsing queue"); - log.debug("initializing SyncWorker, creating {} workers"); - ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("Sync-Cache-Worker-%d").build(); - this.syncExecutor = Executors.newSingleThreadScheduledExecutor(threadFactory); - log.debug("initializing workers, creating {} cacheWorkers", numberOfWorkers); - threadFactory = new ThreadFactoryBuilder().setNameFormat("Cache-Worker-%d").build(); - String workerName = "Sync-Worker"; - Integer syncWorkerExacutionIntrval = applicationL2CacheConfig.getQueue().getSyncIntervalInSecondes(); - log.debug("starting Sync worker:{} with executions interval:{} ", workerName, syncWorkerExacutionIntrval); - SyncWorker syncWorker = new SyncWorker(workerName, this); - this.syncExecutor.scheduleAtFixedRate(syncWorker, 5 * 60, syncWorkerExacutionIntrval, TimeUnit.SECONDS); - this.workerExecutor = Executors.newFixedThreadPool(numberOfWorkers, threadFactory); - CacheWorker cacheWorker; - for (int i = 0; i < numberOfWorkers; i++) { - workerName = "Cache-Worker-" + i; - log.debug("starting Cache worker:{}", workerName); - cacheWorker = new CacheWorker(workerName, jobQueue); - this.workerExecutor.submit(cacheWorker); - this.workerList.add(cacheWorker); - } - } else { - log.info("L2 Cache is disabled"); - } - log.info("L2 Cache has been initialized and the workers are running"); - } - - /** - * the method creates a job to check it the given component is in the cach and if so is it valid if the value in the cache is not valid it will be updated. - * - * @param componentId - * the uid of the component we want to update - * @param timestamp - * the time of the component update - * @param nodeTypeEnum - * the type of the component resource/service/product - */ - @Override - public void updateComponentInCache(String componentId, long timestamp, NodeTypeEnum nodeTypeEnum) { - Configuration.ApplicationL2CacheConfig applicationL2CacheConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getApplicationL2Cache(); - if (applicationL2CacheConfig != null && applicationL2CacheConfig.isEnabled()) { - this.jobQueue.add(new CheckAndUpdateJob(daoInfo, componentId, nodeTypeEnum, timestamp)); - } - } - - public void overideComponentInCache(String componentId, long timestamp, NodeTypeEnum nodeTypeEnum) { - Configuration.ApplicationL2CacheConfig applicationL2CacheConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getApplicationL2Cache(); - if (applicationL2CacheConfig != null && applicationL2CacheConfig.isEnabled()) { - this.jobQueue.add(new OverrideJob(daoInfo, componentId, nodeTypeEnum, timestamp)); - } - } - - public void deleteComponentInCache(String componentId, long timestamp, NodeTypeEnum nodeTypeEnum) { - Configuration.ApplicationL2CacheConfig applicationL2CacheConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getApplicationL2Cache(); - if (applicationL2CacheConfig != null && applicationL2CacheConfig.isEnabled()) { - this.jobQueue.add(new DeleteJob(daoInfo, componentId, nodeTypeEnum, timestamp)); - } - } - - /** - * the method stores the given component in the cache - * - * @param component - * componet to store in cache - * @param nodeTypeEnum - * the type of the component we want to store - */ - @Override - public void storeComponentInCache(org.openecomp.sdc.be.model.Component component, NodeTypeEnum nodeTypeEnum) { - Configuration.ApplicationL2CacheConfig applicationL2CacheConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getApplicationL2Cache(); - if (applicationL2CacheConfig != null && applicationL2CacheConfig.isEnabled()) { - this.jobQueue.add(new StoreJob(daoInfo, component, nodeTypeEnum)); - } - } - - /** - * the method shutdown's all the worker's. the method has a pre set of how long it will wait for the workers to shutdown. the pre defined value is taken from the configuration. - */ - @PreDestroy - public void shutDown() { - workerExecutor.shutdown(); - syncExecutor.shutdown(); - this.workerList.forEach(e -> e.shutDown()); - try { - if (!workerExecutor.awaitTermination(this.waitOnShutDownInMinutes, TimeUnit.MINUTES)) { - log.error("timer elapsed while waiting for Cache workers to finish, forcing a shutdown. "); - } - log.debug("all Cache workers finished"); - } catch (InterruptedException e) { - log.error("failed while waiting for Cache worker", e); - } - try { - if (!workerExecutor.awaitTermination(1, TimeUnit.MINUTES)) { - log.error("timer elapsed while waiting for the Sync worker's to finish, forcing a shutdown. "); - } - log.debug("sync worker finished"); - } catch (InterruptedException e) { - log.error("failed while waiting for sync worker", e); - } - } - - public TitanGenericDao getTitanGenericDao() { - return titanGenericDao; - } - - public ComponentCache getComponentCache() { - return componentCache; - } + @Autowired + private ToscaOperationFacade toscaOperationFacade; + @Autowired + private TitanGenericDao titanGenericDao; + @Autowired + private ComponentCache componentCache; + + private static final Logger log = Logger.getLogger(CacheMangerOperation.class.getName()); + private LinkedBlockingQueue<Job> jobQueue = null; + private int waitOnShutDownInMinutes; + private ScheduledExecutorService syncExecutor; + private ExecutorService workerExecutor; + private LinkedList<IWorker> workerList = new LinkedList<>(); + private DaoInfo daoInfo; + + /** + * constructor + */ + public CacheMangerOperation() { + } + + /** + * the method checks in the cache is enabled, if it is, it initializes all the workers according to the configuration values. + */ + @PostConstruct + public void init() { + + daoInfo = new DaoInfo(toscaOperationFacade, componentCache); + + Configuration.ApplicationL2CacheConfig applicationL2CacheConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getApplicationL2Cache(); + if (applicationL2CacheConfig != null && applicationL2CacheConfig.isEnabled()) { + Integer numberOfWorkers = applicationL2CacheConfig.getQueue().getNumberOfCacheWorkers(); + this.waitOnShutDownInMinutes = applicationL2CacheConfig.getQueue().getWaitOnShutDownInMinutes(); + jobQueue = new LinkedBlockingQueue<>(); + log.info("L2 Cache is enabled initializing queue"); + log.debug("initializing SyncWorker, creating {} workers", numberOfWorkers); + ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("Sync-Cache-Worker-%d").build(); + this.syncExecutor = Executors.newSingleThreadScheduledExecutor(threadFactory); + log.debug("initializing workers, creating {} cacheWorkers", numberOfWorkers); + threadFactory = new ThreadFactoryBuilder().setNameFormat("Cache-Worker-%d").build(); + String workerName = "Sync-Worker"; + Integer syncWorkerExacutionIntrval = applicationL2CacheConfig.getQueue().getSyncIntervalInSecondes(); + log.debug("starting Sync worker:{} with executions interval:{} ", workerName, syncWorkerExacutionIntrval); + SyncWorker syncWorker = new SyncWorker(workerName, this); + this.syncExecutor.scheduleAtFixedRate(syncWorker, 5 * 60, syncWorkerExacutionIntrval, TimeUnit.SECONDS); + this.workerExecutor = Executors.newFixedThreadPool(numberOfWorkers, threadFactory); + CacheWorker cacheWorker; + for (int i = 0; i < numberOfWorkers; i++) { + workerName = "Cache-Worker-" + i; + log.debug("starting Cache worker:{}", workerName); + cacheWorker = new CacheWorker(workerName, jobQueue); + this.workerExecutor.submit(cacheWorker); + this.workerList.add(cacheWorker); + } + } else { + log.info("L2 Cache is disabled"); + } + log.info("L2 Cache has been initialized and the workers are running"); + } + + /** + * the method creates a job to check it the given component is in the cach and if so is it valid if the value in the cache is not valid it will be updated. + * + * @param componentId + * the uid of the component we want to update + * @param timestamp + * the time of the component update + * @param nodeTypeEnum + * the type of the component resource/service/product + */ + @Override + public void updateComponentInCache(String componentId, long timestamp, NodeTypeEnum nodeTypeEnum) { + Configuration.ApplicationL2CacheConfig applicationL2CacheConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getApplicationL2Cache(); + if (applicationL2CacheConfig != null && applicationL2CacheConfig.isEnabled()) { + this.jobQueue.add(new CheckAndUpdateJob(daoInfo, componentId, nodeTypeEnum, timestamp)); + } + } + + public void overideComponentInCache(String componentId, long timestamp, NodeTypeEnum nodeTypeEnum) { + Configuration.ApplicationL2CacheConfig applicationL2CacheConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getApplicationL2Cache(); + if (applicationL2CacheConfig != null && applicationL2CacheConfig.isEnabled()) { + this.jobQueue.add(new OverrideJob(daoInfo, componentId, nodeTypeEnum, timestamp)); + } + } + + public void deleteComponentInCache(String componentId, long timestamp, NodeTypeEnum nodeTypeEnum) { + Configuration.ApplicationL2CacheConfig applicationL2CacheConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getApplicationL2Cache(); + if (applicationL2CacheConfig != null && applicationL2CacheConfig.isEnabled()) { + this.jobQueue.add(new DeleteJob(daoInfo, componentId, nodeTypeEnum, timestamp)); + } + } + + /** + * the method stores the given component in the cache + * + * @param component + * componet to store in cache + * @param nodeTypeEnum + * the type of the component we want to store + */ + @Override + public void storeComponentInCache(org.openecomp.sdc.be.model.Component component, NodeTypeEnum nodeTypeEnum) { + Configuration.ApplicationL2CacheConfig applicationL2CacheConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getApplicationL2Cache(); + if (applicationL2CacheConfig != null && applicationL2CacheConfig.isEnabled()) { + this.jobQueue.add(new StoreJob(daoInfo, component, nodeTypeEnum)); + } + } + + /** + * the method shutdown's all the worker's. the method has a pre set of how long it will wait for the workers to shutdown. the pre defined value is taken from the configuration. + */ + @PreDestroy + public void shutDown() { + workerExecutor.shutdown(); + syncExecutor.shutdown(); + this.workerList.forEach(IWorker::shutDown); + try { + if (!workerExecutor.awaitTermination(this.waitOnShutDownInMinutes, TimeUnit.MINUTES)) { + log.error("timer elapsed while waiting for Cache workers to finish, forcing a shutdown. "); + } + log.debug("all Cache workers finished"); + } catch (InterruptedException e) { + log.error("failed while waiting for Cache worker", e); + } + try { + if (!workerExecutor.awaitTermination(1, TimeUnit.MINUTES)) { + log.error("timer elapsed while waiting for the Sync worker's to finish, forcing a shutdown. "); + } + log.debug("sync worker finished"); + } catch (InterruptedException e) { + log.error("failed while waiting for sync worker", e); + } + } + + public TitanGenericDao getTitanGenericDao() { + return titanGenericDao; + } + + public ComponentCache getComponentCache() { + return componentCache; + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityOperation.java index 175c695e73..7a17183921 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityOperation.java @@ -20,114 +20,398 @@ package org.openecomp.sdc.be.model.operations.impl; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.stream.Collectors; - +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Strings; +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; +import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation; import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; +import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary; +import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.dao.titan.TitanGenericDao; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.CapabilityTypeDefinition; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.operations.api.ICapabilityOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.resources.data.CapabilityData; import org.openecomp.sdc.be.resources.data.CapabilityTypeData; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; +import org.openecomp.sdc.be.resources.data.PropertyData; +import org.openecomp.sdc.be.resources.data.PropertyValueData; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.stereotype.Component; -import fj.data.Either; +import java.util.*; +import java.util.function.Function; +import java.util.stream.Collectors; + +import static org.springframework.util.CollectionUtils.isEmpty; @Component("capability-operation") -public class CapabilityOperation extends AbstractOperation implements ICapabilityOperation { - - public CapabilityOperation() { - super(); - } - - private static Logger log = LoggerFactory.getLogger(CapabilityOperation.class.getName()); - - @Autowired - private PropertyOperation propertyOperation; - - @Autowired - private TitanGenericDao titanGenericDao; - - /** - * FOR TEST ONLY - * - * @param titanGenericDao - */ - public void setTitanGenericDao(TitanGenericDao titanGenericDao) { - this.titanGenericDao = titanGenericDao; - } - - - @Override - public Either<List<PropertyDefinition>, TitanOperationStatus> validatePropertyUniqueness(Map<String, PropertyDefinition> propertiesOfCapabilityType, List<PropertyDefinition> properties) { - Either<List<PropertyDefinition>, TitanOperationStatus> result = Either.left(properties); - - for (PropertyDefinition property : properties) { - String propertyName = property.getName(); - String propertyType = property.getType(); - PropertyDefinition defaultProperty = null; - - if (propertiesOfCapabilityType.containsKey(propertyName)) { - defaultProperty = propertiesOfCapabilityType.get(propertyName); - if (propertyType != null && defaultProperty.getType() != null && !defaultProperty.getType().equals(propertyType)) { - log.error(" Property with name {} and different type already exists.", propertyName); - result = Either.right(TitanOperationStatus.PROPERTY_NAME_ALREADY_EXISTS); - } else { - property.setType(defaultProperty.getType()); - String innerType = defaultProperty.getSchema() == null ? null : defaultProperty.getSchema().getProperty() == null ? null : defaultProperty.getSchema().getProperty().getType(); - - if (property.getSchema() != null && property.getSchema().getProperty() != null) { - property.getSchema().getProperty().setType(innerType); - } - } - } - } - return result; - } - - @Override - public Either<Map<String, PropertyDefinition>, TitanOperationStatus> getAllCapabilityTypePropertiesFromAllDerivedFrom(String firstParentType) { - Map<String, PropertyDefinition> allProperies = new HashMap<>(); - return getCapabilityTypePropertiesFromDerivedFromRecursively(firstParentType, allProperies); - } - - private Either<Map<String, PropertyDefinition>, TitanOperationStatus> getCapabilityTypePropertiesFromDerivedFromRecursively(String nextParentType, Map<String, PropertyDefinition> allProperies) { - TitanOperationStatus error; - Either<List<ImmutablePair<CapabilityTypeData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), nextParentType, GraphEdgeLabels.DERIVED_FROM, - NodeTypeEnum.CapabilityType, CapabilityTypeData.class); - if (childrenNodes.isRight()) { - if (childrenNodes.right().value() != TitanOperationStatus.NOT_FOUND) { - error = childrenNodes.right().value(); - log.debug("Couldn't fetch derived from node for capability type {}, error: {}", nextParentType, error); - return Either.right(error); - } else { - log.debug("Derived from node is not found for type {} - this is OK for root capability."); - return Either.left(allProperies); - } - } else { - - Either<Map<String, PropertyDefinition>, TitanOperationStatus> allPropertiesOfCapabilityTypeRes = propertyOperation.findPropertiesOfNode(NodeTypeEnum.CapabilityType, nextParentType); - if (allPropertiesOfCapabilityTypeRes.isRight() && !allPropertiesOfCapabilityTypeRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { - error = allPropertiesOfCapabilityTypeRes.right().value(); - log.error("Failed to retrieve properties for capability type {} from graph. status is {}", nextParentType, error); - return Either.right(error); - } else if (allPropertiesOfCapabilityTypeRes.isLeft()) { - if (allProperies.isEmpty()) { - allProperies.putAll(allPropertiesOfCapabilityTypeRes.left().value()); - } else { - allProperies.putAll(allPropertiesOfCapabilityTypeRes.left().value().entrySet().stream().filter(e -> !allProperies.containsKey(e.getKey())).collect(Collectors.toMap(Entry::getKey, Entry::getValue))); - } - } - return getCapabilityTypePropertiesFromDerivedFromRecursively(childrenNodes.left().value().get(0).getLeft().getUniqueId(), allProperies); - } - } +public class CapabilityOperation extends AbstractOperation { + + + private static final Logger log = Logger.getLogger(CapabilityOperation.class.getName()); + + private final CapabilityTypeOperation capabilityTypeOperation; + private final PropertyOperation propertyOperation; + + + public CapabilityOperation(CapabilityTypeOperation capabilityTypeOperation, PropertyOperation propertyOperation) { + this.capabilityTypeOperation = capabilityTypeOperation; + this.propertyOperation = propertyOperation; + } + + + @VisibleForTesting + public void setTitanGenericDao(TitanGenericDao titanGenericDao) { + this.titanGenericDao = titanGenericDao; + } + + public Either<CapabilityData, TitanOperationStatus> addCapabilityToGraph(String resourceId, CapabilityTypeData capTypeData, CapabilityDefinition capabilityDefinition) { + + log.debug("#addCapabilityToGraph - capabilityDefinition={}", capabilityDefinition); + + String capUniqueId = UniqueIdBuilder.buildCapabilityUid(resourceId, capabilityDefinition.getName()); + CapabilityData capabilityData = buildCapabilityData(capabilityDefinition, capUniqueId); + + log.debug("addCapabilityToGraph - Before adding capability to graph. capabilityTypeData = {}", capabilityData); + Either<CapabilityData, TitanOperationStatus> createCapResult = titanGenericDao.createNode(capabilityData, CapabilityData.class); + log.debug("addCapabilityToGraph - After adding capability to graph. status is = {}", createCapResult); + + if (createCapResult.isRight()) { + TitanOperationStatus operationStatus = createCapResult.right().value(); + log.error("addCapabilityToGraph - Failed to add capability of type {} to graph. status is {}", capabilityDefinition.getType(), operationStatus); + return createCapResult; + } + + createCapResult = connectToCapabilityType(capabilityData, capTypeData) + .left() + .bind(res -> createCapabilityProperties(capabilityData, capTypeData)) + .left() + .map(res -> capabilityData); + + return createCapResult; + } + + private Either<GraphRelation, TitanOperationStatus> connectToCapabilityType(CapabilityData capabilityData, CapabilityTypeData capabilityTypeData) { + + Map<String, Object> properties = new HashMap<>(); + + String capabilityName = capabilityData.getCapabilityDataDefinition().getName(); + properties.put(GraphEdgePropertiesDictionary.NAME.getProperty(), capabilityName); + + return titanGenericDao.createRelation(capabilityData, capabilityTypeData, GraphEdgeLabels.CAPABILITY_IMPL, properties); + + } + + + /** + * @param capabilites + * @return + */ + public Either<List<CapabilityDefinition>, TitanOperationStatus> getCapabilitiesWithProps(List<ImmutablePair<CapabilityData, GraphEdge>> capabilites) { + List<Either<CapabilityDefinition, TitanOperationStatus>> listFilledCapabilitiesResults = capabilites.stream() + .map(ImmutablePair::getLeft) + .map(this::toCapabilityDefinitionWithProps) + .collect(Collectors.toList()); + + Optional<TitanOperationStatus> status = listFilledCapabilitiesResults.stream().filter(Either::isRight) + .map(res -> res.right().value()) + .findFirst(); + + if (status.isPresent()) { + return Either.right(status.get()); + } + + List<CapabilityDefinition> listCapabilities = listFilledCapabilitiesResults.stream() + .map(res -> res.left().value()) + .collect(Collectors.toList()); + + return Either.left(listCapabilities); + } + + private Either<CapabilityDefinition, TitanOperationStatus> toCapabilityDefinitionWithProps(CapabilityData capabilityData) { + CapabilityDefinition capabilityDefinition = new CapabilityDefinition(capabilityData.getCapabilityDataDefinition()); + return getCapabilityProperties(capabilityDefinition.getUniqueId(), capabilityDefinition.getType()) + .left() + .map(props -> { + capabilityDefinition.setProperties(props); + return capabilityDefinition; + }); + } + + + /** + * get all properties of the capability. + * + * the property definition is taken from the capability type. + * + * @param capabilityUid + * @return + */ + private Either<List<ComponentInstanceProperty>, TitanOperationStatus> getCapabilityProperties(String capabilityUid, String capabilityType) { + Either<CapabilityTypeDefinition, TitanOperationStatus> capabilityTypeRes = capabilityTypeOperation.getCapabilityTypeByType(capabilityType); + + if (capabilityTypeRes.isRight()) { + TitanOperationStatus status = capabilityTypeRes.right().value(); + return Either.right(status); + } + + CapabilityTypeDefinition capabilityTypeDefinition = capabilityTypeRes.left().value(); + + Either<Map<String, PropertyDefinition>, TitanOperationStatus> typesPropsRes = getPropertiesOfCapabilityTypeAndAcestors(capabilityTypeDefinition); + if (typesPropsRes.isRight()) { + TitanOperationStatus status = typesPropsRes.right().value(); + return Either.right(status); + } + + Map<String, PropertyDefinition> capabilityTypeProperties = typesPropsRes.left().value(); + + if (isEmpty(capabilityTypeProperties)) { + return Either.right(TitanOperationStatus.OK); + } + + Map<String, PropertyDefinition> uidToPropDefMap = capabilityTypeProperties.values().stream() + .collect(Collectors.toMap(PropertyDefinition::getUniqueId, Function.identity())); + + // Find all properties values on the capability + Either<List<ImmutablePair<PropertyValueData, GraphEdge>>, TitanOperationStatus> propertyValNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Capability), capabilityUid, GraphEdgeLabels.PROPERTY_VALUE, + NodeTypeEnum.PropertyValue, PropertyValueData.class); + + if (propertyValNodes.isRight()) { + return onLoadPropValuesFailure(propertyValNodes.right().value(), capabilityTypeProperties); + } + + List<ImmutablePair<PropertyValueData, GraphEdge>> propValsRelationPairs = propertyValNodes.left().value(); + if (isEmpty(propValsRelationPairs)) { + return Either.right(TitanOperationStatus.OK); + } + + List<ComponentInstanceProperty> capabilityProperties = new ArrayList<>(); + + for (ImmutablePair<PropertyValueData, GraphEdge> propValRelPair : propValsRelationPairs) { + + PropertyValueData propertyValueData = propValRelPair.getLeft(); + Either<ImmutablePair<PropertyData, GraphEdge>, TitanOperationStatus> propertyDefRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PropertyValue), propertyValueData.getUniqueId(), GraphEdgeLabels.PROPERTY_IMPL, + NodeTypeEnum.Property, PropertyData.class); + if (propertyDefRes.isRight()) { + TitanOperationStatus status = propertyDefRes.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + return Either.right(status); + } + + ImmutablePair<PropertyData, GraphEdge> propertyDefPair = propertyDefRes.left().value(); + PropertyData propertyData = propertyDefPair.left; + String propertyUniqueId = propertyData.getPropertyDataDefinition().getUniqueId(); + + PropertyDefinition propertyDefinition = uidToPropDefMap.get(propertyUniqueId); + ComponentInstanceProperty capabilityProperty = new ComponentInstanceProperty(propertyDefinition, propertyValueData.getValue(), propertyValueData.getUniqueId()); + + capabilityProperties.add(capabilityProperty); + } + + Set<String> processedProps = buildProcessedPropsSet(capabilityProperties); + + // Find all properties which does not have property value on the group. + List<ComponentInstanceProperty> leftProps = filterCapabilityTypesProps(capabilityTypeProperties, processedProps); + if (leftProps != null) { + capabilityProperties.addAll(leftProps); + } + + return Either.left(capabilityProperties); + } + + + /** + * @param capabilityProperties + * @return + */ + private Set<String> buildProcessedPropsSet(List<ComponentInstanceProperty> capabilityProperties) { + return capabilityProperties.stream() + .map(ComponentInstanceProperty::getName) + .collect(Collectors.toSet()); + } + + private Either<List<ComponentInstanceProperty>, TitanOperationStatus> onLoadPropValuesFailure(TitanOperationStatus status, Map<String, PropertyDefinition> capabilityTypeProperties) { + if (status == TitanOperationStatus.NOT_FOUND) { + return Either.left(buildPropsFromCapabilityTypeProps(capabilityTypeProperties)); + } else { + return Either.right(status); + } + } + + + /** + * @param capabilityTypeProperties + * @return + */ + private List<ComponentInstanceProperty> buildPropsFromCapabilityTypeProps(Map<String, PropertyDefinition> capabilityTypeProperties) { + return capabilityTypeProperties.values().stream() + .map(p -> new ComponentInstanceProperty(p, p.getDefaultValue(), null)) + .collect(Collectors.toList()); + } + + + /** + * @param capabilityTypeRes + * @param capabilityTypeDefinition + * @return + */ + private Either<Map<String, PropertyDefinition>, TitanOperationStatus> getPropertiesOfCapabilityTypeAndAcestors(CapabilityTypeDefinition capabilityTypeDefinition) { + // Get the properties on the group type of this capability + Map<String, PropertyDefinition> capabilityTypeProperties = capabilityTypeDefinition.getProperties(); + + String derivedFrom = capabilityTypeDefinition.getDerivedFrom(); + if (!Strings.isNullOrEmpty(derivedFrom)) { + Either<Map<String, PropertyDefinition>, TitanOperationStatus> parentPropsRes = capabilityTypeOperation.getAllCapabilityTypePropertiesFromAllDerivedFrom(derivedFrom); + if(parentPropsRes.isRight()) { + TitanOperationStatus status = parentPropsRes.right().value(); + return Either.right(status); + } + if (capabilityTypeProperties != null) { + capabilityTypeProperties.putAll(parentPropsRes.left().value()); + } else { + capabilityTypeProperties = parentPropsRes.left().value(); + } + } + + return Either.left(capabilityTypeProperties); + } + + + /** + * Create all property values of the capability and their + * relations to relevant properties of the capability type. + * + * @param capabilityDefintion + * @param capabilityTypeData + * @return + */ + private Either<List<ComponentInstanceProperty>, TitanOperationStatus> createCapabilityProperties(CapabilityData capabilityData, + CapabilityTypeData capabilityTypeData) { + + CapabilityDefinition capabilityDefintion = (CapabilityDefinition)capabilityData.getCapabilityDataDefinition(); + CapabilityTypeDefinition capabilityTypeDefinition = (CapabilityTypeDefinition)capabilityTypeData.getCapabilityTypeDataDefinition(); + + Either<Map<String, PropertyDefinition>, TitanOperationStatus> typesPropsRes = getPropertiesOfCapabilityTypeAndAcestors(capabilityTypeDefinition); + if (typesPropsRes.isRight()) { + TitanOperationStatus status = typesPropsRes.right().value(); + return Either.right(status); + } + + Map<String, PropertyDefinition> capabilityTypeProperties = typesPropsRes.left().value(); + + if (isEmpty(capabilityTypeProperties) && !isEmpty(capabilityDefintion.getProperties())) { + log.debug("#createCapabilityProperties - It's not valid if group capability has properties while corresponding capability type doesn't."); + return Either.right(TitanOperationStatus.MATCH_NOT_FOUND); + } + + Optional<TitanOperationStatus> error = capabilityDefintion.getProperties().stream() + .map(property -> createPropertyValue(property, capabilityData, capabilityTypeProperties.get(property.getName()))) + .filter(Either::isRight) + .map(result -> result.right().value()) + .findFirst(); + if (error.isPresent()) { + return Either.right(error.get()); + } + + return Either.left(capabilityDefintion.getProperties()); + } + + + /** + * @param capabilityTypeProperties + * @param excludePropsWithUniqueIds + * @return + */ + private List<ComponentInstanceProperty> filterCapabilityTypesProps(Map<String, PropertyDefinition> capabilityTypeProperties, + Set<String> excludePropsWithNames) { + return capabilityTypeProperties.values().stream() + .filter(p -> !excludePropsWithNames.contains(p.getName())) + .map(p -> new ComponentInstanceProperty(p, p.getDefaultValue(), null)) + .collect(Collectors.toList()); + } + + private Either<PropertyValueData, TitanOperationStatus> createPropertyValue(ComponentInstanceProperty capabilityProperty, + CapabilityData capabilityData, + PropertyDefinition capTypePropertyDefinition) { + if (capTypePropertyDefinition == null) { + return Either.right(TitanOperationStatus.MATCH_NOT_FOUND); + } + + CapabilityDefinition capabilityDefintion = (CapabilityDefinition)capabilityData.getCapabilityDataDefinition(); + + Either<Integer, StorageOperationStatus> indexRes = + propertyOperation.increaseAndGetObjInstancePropertyCounter(capabilityDefintion.getUniqueId(), NodeTypeEnum.Capability); + String uniqueId = UniqueIdBuilder.buildResourceInstancePropertyValueUid(capabilityDefintion.getUniqueId(), indexRes.left().value() ); + PropertyValueData propertyValueData = new PropertyValueData(); + propertyValueData.setUniqueId(uniqueId); + propertyValueData.setValue(capabilityProperty.getValue()); + Either<PropertyValueData, TitanOperationStatus> propResult = titanGenericDao.createNode(propertyValueData, PropertyValueData.class); + // It's not accepted if Capability Type doesn't have suitable property + propResult = propResult.left() + .bind(propValueData -> connectToProperty(propValueData, capTypePropertyDefinition)) + .left() + .bind(graphRelation -> connectCapability(propertyValueData, capTypePropertyDefinition.getName(), capabilityData)) + .left() + .map(graphRelation -> propertyValueData); + + propResult.left() + .foreachDoEffect(propValueData -> capabilityProperty.setUniqueId(uniqueId)); + + return propResult; + } + + private Either<GraphRelation, TitanOperationStatus> connectCapability(PropertyValueData propValueData, String name, CapabilityData capabilityData) { + Map<String, Object> properties = new HashMap<>(); + properties.put(GraphEdgePropertiesDictionary.NAME.getProperty(), name); + + return titanGenericDao.createRelation(capabilityData, propValueData, GraphEdgeLabels.PROPERTY_VALUE, properties); + } + + private Either<GraphRelation, TitanOperationStatus> connectToProperty(PropertyValueData propValueData, PropertyDefinition propertyDefinition) { + Either<PropertyData, TitanOperationStatus> dataTypesRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), + propertyDefinition.getUniqueId(), PropertyData.class); + + Map<String, Object> properties = new HashMap<>(); + properties.put(GraphEdgePropertiesDictionary.NAME.getProperty(), propertyDefinition.getName()); + + return dataTypesRes.left() + .bind(propertyData -> titanGenericDao.createRelation(propValueData, propertyData, GraphEdgeLabels.PROPERTY_IMPL, properties)); + } + + + private CapabilityData buildCapabilityData(CapabilityDefinition capabilityDefinition, String ctUniqueId) { + + CapabilityData capabilityData = new CapabilityData(capabilityDefinition); + + capabilityData.setUniqueId(ctUniqueId); + Long creationDate = capabilityData.getCreationTime(); + if (creationDate == null) { + creationDate = System.currentTimeMillis(); + } + capabilityData.setCreationTime(creationDate); + capabilityData.setModificationTime(creationDate); + return capabilityData; + } + + + public StorageOperationStatus deleteCapability(CapabilityDefinition capabilityDef) { + + return titanGenericDao.deleteChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), capabilityDef.getUniqueId(), GraphEdgeLabels.PROPERTY_VALUE, + NodeTypeEnum.PropertyValue, PropertyValueData.class) + .left() + .bind(props -> titanGenericDao.deleteNode(new CapabilityData(capabilityDef), CapabilityData.class)) + .right() + .map(DaoStatusConverter::convertTitanStatusToStorageStatus) + .right() + .on(capData -> StorageOperationStatus.OK); + } + } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperation.java index 9b31c71787..97f3e80e2a 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CapabilityTypeOperation.java @@ -20,379 +20,401 @@ package org.openecomp.sdc.be.model.operations.impl; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - +import fj.data.Either; +import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation; import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; -import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.dao.titan.TitanGenericDao; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.CapabilityTypeDefinition; import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.operations.api.ICapabilityOperation; +import org.openecomp.sdc.be.model.operations.api.DerivedFromOperation; import org.openecomp.sdc.be.model.operations.api.ICapabilityTypeOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.api.TypeOperations; import org.openecomp.sdc.be.resources.data.CapabilityTypeData; import org.openecomp.sdc.be.resources.data.PropertyData; -import org.openecomp.sdc.be.resources.data.UniqueIdData; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import fj.data.Either; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; @Component("capability-type-operation") public class CapabilityTypeOperation extends AbstractOperation implements ICapabilityTypeOperation { - @Autowired - private PropertyOperation propertyOperation; - @Autowired - private ICapabilityOperation capabilityOperation; - - public CapabilityTypeOperation() { - super(); - } - - private static Logger log = LoggerFactory.getLogger(CapabilityTypeOperation.class.getName()); - - /** - * FOR TEST ONLY - * - * @param titanGenericDao - */ - public void setTitanGenericDao(TitanGenericDao titanGenericDao) { - this.titanGenericDao = titanGenericDao; - } - - @Override - public Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType(CapabilityTypeDefinition capabilityTypeDefinition, boolean inTransaction) { - - Either<CapabilityTypeDefinition, StorageOperationStatus> result = null; - - try { - Either<CapabilityTypeDefinition, TitanOperationStatus> validationRes = validateUpdateProperties(capabilityTypeDefinition); - if (validationRes.isRight()) { - log.error("One or all properties of capability type {} not valid. status is {}", capabilityTypeDefinition, validationRes.right().value().name()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(validationRes.right().value())); - return result; - } - Either<CapabilityTypeData, TitanOperationStatus> eitherStatus = addCapabilityTypeToGraph(capabilityTypeDefinition); - - if (eitherStatus.isRight()) { - log.error("Failed to add capability {} to Graph. status is {}", capabilityTypeDefinition, eitherStatus.right().value().name()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherStatus.right().value())); - return result; - } else { - CapabilityTypeData capabilityTypeData = eitherStatus.left().value(); - - CapabilityTypeDefinition capabilityTypeDefResult = convertCTDataToCTDefinition(capabilityTypeData); - log.debug("The returned CapabilityTypeDefinition is {}", capabilityTypeDefResult); - result = Either.left(capabilityTypeDefResult); - return result; - } - } - - finally { - if (false == inTransaction) { - if (result == null || result.isRight()) { - log.error("Going to execute rollback on graph."); - titanGenericDao.rollback(); - } else { - log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } - - } - - private Either<CapabilityTypeDefinition, TitanOperationStatus> validateUpdateProperties(CapabilityTypeDefinition capabilityTypeDefinition) { - TitanOperationStatus error = null; - if (capabilityTypeDefinition.getProperties() != null && !capabilityTypeDefinition.getProperties().isEmpty() && capabilityTypeDefinition.getDerivedFrom() != null) { - Either<Map<String, PropertyDefinition>, TitanOperationStatus> allPropertiesRes = capabilityOperation.getAllCapabilityTypePropertiesFromAllDerivedFrom(capabilityTypeDefinition.getDerivedFrom()); - if (allPropertiesRes.isRight() && !allPropertiesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { - error = allPropertiesRes.right().value(); - log.debug("Couldn't fetch derived from property nodes for capability type {}, error: {}", capabilityTypeDefinition.getType(), error); - } - if (error == null && !allPropertiesRes.left().value().isEmpty()) { - Map<String, PropertyDefinition> derivedFromProperties = allPropertiesRes.left().value(); - capabilityTypeDefinition.getProperties().entrySet().stream().filter(e -> derivedFromProperties.containsKey(e.getKey()) && e.getValue().getType() == null) - .forEach(e -> e.getValue().setType(derivedFromProperties.get(e.getKey()).getType())); - - Either<List<PropertyDefinition>, TitanOperationStatus> validatePropertiesRes = capabilityOperation.validatePropertyUniqueness(allPropertiesRes.left().value(), - capabilityTypeDefinition.getProperties().values().stream().collect(Collectors.toList())); - if (validatePropertiesRes.isRight()) { - error = validatePropertiesRes.right().value(); - } - } - } - if (error == null) { - return Either.left(capabilityTypeDefinition); - } - return Either.right(error); - } - - /** - * - * convert between graph Node object to Java object - * - * @param capabilityTypeData - * @return - */ - protected CapabilityTypeDefinition convertCTDataToCTDefinition(CapabilityTypeData capabilityTypeData) { - log.debug("The object returned after create capability is {}", capabilityTypeData); - - CapabilityTypeDefinition capabilityTypeDefResult = new CapabilityTypeDefinition(capabilityTypeData.getCapabilityTypeDataDefinition()); - - return capabilityTypeDefResult; - } - - /** - * - * Add capability type to graph. - * - * 1. Add capability type node - * - * 2. Add edge between the former node to its parent(if exists) - * - * 3. Add property node and associate it to the node created at #1. (per property & if exists) - * - * @param capabilityTypeDefinition - * @return - */ - private Either<CapabilityTypeData, TitanOperationStatus> addCapabilityTypeToGraph(CapabilityTypeDefinition capabilityTypeDefinition) { - - log.debug("Got capability type {}", capabilityTypeDefinition); - - String ctUniqueId = UniqueIdBuilder.buildCapabilityTypeUid(capabilityTypeDefinition.getType()); - // capabilityTypeDefinition.setUniqueId(ctUniqueId); - - CapabilityTypeData capabilityTypeData = buildCapabilityTypeData(capabilityTypeDefinition, ctUniqueId); - - log.debug("Before adding capability type to graph. capabilityTypeData = {}", capabilityTypeData); - Either<CapabilityTypeData, TitanOperationStatus> createCTResult = titanGenericDao.createNode(capabilityTypeData, CapabilityTypeData.class); - log.debug("After adding capability type to graph. status is = {}", createCTResult); - - if (createCTResult.isRight()) { - TitanOperationStatus operationStatus = createCTResult.right().value(); - log.error("Failed to capability type {} to graph. status is {}", capabilityTypeDefinition.getType(), operationStatus); - return Either.right(operationStatus); - } - - CapabilityTypeData resultCTD = createCTResult.left().value(); - Map<String, PropertyDefinition> propertiesMap = capabilityTypeDefinition.getProperties(); - Collection<PropertyDefinition> properties = propertiesMap != null ? propertiesMap.values() : null; - Either<Map<String, PropertyData>, TitanOperationStatus> addPropertiesToCapablityType = propertyOperation.addPropertiesToElementType(resultCTD.getUniqueId(), NodeTypeEnum.CapabilityType, propertiesMap); - if (addPropertiesToCapablityType.isRight()) { - log.error("Failed add properties {} to capability {}", propertiesMap, capabilityTypeDefinition.getType()); - return Either.right(addPropertiesToCapablityType.right().value()); - } - - String derivedFrom = capabilityTypeDefinition.getDerivedFrom(); - if (derivedFrom != null) { - log.debug("Before creating relation between capability type {} to its parent {}", ctUniqueId, derivedFrom); - UniqueIdData from = new UniqueIdData(NodeTypeEnum.CapabilityType, ctUniqueId); - UniqueIdData to = new UniqueIdData(NodeTypeEnum.CapabilityType, derivedFrom); - Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(from, to, GraphEdgeLabels.DERIVED_FROM, null); - log.debug("After create relation between capability type {} to its parent {}. status is {}", ctUniqueId, derivedFrom, createRelation); - if (createRelation.isRight()) { - return Either.right(createRelation.right().value()); - } - } - - return Either.left(createCTResult.left().value()); - - } - - private CapabilityTypeData buildCapabilityTypeData(CapabilityTypeDefinition capabilityTypeDefinition, String ctUniqueId) { - - CapabilityTypeData capabilityTypeData = new CapabilityTypeData(capabilityTypeDefinition); - - capabilityTypeData.getCapabilityTypeDataDefinition().setUniqueId(ctUniqueId); - Long creationDate = capabilityTypeData.getCapabilityTypeDataDefinition().getCreationTime(); - if (creationDate == null) { - creationDate = System.currentTimeMillis(); - } - capabilityTypeData.getCapabilityTypeDataDefinition().setCreationTime(creationDate); - capabilityTypeData.getCapabilityTypeDataDefinition().setModificationTime(creationDate); - return capabilityTypeData; - } - - @Override - public Either<CapabilityTypeDefinition, StorageOperationStatus> getCapabilityType(String uniqueId, boolean inTransaction) { - - Either<CapabilityTypeDefinition, StorageOperationStatus> result = null; - try { - - Either<CapabilityTypeDefinition, TitanOperationStatus> ctResult = this.getCapabilityTypeByUid(uniqueId); - - if (ctResult.isRight()) { - TitanOperationStatus status = ctResult.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { - log.error("Failed to retrieve information on capability type {}. status is {}", uniqueId, status); - } - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(ctResult.right().value())); - return result; - } - - result = Either.left(ctResult.left().value()); - - return result; - } finally { - if (false == inTransaction) { - log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } - - - public Either<CapabilityTypeData, TitanOperationStatus> getCapabilityTypeByType(String capabilityType) { - Either<CapabilityTypeData, TitanOperationStatus> capabilityTypesRes = titanGenericDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), capabilityType, CapabilityTypeData.class); - - if (capabilityTypesRes.isRight()) { - TitanOperationStatus status = capabilityTypesRes.right().value(); - log.debug("Capability type {} cannot be found in graph. status is {}", capabilityType, status); - - return Either.right(status); - } - - CapabilityTypeData ctData = capabilityTypesRes.left().value(); - return Either.left(ctData); - } - - /** - * Build Capability type object from graph by unique id - * - * @param uniqueId - * @return - */ - public Either<CapabilityTypeDefinition, TitanOperationStatus> getCapabilityTypeByUid(String uniqueId) { - - Either<CapabilityTypeDefinition, TitanOperationStatus> result = null; - - Either<CapabilityTypeData, TitanOperationStatus> capabilityTypesRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), uniqueId, CapabilityTypeData.class); - - if (capabilityTypesRes.isRight()) { - TitanOperationStatus status = capabilityTypesRes.right().value(); - log.debug("Capability type {} cannot be found in graph. status is {}", uniqueId, status); - return Either.right(status); - } - - CapabilityTypeData ctData = capabilityTypesRes.left().value(); - CapabilityTypeDefinition capabilityTypeDefinition = new CapabilityTypeDefinition(ctData.getCapabilityTypeDataDefinition()); - - TitanOperationStatus propertiesStatus = fillProperties(uniqueId, capabilityTypeDefinition); - if (propertiesStatus != TitanOperationStatus.OK) { - log.error("Failed to fetch properties of capability type {}", uniqueId); - return Either.right(propertiesStatus); - } - - Either<ImmutablePair<CapabilityTypeData, GraphEdge>, TitanOperationStatus> parentNode = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), uniqueId, GraphEdgeLabels.DERIVED_FROM, - NodeTypeEnum.CapabilityType, CapabilityTypeData.class); - log.debug("After retrieving DERIVED_FROM node of {}. status is {}", uniqueId, parentNode); - if (parentNode.isRight()) { - TitanOperationStatus titanOperationStatus = parentNode.right().value(); - if (titanOperationStatus != TitanOperationStatus.NOT_FOUND) { - log.error("Failed to find the parent capability of capability type {}. status is {}", uniqueId, titanOperationStatus); - result = Either.right(titanOperationStatus); - return result; - } - } else { - // derived from node was found - ImmutablePair<CapabilityTypeData, GraphEdge> immutablePair = parentNode.left().value(); - CapabilityTypeData parentCT = immutablePair.getKey(); - capabilityTypeDefinition.setDerivedFrom(parentCT.getCapabilityTypeDataDefinition().getType()); - } - result = Either.left(capabilityTypeDefinition); - - return result; - } - - private TitanOperationStatus fillProperties(String uniqueId, CapabilityTypeDefinition capabilityTypeDefinition) { - - Either<Map<String, PropertyDefinition>, TitanOperationStatus> findPropertiesOfNode = propertyOperation.findPropertiesOfNode(NodeTypeEnum.CapabilityType, uniqueId); - if (findPropertiesOfNode.isRight()) { - TitanOperationStatus titanOperationStatus = findPropertiesOfNode.right().value(); - log.debug("After looking for properties of vertex {}. status is {}", uniqueId, titanOperationStatus); - if (TitanOperationStatus.NOT_FOUND.equals(titanOperationStatus)) { - return TitanOperationStatus.OK; - } else { - return titanOperationStatus; - } - } else { - Map<String, PropertyDefinition> properties = findPropertiesOfNode.left().value(); - capabilityTypeDefinition.setProperties(properties); - return TitanOperationStatus.OK; - } - } - - public Either<Boolean, StorageOperationStatus> isCapabilityTypeDerivedFrom(String childCandidateType, String parentCandidateType) { - Map<String, Object> propertiesToMatch = new HashMap<String, Object>(); - propertiesToMatch.put(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), childCandidateType); - Either<List<CapabilityTypeData>, TitanOperationStatus> getResponse = titanGenericDao.getByCriteria(NodeTypeEnum.CapabilityType, propertiesToMatch, CapabilityTypeData.class); - if (getResponse.isRight()) { - TitanOperationStatus titanOperationStatus = getResponse.right().value(); - log.debug("Couldn't fetch capability type {}, error: {}", childCandidateType, titanOperationStatus); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(titanOperationStatus)); - } - String childUniqueId = getResponse.left().value().get(0).getUniqueId(); - Set<String> travelledTypes = new HashSet<>(); - do { - travelledTypes.add(childUniqueId); - Either<List<ImmutablePair<CapabilityTypeData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), childUniqueId, GraphEdgeLabels.DERIVED_FROM, - NodeTypeEnum.CapabilityType, CapabilityTypeData.class); - if (childrenNodes.isRight()) { - if (childrenNodes.right().value() != TitanOperationStatus.NOT_FOUND) { - TitanOperationStatus titanOperationStatus = getResponse.right().value(); - log.debug("Couldn't fetch derived from node for capability type {}, error: {}", childCandidateType, titanOperationStatus); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(titanOperationStatus)); - } else { - log.debug("Derived from node is not found for type {} - this is OK for root capability."); - return Either.left(false); - } - } - String derivedFromUniqueId = childrenNodes.left().value().get(0).getLeft().getUniqueId(); - if (derivedFromUniqueId.equals(parentCandidateType)) { - log.debug("Verified that capability type {} derives from capability type {}", childCandidateType, parentCandidateType); - return Either.left(true); - } - childUniqueId = derivedFromUniqueId; - } while (!travelledTypes.contains(childUniqueId)); - // this stop condition should never be used, if we use it, we have an - // illegal cycle in graph - "derived from" hierarchy cannot be cycled. - // It's here just to avoid infinite loop in case we have such cycle. - log.error("Detected a cycle of \"derived from\" edges starting at capability type node {}", childUniqueId); - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - - /** - * FOR TEST ONLY - * - * @param propertyOperation - */ - public void setPropertyOperation(PropertyOperation propertyOperation) { - this.propertyOperation = propertyOperation; - } - - @Override - public Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType(CapabilityTypeDefinition capabilityTypeDefinition) { - - return addCapabilityType(capabilityTypeDefinition, false); - } - - @Override - public Either<CapabilityTypeDefinition, StorageOperationStatus> getCapabilityType(String uniqueId) { - return getCapabilityType(uniqueId, false); - } - + @Autowired + private PropertyOperation propertyOperation; + @Autowired + private DerivedFromOperation derivedFromOperation; + + public CapabilityTypeOperation() { + super(); + } + + private static final Logger log = Logger.getLogger(CapabilityTypeOperation.class.getName()); + + /** + * FOR TEST ONLY + * + * @param titanGenericDao + */ + public void setTitanGenericDao(TitanGenericDao titanGenericDao) { + this.titanGenericDao = titanGenericDao; + } + + @Override + public Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType(CapabilityTypeDefinition capabilityTypeDefinition, boolean inTransaction) { + + Either<CapabilityTypeDefinition, StorageOperationStatus> result = null; + + try { + Either<CapabilityTypeDefinition, StorageOperationStatus> validationRes = validateUpdateProperties(capabilityTypeDefinition); + if (validationRes.isRight()) { + log.error("#addCapabilityType - One or all properties of capability type {} not valid. status is {}", capabilityTypeDefinition, validationRes.right().value()); + return result; + } + + Either<CapabilityTypeData, StorageOperationStatus> eitherStatus = addCapabilityTypeToGraph(capabilityTypeDefinition); + + result = eitherStatus.left() + .map(CapabilityTypeData::getUniqueId) + .left() + .bind(uniqueId -> getCapabilityType(uniqueId, inTransaction)); + + if(result.isLeft()) { + log.debug("#addCapabilityType - The returned CapabilityTypeDefinition is {}", result.left().value()); + } + + return result; + } + + finally { + if (!inTransaction) { + if (result == null || result.isRight()) { + log.error("#addCapabilityType - Going to execute rollback on graph."); + titanGenericDao.rollback(); + } else { + log.debug("#addCapabilityType - Going to execute commit on graph."); + titanGenericDao.commit(); + } + } + } + + } + + public Either<Map<String, PropertyDefinition>, TitanOperationStatus> getAllCapabilityTypePropertiesFromAllDerivedFrom(String firstParentType) { + return propertyOperation.getAllTypePropertiesFromAllDerivedFrom(firstParentType, NodeTypeEnum.CapabilityType, CapabilityTypeData.class); + } + + public Either<CapabilityTypeDefinition, StorageOperationStatus> validateUpdateProperties(CapabilityTypeDefinition capabilityTypeDefinition) { + TitanOperationStatus error = null; + if (MapUtils.isNotEmpty(capabilityTypeDefinition.getProperties()) && capabilityTypeDefinition.getDerivedFrom() != null) { + Either<Map<String, PropertyDefinition>, TitanOperationStatus> allPropertiesRes = + getAllCapabilityTypePropertiesFromAllDerivedFrom(capabilityTypeDefinition.getDerivedFrom()); + if (allPropertiesRes.isRight() && !allPropertiesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { + error = allPropertiesRes.right().value(); + log.debug("Couldn't fetch derived from property nodes for capability type {}, error: {}", capabilityTypeDefinition.getType(), error); + } + if (error == null && !allPropertiesRes.left().value().isEmpty()) { + Map<String, PropertyDefinition> derivedFromProperties = allPropertiesRes.left().value(); + capabilityTypeDefinition.getProperties().entrySet().stream().filter(e -> derivedFromProperties.containsKey(e.getKey()) && e.getValue().getType() == null) + .forEach(e -> e.getValue().setType(derivedFromProperties.get(e.getKey()).getType())); + + List<PropertyDefinition> properties = capabilityTypeDefinition.getProperties().values().stream().collect(Collectors.toList()); + Either<List<PropertyDefinition>, TitanOperationStatus> validatePropertiesRes = propertyOperation.validatePropertiesUniqueness(allPropertiesRes.left().value(), + properties); + if (validatePropertiesRes.isRight()) { + error = validatePropertiesRes.right().value(); + } + } + } + if (error == null) { + return Either.left(capabilityTypeDefinition); + } + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error)); + } + + + /** + * + * convert between graph Node object to Java object + * + * @param capabilityTypeData + * @return + */ + protected CapabilityTypeDefinition convertCTDataToCTDefinition(CapabilityTypeData capabilityTypeData) { + log.debug("The object returned after create capability is {}", capabilityTypeData); + + return new CapabilityTypeDefinition(capabilityTypeData.getCapabilityTypeDataDefinition()); + } + + /** + * + * Add capability type to graph. + * + * 1. Add capability type node + * + * 2. Add edge between the former node to its parent(if exists) + * + * 3. Add property node and associate it to the node created at #1. (per property & if exists) + * + * @param capabilityTypeDefinition + * @return + */ + private Either<CapabilityTypeData, StorageOperationStatus> addCapabilityTypeToGraph(CapabilityTypeDefinition capabilityTypeDefinition) { + + log.debug("Got capability type {}", capabilityTypeDefinition); + + String ctUniqueId = UniqueIdBuilder.buildCapabilityTypeUid(capabilityTypeDefinition.getType()); + CapabilityTypeData capabilityTypeData = buildCapabilityTypeData(capabilityTypeDefinition, ctUniqueId); + + log.debug("Before adding capability type to graph. capabilityTypeData = {}", capabilityTypeData); + Either<CapabilityTypeData, TitanOperationStatus> createCTResult = titanGenericDao.createNode(capabilityTypeData, CapabilityTypeData.class); + log.debug("After adding capability type to graph. status is = {}", createCTResult); + + if (createCTResult.isRight()) { + TitanOperationStatus operationStatus = createCTResult.right().value(); + log.error("Failed to capability type {} to graph. status is {}", capabilityTypeDefinition.getType(), operationStatus); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationStatus)); + } + + CapabilityTypeData resultCTD = createCTResult.left().value(); + Map<String, PropertyDefinition> propertiesMap = capabilityTypeDefinition.getProperties(); + Either<Map<String, PropertyData>, TitanOperationStatus> addPropertiesToCapablityType = propertyOperation.addPropertiesToElementType(resultCTD.getUniqueId(), NodeTypeEnum.CapabilityType, propertiesMap); + if (addPropertiesToCapablityType.isRight()) { + log.error("Failed add properties {} to capability {}", propertiesMap, capabilityTypeDefinition.getType()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(addPropertiesToCapablityType.right().value())); + } + + return addDerivedFromRelation(capabilityTypeDefinition, ctUniqueId) + .left() + .map(updatedDerivedFrom -> createCTResult.left().value()); + + + } + + private CapabilityTypeData buildCapabilityTypeData(CapabilityTypeDefinition capabilityTypeDefinition, String ctUniqueId) { + + CapabilityTypeData capabilityTypeData = new CapabilityTypeData(capabilityTypeDefinition); + + capabilityTypeData.getCapabilityTypeDataDefinition().setUniqueId(ctUniqueId); + Long creationDate = capabilityTypeData.getCapabilityTypeDataDefinition().getCreationTime(); + if (creationDate == null) { + creationDate = System.currentTimeMillis(); + } + capabilityTypeData.getCapabilityTypeDataDefinition().setCreationTime(creationDate); + capabilityTypeData.getCapabilityTypeDataDefinition().setModificationTime(creationDate); + return capabilityTypeData; + } + + @Override + public Either<CapabilityTypeDefinition, StorageOperationStatus> getCapabilityType(String uniqueId, boolean inTransaction) { + + Either<CapabilityTypeDefinition, StorageOperationStatus> result = null; + try { + + Either<CapabilityTypeDefinition, TitanOperationStatus> ctResult = this.getCapabilityTypeByUid(uniqueId); + + if (ctResult.isRight()) { + TitanOperationStatus status = ctResult.right().value(); + if (status != TitanOperationStatus.NOT_FOUND) { + log.error("Failed to retrieve information on capability type {}. status is {}", uniqueId, status); + } + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(ctResult.right().value())); + return result; + } + + result = Either.left(ctResult.left().value()); + + return result; + } finally { + if (!inTransaction) { + log.debug("Going to execute commit on graph."); + titanGenericDao.commit(); + } + } + } + + + public Either<CapabilityTypeDefinition, TitanOperationStatus> getCapabilityTypeByType(String capabilityType) { + // Optimization: In case of Capability Type its unique ID is the same as type + return getCapabilityTypeByUid(capabilityType); + } + + /** + * Build Capability type object from graph by unique id + * + * @param uniqueId + * @return + */ + public Either<CapabilityTypeDefinition, TitanOperationStatus> getCapabilityTypeByUid(String uniqueId) { + + Either<CapabilityTypeDefinition, TitanOperationStatus> result = null; + + Either<CapabilityTypeData, TitanOperationStatus> capabilityTypesRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), uniqueId, CapabilityTypeData.class); + + if (capabilityTypesRes.isRight()) { + TitanOperationStatus status = capabilityTypesRes.right().value(); + log.debug("Capability type {} cannot be found in graph. status is {}", uniqueId, status); + return Either.right(status); + } + + CapabilityTypeData ctData = capabilityTypesRes.left().value(); + CapabilityTypeDefinition capabilityTypeDefinition = new CapabilityTypeDefinition(ctData.getCapabilityTypeDataDefinition()); + + TitanOperationStatus propertiesStatus = fillProperties(uniqueId, capabilityTypeDefinition); + if (propertiesStatus != TitanOperationStatus.OK) { + log.error("Failed to fetch properties of capability type {}", uniqueId); + return Either.right(propertiesStatus); + } + + Either<ImmutablePair<CapabilityTypeData, GraphEdge>, TitanOperationStatus> parentNode = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), uniqueId, GraphEdgeLabels.DERIVED_FROM, + NodeTypeEnum.CapabilityType, CapabilityTypeData.class); + log.debug("After retrieving DERIVED_FROM node of {}. status is {}", uniqueId, parentNode); + if (parentNode.isRight()) { + TitanOperationStatus titanOperationStatus = parentNode.right().value(); + if (titanOperationStatus != TitanOperationStatus.NOT_FOUND) { + log.error("Failed to find the parent capability of capability type {}. status is {}", uniqueId, titanOperationStatus); + result = Either.right(titanOperationStatus); + return result; + } + } else { + // derived from node was found + ImmutablePair<CapabilityTypeData, GraphEdge> immutablePair = parentNode.left().value(); + CapabilityTypeData parentCT = immutablePair.getKey(); + capabilityTypeDefinition.setDerivedFrom(parentCT.getCapabilityTypeDataDefinition().getType()); + } + result = Either.left(capabilityTypeDefinition); + + return result; + } + + private TitanOperationStatus fillProperties(String uniqueId, CapabilityTypeDefinition capabilityTypeDefinition) { + + Either<Map<String, PropertyDefinition>, TitanOperationStatus> findPropertiesOfNode = propertyOperation.findPropertiesOfNode(NodeTypeEnum.CapabilityType, uniqueId); + if (findPropertiesOfNode.isRight()) { + TitanOperationStatus titanOperationStatus = findPropertiesOfNode.right().value(); + log.debug("After looking for properties of vertex {}. status is {}", uniqueId, titanOperationStatus); + if (TitanOperationStatus.NOT_FOUND.equals(titanOperationStatus)) { + return TitanOperationStatus.OK; + } else { + return titanOperationStatus; + } + } else { + Map<String, PropertyDefinition> properties = findPropertiesOfNode.left().value(); + capabilityTypeDefinition.setProperties(properties); + return TitanOperationStatus.OK; + } + } + + public Either<Boolean, StorageOperationStatus> isCapabilityTypeDerivedFrom(String childCandidateType, String parentCandidateType) { + return derivedFromOperation.isTypeDerivedFrom(childCandidateType, parentCandidateType, null, NodeTypeEnum.CapabilityType, CapabilityTypeData.class, t -> t.getCapabilityTypeDataDefinition().getType()); + } + + + @Override + public Either<CapabilityTypeDefinition, StorageOperationStatus> updateCapabilityType(CapabilityTypeDefinition capabilityTypeDefNew, + CapabilityTypeDefinition capabilityTypeDefOld) { + log.debug("updating capability type {}", capabilityTypeDefNew.getType()); + updateCapabilityTypeData(capabilityTypeDefNew, capabilityTypeDefOld); + return updateCapabilityTypeOnGraph(capabilityTypeDefNew, capabilityTypeDefOld); + } + + + private Either<CapabilityTypeDefinition, StorageOperationStatus> updateCapabilityTypeOnGraph(CapabilityTypeDefinition capabilityTypeDefinitionNew, CapabilityTypeDefinition capabilityTypeDefinitionOld) { + return titanGenericDao.updateNode(new CapabilityTypeData(capabilityTypeDefinitionNew), CapabilityTypeData.class) + .right() + .map(DaoStatusConverter::convertTitanStatusToStorageStatus) + .left() + .bind(updatedNode -> updateProperties(capabilityTypeDefinitionNew.getUniqueId(), capabilityTypeDefinitionNew.getProperties())) + .left() + .bind(updatedProperties -> updateDerivedFrom(capabilityTypeDefinitionNew, capabilityTypeDefinitionOld.getDerivedFrom())) + .right() + .bind(result -> TypeOperations.mapOkStatus(result, null)) + .left() + .map(updatedDerivedFrom -> capabilityTypeDefinitionNew); + } + + private Either<Map<String, PropertyData>, StorageOperationStatus> updateProperties(String capabilityTypeId, Map<String, PropertyDefinition> properties) { + log.debug("#updateCapabilityTypeProperties - updating properties for capability type with id {}", capabilityTypeId); + return propertyOperation.mergePropertiesAssociatedToNode(NodeTypeEnum.CapabilityType, capabilityTypeId, properties) + .right() + .map(DaoStatusConverter::convertTitanStatusToStorageStatus); + } + + private Either<GraphRelation, StorageOperationStatus> updateDerivedFrom(CapabilityTypeDefinition updatedCapabilityType, String currDerivedFromCapabilityType) { + if( StringUtils.equals(updatedCapabilityType.getDerivedFrom(), currDerivedFromCapabilityType)) { + return Either.right(StorageOperationStatus.OK); + } + + StorageOperationStatus status = isLegalToReplaceParent(currDerivedFromCapabilityType, updatedCapabilityType.getDerivedFrom(), updatedCapabilityType.getType()); + if ( status != StorageOperationStatus.OK) { + return Either.right(status); + } + + String capabilityTypeId = updatedCapabilityType.getUniqueId(); + log.debug("#updateCapabilityTypeDerivedFrom - updating capability type derived from relation for capability type with id {}. old derived type {}. new derived type {}", capabilityTypeId, currDerivedFromCapabilityType, updatedCapabilityType.getDerivedFrom()); + StorageOperationStatus deleteDerivedRelationStatus = deleteDerivedFromCapabilityType(capabilityTypeId, currDerivedFromCapabilityType); + if (deleteDerivedRelationStatus != StorageOperationStatus.OK) { + return Either.right(deleteDerivedRelationStatus); + } + return addDerivedFromRelation(updatedCapabilityType, capabilityTypeId); + } + + private StorageOperationStatus isLegalToReplaceParent(String oldTypeParent, String newTypeParent, String childType) { + return derivedFromOperation.isUpdateParentAllowed(oldTypeParent, newTypeParent, childType, NodeTypeEnum.CapabilityType, CapabilityTypeData.class, t -> t.getCapabilityTypeDataDefinition().getType()); + } + + private Either<GraphRelation, StorageOperationStatus> addDerivedFromRelation(CapabilityTypeDefinition capabilityTypeDef, String ptUniqueId) { + String derivedFrom = capabilityTypeDef.getDerivedFrom(); + if (derivedFrom == null) { + return Either.left(null); + } + log.debug("#addDerivedFromRelationBefore - adding derived from relation between capability type {} to its parent {}", capabilityTypeDef.getType(), derivedFrom); + return this.getCapabilityType(derivedFrom, true) + .left() + .bind(derivedFromCapabilityType -> derivedFromOperation.addDerivedFromRelation(ptUniqueId, derivedFromCapabilityType.getUniqueId(), NodeTypeEnum.CapabilityType)); + } + + private StorageOperationStatus deleteDerivedFromCapabilityType(String capabilityTypeId, String derivedFromType) { + if (derivedFromType == null) { + return StorageOperationStatus.OK; + } + log.debug("#deleteDerivedFromCapabilityType - deleting derivedFrom relation for capability type with id {} and its derived type {}", capabilityTypeId, derivedFromType); + return getCapabilityType(derivedFromType, true) + .either(derivedFromNode -> derivedFromOperation.removeDerivedFromRelation(capabilityTypeId, derivedFromNode.getUniqueId(), NodeTypeEnum.CapabilityType), + err -> err); + } + + private void updateCapabilityTypeData(CapabilityTypeDefinition updatedTypeDefinition, CapabilityTypeDefinition currTypeDefinition) { + updatedTypeDefinition.setUniqueId(currTypeDefinition.getUniqueId()); + updatedTypeDefinition.setCreationTime(currTypeDefinition.getCreationTime()); + } + + + /** + * FOR TEST ONLY + * + * @param propertyOperation + */ + public void setPropertyOperation(PropertyOperation propertyOperation) { + this.propertyOperation = propertyOperation; + } + + @Override + public Either<CapabilityTypeDefinition, StorageOperationStatus> addCapabilityType(CapabilityTypeDefinition capabilityTypeDefinition) { + + return addCapabilityType(capabilityTypeDefinition, true); + } + + @Override + public Either<CapabilityTypeDefinition, StorageOperationStatus> getCapabilityType(String uniqueId) { + return getCapabilityType(uniqueId, true); + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CommonTypeOperations.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CommonTypeOperations.java new file mode 100644 index 0000000000..0189b61976 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CommonTypeOperations.java @@ -0,0 +1,84 @@ +package org.openecomp.sdc.be.model.operations.impl; + +import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; +import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; +import org.openecomp.sdc.be.dao.titan.TitanGenericDao; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.stream.Collectors; + +import static java.util.Collections.emptyList; + +@Component +public class CommonTypeOperations { + + private final TitanGenericDao titanGenericDao; + private final PropertyOperation propertyOperation; + private final OperationUtils operationUtils; + + public CommonTypeOperations(TitanGenericDao titanGenericDao, PropertyOperation propertyOperation, OperationUtils operationUtils) { + this.titanGenericDao = titanGenericDao; + this.propertyOperation = propertyOperation; + this.operationUtils = operationUtils; + } + + public <T extends GraphNode> void addType(T typeData, Class<T> clazz) { + titanGenericDao.createNode(typeData, clazz) + .left() + .on(operationUtils::onTitanOperationFailure); + } + + public <T extends GraphNode> Optional<T> getType(String uniqueId, Class<T> clazz, NodeTypeEnum nodeType) { + T type = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, clazz) + .left() + .on(err -> null); + return Optional.ofNullable(type); + } + + public <T extends GraphNode> Optional<T> getLatestType(String type, Class<T> clazz, NodeTypeEnum nodeType) { + Map<String, Object> mapCriteria = new HashMap<>(); + mapCriteria.put(GraphPropertiesDictionary.TYPE.getProperty(), type); + mapCriteria.put(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true); + return titanGenericDao.getByCriteria(nodeType, mapCriteria, clazz) + .left() + .on(err -> emptyList()) + .stream() + .findFirst(); + } + + public void addProperties(String uniqueId, NodeTypeEnum nodeType, List<PropertyDefinition> properties) { + propertyOperation.addPropertiesToElementType(uniqueId, nodeType, properties) + .left() + .on(operationUtils::onTitanOperationFailure); + } + + public void fillProperties(String uniqueId, NodeTypeEnum nodeType, Consumer<List<PropertyDefinition>> propertySetter) { + TitanOperationStatus status = propertyOperation.fillPropertiesList(uniqueId, nodeType, propertySetter); + if (status!=TitanOperationStatus.OK) { + operationUtils.onTitanOperationFailure(status); + } + } + + /** + * Handle update of type without dervidedFrom attribute + */ + public <T extends GraphNode> void updateType(T typeData, List<PropertyDefinition> properties, Class<T> clazz, NodeTypeEnum nodeType) { + titanGenericDao.updateNode(typeData, clazz) + .left() + .on(operationUtils::onTitanOperationFailure); + Map<String, PropertyDefinition> newProperties = properties.stream() + .collect(Collectors.toMap(PropertyDefinition::getName, Function.identity())); + propertyOperation.mergePropertiesAssociatedToNode(nodeType, typeData.getUniqueId(), newProperties) + .left() + .on(operationUtils::onTitanOperationFailure); + } +} 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 e67f9a4866..fb0674cf22 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 @@ -20,11 +20,9 @@ package org.openecomp.sdc.be.model.operations.impl; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; -import java.util.function.Supplier; - +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.TitanVertex; +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.apache.tinkerpop.gremlin.structure.VertexProperty; @@ -41,687 +39,667 @@ import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentInstanceInput; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.IComponentInstanceConnectedElement; +import org.openecomp.sdc.be.model.*; 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; -import org.openecomp.sdc.be.resources.data.AttributeData; -import org.openecomp.sdc.be.resources.data.AttributeValueData; -import org.openecomp.sdc.be.resources.data.ComponentInstanceData; -import org.openecomp.sdc.be.resources.data.InputValueData; -import org.openecomp.sdc.be.resources.data.InputsData; +import org.openecomp.sdc.be.resources.data.*; import org.openecomp.sdc.common.datastructure.Wrapper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.beans.factory.annotation.Autowired; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanVertex; - -import fj.data.Either; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import java.util.function.Supplier; @org.springframework.stereotype.Component("component-instance-operation") public class ComponentInstanceOperation extends AbstractOperation implements IComponentInstanceOperation { - public ComponentInstanceOperation() { - super(); - } - - private static Logger log = LoggerFactory.getLogger(ComponentInstanceOperation.class.getName()); - - @Autowired - TitanGenericDao titanGenericDao; - - @Autowired - PropertyOperation propertyOperation; - - @Autowired - private IInputsOperation inputOperation; - - @Autowired - private ApplicationDataTypeCache dataTypeCache; - - /** - * FOR TEST ONLY - * - * @param titanGenericDao - */ - public void setTitanGenericDao(TitanGenericDao titanGenericDao) { - this.titanGenericDao = titanGenericDao; - } - - @Override - public Either<Integer, StorageOperationStatus> increaseAndGetResourceInstanceSpecificCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, boolean inTransaction) { - - Either<Integer, StorageOperationStatus> result = null; - try { - - Either<TitanGraph, TitanOperationStatus> graphResult = titanGenericDao.getGraph(); - if (graphResult.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value())); - return result; - } - Either<TitanVertex, TitanOperationStatus> vertexService = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId); - if (vertexService.isRight()) { - log.debug("failed to fetch vertex of resource instance for id = {}", resourceInstanceId); - TitanOperationStatus status = vertexService.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexService.right().value())); - return result; - } - Vertex vertex = vertexService.left().value(); - - VertexProperty<Object> vertexProperty = vertex.property(counterType.getProperty()); - Integer counter = 0; - if (vertexProperty.isPresent()) { - if (vertexProperty.value() != null) { - counter = (Integer) vertexProperty.value(); - } - } - - counter++; - vertex.property(counterType.getProperty(), counter); - - result = Either.left(counter); - return result; - - } finally { - if (false == inTransaction) { - if (result == null || result.isRight()) { - log.error("increaseAndGetResourceInstanceSpecificCounter operation : Going to execute rollback on graph."); - titanGenericDao.rollback(); - } else { - log.debug("increaseAndGetResourceInstanceSpecificCounter operation : Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } - - } - - private void connectAttValueDataToComponentInstanceData(Wrapper<TitanOperationStatus> errorWrapper, ComponentInstanceData compIns, AttributeValueData attValueData) { - - Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(compIns, attValueData, GraphEdgeLabels.ATTRIBUTE_VALUE, null); - - if (createRelResult.isRight()) { - TitanOperationStatus operationStatus = createRelResult.right().value(); - errorWrapper.setInnerElement(operationStatus); - BeEcompErrorManager.getInstance().logInternalFlowError("connectAttValueDataToComponentInstanceData", - "Failed to associate resource instance " + compIns.getUniqueId() + " attribute value " + attValueData.getUniqueId() + " in graph. status is " + operationStatus, ErrorSeverity.ERROR); - } - } - - private void connectAttValueDataToAttData(Wrapper<TitanOperationStatus> errorWrapper, AttributeData attData, AttributeValueData attValueData) { - - Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(attValueData, attData, GraphEdgeLabels.ATTRIBUTE_IMPL, null); - - if (createRelResult.isRight()) { - TitanOperationStatus operationStatus = createRelResult.right().value(); - BeEcompErrorManager.getInstance().logInternalFlowError("connectAttValueDataToAttData", - "Failed to associate attribute value " + attValueData.getUniqueId() + " to attribute " + attData.getUniqueId() + " in graph. status is " + operationStatus, ErrorSeverity.ERROR); - - errorWrapper.setInnerElement(operationStatus); - } - } - - private void createAttributeValueDataNode(ComponentInstanceProperty attributeInstanceProperty, Integer index, Wrapper<TitanOperationStatus> errorWrapper, ComponentInstanceData resourceInstanceData, - Wrapper<AttributeValueData> attValueDataWrapper) { - String valueUniqueUid = attributeInstanceProperty.getValueUniqueUid(); - if (valueUniqueUid == null) { - - String attValueDatauniqueId = UniqueIdBuilder.buildResourceInstanceAttributeValueUid(resourceInstanceData.getUniqueId(), index); - AttributeValueData attributeValueData = buildAttributeValueDataFromComponentInstanceAttribute(attributeInstanceProperty, attValueDatauniqueId); - - log.debug("Before adding attribute value to graph {}", attributeValueData); - Either<AttributeValueData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(attributeValueData, AttributeValueData.class); - log.debug("After adding attribute value to graph {}", attributeValueData); - - if (createNodeResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); - errorWrapper.setInnerElement(operationStatus); - } else { - attValueDataWrapper.setInnerElement(createNodeResult.left().value()); - } - - } else { - BeEcompErrorManager.getInstance().logInternalFlowError("CreateAttributeValueDataNode", "attribute value already exists.", ErrorSeverity.ERROR); - errorWrapper.setInnerElement(TitanOperationStatus.ALREADY_EXIST); - } - } - - private AttributeValueData buildAttributeValueDataFromComponentInstanceAttribute(ComponentInstanceProperty resourceInstanceAttribute, String uniqueId) { - AttributeValueData attributeValueData = new AttributeValueData(); - attributeValueData.setUniqueId(uniqueId); - attributeValueData.setHidden(resourceInstanceAttribute.isHidden()); - attributeValueData.setValue(resourceInstanceAttribute.getValue()); - attributeValueData.setType(resourceInstanceAttribute.getType()); - long currentTimeMillis = System.currentTimeMillis(); - attributeValueData.setCreationTime(currentTimeMillis); - attributeValueData.setModificationTime(currentTimeMillis); - return attributeValueData; - } - - private static final class UpdateDataContainer<SomeData, SomeValueData> { - final Wrapper<SomeValueData> valueDataWrapper; - final Wrapper<SomeData> dataWrapper; - final GraphEdgeLabels graphEdge; - final Supplier<Class<SomeData>> someDataClassGen; - final Supplier<Class<SomeValueData>> someValueDataClassGen; - final NodeTypeEnum nodeType; - final NodeTypeEnum nodeTypeValue; - - private UpdateDataContainer(GraphEdgeLabels graphEdge, Supplier<Class<SomeData>> someDataClassGen, Supplier<Class<SomeValueData>> someValueDataClassGen, NodeTypeEnum nodeType, NodeTypeEnum nodeTypeValue) { - super(); - this.valueDataWrapper = new Wrapper<>(); - this.dataWrapper = new Wrapper<>(); - this.graphEdge = graphEdge; - this.someDataClassGen = someDataClassGen; - this.someValueDataClassGen = someValueDataClassGen; - this.nodeType = nodeType; - this.nodeTypeValue = nodeTypeValue; - } - - public Wrapper<SomeValueData> getValueDataWrapper() { - return valueDataWrapper; - } - - public Wrapper<SomeData> getDataWrapper() { - return dataWrapper; - } - - public GraphEdgeLabels getGraphEdge() { - return graphEdge; - } - - public Supplier<Class<SomeData>> getSomeDataClassGen() { - return someDataClassGen; - } - - public Supplier<Class<SomeValueData>> getSomeValueDataClassGen() { - return someValueDataClassGen; - } - - public NodeTypeEnum getNodeType() { - return nodeType; - } - - public NodeTypeEnum getNodeTypeValue() { - return nodeTypeValue; - } - } - - /** - * update value of attribute on resource instance - * - * @param resourceInstanceAttribute - * @param resourceInstanceId - * @return - */ - private Either<AttributeValueData, TitanOperationStatus> updateAttributeOfResourceInstance(ComponentInstanceProperty resourceInstanceAttribute, String resourceInstanceId) { - - Either<AttributeValueData, TitanOperationStatus> result = null; - Wrapper<TitanOperationStatus> errorWrapper = new Wrapper<>(); - UpdateDataContainer<AttributeData, AttributeValueData> updateDataContainer = new UpdateDataContainer<>(GraphEdgeLabels.ATTRIBUTE_IMPL, (() -> AttributeData.class), (() -> AttributeValueData.class), NodeTypeEnum.Attribute, - NodeTypeEnum.AttributeValue); - preUpdateElementOfResourceInstanceValidations(updateDataContainer, resourceInstanceAttribute, resourceInstanceId, errorWrapper); - if (errorWrapper.isEmpty()) { - AttributeValueData attributeValueData = updateDataContainer.getValueDataWrapper().getInnerElement(); - attributeValueData.setHidden(resourceInstanceAttribute.isHidden()); - attributeValueData.setValue(resourceInstanceAttribute.getValue()); - Either<AttributeValueData, TitanOperationStatus> updateRes = titanGenericDao.updateNode(attributeValueData, AttributeValueData.class); - if (updateRes.isRight()) { - TitanOperationStatus status = updateRes.right().value(); - errorWrapper.setInnerElement(status); - } else { - result = Either.left(updateRes.left().value()); - } - } - if (!errorWrapper.isEmpty()) { - result = Either.right(errorWrapper.getInnerElement()); - } - return result; - - } - - private Either<AttributeValueData, TitanOperationStatus> addAttributeToResourceInstance(ComponentInstanceProperty attributeInstanceProperty, String resourceInstanceId, Integer index) { - Wrapper<TitanOperationStatus> errorWrapper = new Wrapper<>(); - Wrapper<ComponentInstanceData> compInsWrapper = new Wrapper<>(); - Wrapper<AttributeData> attDataWrapper = new Wrapper<>(); - Wrapper<AttributeValueData> attValueDataWrapper = new Wrapper<>(); - - // Verify RI Exist - validateRIExist(resourceInstanceId, compInsWrapper, errorWrapper); - - if (errorWrapper.isEmpty()) { - // Verify Attribute Exist - validateElementExistInGraph(attributeInstanceProperty.getUniqueId(), NodeTypeEnum.Attribute, () -> AttributeData.class, attDataWrapper, errorWrapper); - } - if (errorWrapper.isEmpty()) { - // Create AttributeValueData that is connected to RI - createAttributeValueDataNode(attributeInstanceProperty, index, errorWrapper, compInsWrapper.getInnerElement(), attValueDataWrapper); - } - if (errorWrapper.isEmpty()) { - // Connect AttributeValueData (Att on RI) to AttData (Att on - // Resource) - connectAttValueDataToAttData(errorWrapper, attDataWrapper.getInnerElement(), attValueDataWrapper.getInnerElement()); - } - if (errorWrapper.isEmpty()) { - // Connect AttributeValueData to RI - connectAttValueDataToComponentInstanceData(errorWrapper, compInsWrapper.getInnerElement(), attValueDataWrapper.getInnerElement()); - } - - if (errorWrapper.isEmpty()) { - return Either.left(attValueDataWrapper.getInnerElement()); - } else { - return Either.right(errorWrapper.getInnerElement()); - } - - } - - private <SomeData extends GraphNode, SomeValueData extends GraphNode> void preUpdateElementOfResourceInstanceValidations(UpdateDataContainer<SomeData, SomeValueData> updateDataContainer, IComponentInstanceConnectedElement resourceInstanceProerty, - String resourceInstanceId, Wrapper<TitanOperationStatus> errorWrapper) { - - if (errorWrapper.isEmpty()) { - // Verify VFC instance Exist - validateRIExist(resourceInstanceId, errorWrapper); - } - - if (errorWrapper.isEmpty()) { - // Example: Verify Property connected to VFC exist - validateElementConnectedToComponentExist(updateDataContainer, resourceInstanceProerty, errorWrapper); - } - - if (errorWrapper.isEmpty()) { - // Example: Verify PropertyValue connected to VFC Instance exist - validateElementConnectedToComponentInstanceExist(updateDataContainer, resourceInstanceProerty, errorWrapper); - } - - if (errorWrapper.isEmpty()) { - // Example: Verify PropertyValue connected Property - validateElementConnectedToInstance(updateDataContainer, resourceInstanceProerty, errorWrapper); - } - } - - private <SomeData extends GraphNode, SomeValueData extends GraphNode> void validateElementConnectedToInstance(UpdateDataContainer<SomeData, SomeValueData> updateDataContainer, IComponentInstanceConnectedElement resourceInstanceProerty, - Wrapper<TitanOperationStatus> errorWrapper) { - Either<ImmutablePair<SomeData, GraphEdge>, TitanOperationStatus> child = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(updateDataContainer.getNodeTypeValue()), resourceInstanceProerty.getValueUniqueUid(), - updateDataContainer.getGraphEdge(), updateDataContainer.getNodeType(), updateDataContainer.getSomeDataClassGen().get()); - - if (child.isRight()) { - TitanOperationStatus status = child.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - errorWrapper.setInnerElement(status); - - } else { - updateDataContainer.getDataWrapper().setInnerElement(child.left().value().left); - } - } - - private <SomeValueData extends GraphNode, SomeData extends GraphNode> void validateElementConnectedToComponentInstanceExist(UpdateDataContainer<SomeData, SomeValueData> updateDataContainer, - IComponentInstanceConnectedElement resourceInstanceProerty, Wrapper<TitanOperationStatus> errorWrapper) { - String valueUniqueUid = resourceInstanceProerty.getValueUniqueUid(); - if (valueUniqueUid == null) { - errorWrapper.setInnerElement(TitanOperationStatus.INVALID_ID); - } else { - Either<SomeValueData, TitanOperationStatus> findPropertyValueRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(updateDataContainer.getNodeTypeValue()), valueUniqueUid, updateDataContainer.getSomeValueDataClassGen().get()); - if (findPropertyValueRes.isRight()) { - TitanOperationStatus status = findPropertyValueRes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - errorWrapper.setInnerElement(status); - } else { - updateDataContainer.getValueDataWrapper().setInnerElement(findPropertyValueRes.left().value()); - } - } - } - - private <SomeData extends GraphNode, SomeValueData extends GraphNode> void validateElementConnectedToComponentExist(UpdateDataContainer<SomeData, SomeValueData> updateDataContainer, - IComponentInstanceConnectedElement resourceInstanceElementConnected, Wrapper<TitanOperationStatus> errorWrapper) { - String uniqueId = resourceInstanceElementConnected.getUniqueId(); - Either<SomeData, TitanOperationStatus> findPropertyDefRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(updateDataContainer.getNodeType()), uniqueId, updateDataContainer.getSomeDataClassGen().get()); - - if (findPropertyDefRes.isRight()) { - TitanOperationStatus status = findPropertyDefRes.right().value(); - errorWrapper.setInnerElement(status); - } - } - - private void validateRIExist(String resourceInstanceId, Wrapper<TitanOperationStatus> errorWrapper) { - validateRIExist(resourceInstanceId, null, errorWrapper); - } - - private void validateRIExist(String resourceInstanceId, Wrapper<ComponentInstanceData> compInsDataWrapper, Wrapper<TitanOperationStatus> errorWrapper) { - validateElementExistInGraph(resourceInstanceId, NodeTypeEnum.ResourceInstance, () -> ComponentInstanceData.class, compInsDataWrapper, errorWrapper); - } - - public <ElementData extends GraphNode> void validateElementExistInGraph(String elementUniqueId, NodeTypeEnum elementNodeType, Supplier<Class<ElementData>> elementClassGen, Wrapper<ElementData> elementDataWrapper, - Wrapper<TitanOperationStatus> errorWrapper) { - Either<ElementData, TitanOperationStatus> findResInstanceRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(elementNodeType), elementUniqueId, elementClassGen.get()); - if (findResInstanceRes.isRight()) { - TitanOperationStatus status = findResInstanceRes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - errorWrapper.setInnerElement(status); - } else { - if (elementDataWrapper != null) { - elementDataWrapper.setInnerElement(findResInstanceRes.left().value()); - } - } - } - - /** - * add property to resource instance - * - * @param resourceInstanceId - * @param index - * @return - */ - private Either<InputValueData, TitanOperationStatus> addInputToResourceInstance(ComponentInstanceInput resourceInstanceInput, String resourceInstanceId, Integer index) { - - Either<ComponentInstanceData, TitanOperationStatus> findResInstanceRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId, ComponentInstanceData.class); - - if (findResInstanceRes.isRight()) { - TitanOperationStatus status = findResInstanceRes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - return Either.right(status); - } - - String propertyId = resourceInstanceInput.getUniqueId(); - Either<InputsData, TitanOperationStatus> findPropertyDefRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Input), propertyId, InputsData.class); - - if (findPropertyDefRes.isRight()) { - TitanOperationStatus status = findPropertyDefRes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - return Either.right(status); - } - - String valueUniqueUid = resourceInstanceInput.getValueUniqueUid(); - if (valueUniqueUid == null) { - - InputsData propertyData = findPropertyDefRes.left().value(); - - ComponentInstanceData resourceInstanceData = findResInstanceRes.left().value(); - - ImmutablePair<TitanOperationStatus, String> isInputValueExists = inputOperation.findInputValue(resourceInstanceId, propertyId); - if (isInputValueExists.getLeft() == TitanOperationStatus.ALREADY_EXIST) { - log.debug("The property {} already added to the resource instance {}", propertyId, resourceInstanceId); - resourceInstanceInput.setValueUniqueUid(isInputValueExists.getRight()); - /* - * Either<InputValueData, TitanOperationStatus> updatePropertyOfResourceInstance = updatePropertyOfResourceInstance(resourceInstanceInput, resourceInstanceId); if (updatePropertyOfResourceInstance.isRight()) { - * BeEcompErrorManager.getInstance().logInternalFlowError( "UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + updatePropertyOfResourceInstance.right().value(), ErrorSeverity.ERROR); - * return Either.right(updatePropertyOfResourceInstance.right().value() ); } return Either.left(updatePropertyOfResourceInstance.left().value()); - */ - } - - if (isInputValueExists.getLeft() != TitanOperationStatus.NOT_FOUND) { - log.debug("After finding input value of {} on componenet instance {}", propertyId, resourceInstanceId); - return Either.right(isInputValueExists.getLeft()); - } - - String innerType = null; - - PropertyDataDefinition propDataDef = propertyData.getPropertyDataDefinition(); - String propertyType = propDataDef.getType(); - String value = resourceInstanceInput.getValue(); - ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); - - if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { - SchemaDefinition def = propDataDef.getSchema(); - if (def == null) { - log.debug("Schema doesn't exists for property of type {}", type); - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); - } - PropertyDataDefinition propDef = def.getProperty(); - if (propDef == null) { - log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); - } - innerType = propDef.getType(); - } - - log.debug("Before validateAndUpdatePropertyValue"); - Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); - if (allDataTypes.isRight()) { - TitanOperationStatus status = allDataTypes.right().value(); - BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); - return Either.right(status); - } - - String uniqueId = UniqueIdBuilder.buildResourceInstanceInputValueUid(resourceInstanceData.getUniqueId(), index); - InputValueData propertyValueData = new InputValueData(); - propertyValueData.setUniqueId(uniqueId); - propertyValueData.setValue(value); - - log.debug("Before validateAndUpdateRules"); - ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, resourceInstanceInput.getRules(), innerType, allDataTypes.left().value(), true); - log.debug("After validateAndUpdateRules. pair = {} ", pair); - if (pair.getRight() != null && pair.getRight() == false) { - BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), resourceInstanceInput.getName(), propertyType); - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); - } - // propertyOperation.addRulesToNewPropertyValue(propertyValueData, - // resourceInstanceInput, resourceInstanceId); - - log.debug("Before adding property value to graph {}", propertyValueData); - Either<InputValueData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(propertyValueData, InputValueData.class); - log.debug("After adding property value to graph {}", propertyValueData); - - if (createNodeResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); - return Either.right(operationStatus); - } - - Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(propertyValueData, propertyData, GraphEdgeLabels.INPUT_IMPL, null); - - if (createRelResult.isRight()) { - TitanOperationStatus operationStatus = createRelResult.right().value(); - log.error("Failed to associate property value {} to property {} in graph. status is {}", uniqueId, propertyId, operationStatus); - return Either.right(operationStatus); - } - - Map<String, Object> properties1 = new HashMap<String, Object>(); - - properties1.put(GraphEdgePropertiesDictionary.NAME.getProperty(), resourceInstanceData.getComponentInstDataDefinition().getName()); - properties1.put(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), resourceInstanceData.getComponentInstDataDefinition().getUniqueId()); - - createRelResult = titanGenericDao.createRelation(resourceInstanceData, propertyValueData, GraphEdgeLabels.INPUT_VALUE, properties1); - - if (createRelResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); - log.error("Failed to associate resource instance {} property value {} in graph. status is {}", resourceInstanceId, uniqueId, operationStatus); - return Either.right(operationStatus); - - } - - return Either.left(createNodeResult.left().value()); - } else { - log.error("property value already exists."); - return Either.right(TitanOperationStatus.ALREADY_EXIST); - } - - } - - @Override - public Either<ComponentInstanceProperty, StorageOperationStatus> addAttributeValueToResourceInstance(ComponentInstanceProperty resourceInstanceAttribute, String resourceInstanceId, Integer index, boolean inTransaction) { - Either<ComponentInstanceProperty, StorageOperationStatus> result = null; - - try { - - Either<AttributeValueData, TitanOperationStatus> eitherStatus = this.addAttributeToResourceInstance(resourceInstanceAttribute, resourceInstanceId, index); - - if (eitherStatus.isRight()) { - log.error("Failed to add attribute value {} to resource instance {} in Graph. status is {}", resourceInstanceAttribute, resourceInstanceId, eitherStatus.right().value().name()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherStatus.right().value())); - return result; - } else { - AttributeValueData attributeValueData = eitherStatus.left().value(); - - ComponentInstanceProperty attributeValueResult = buildResourceInstanceAttribute(attributeValueData, resourceInstanceAttribute); - log.debug("The returned ResourceInstanceAttribute is {}", attributeValueResult); - - result = Either.left(attributeValueResult); - return result; - } - } - - finally { - handleTransactionCommitRollback(inTransaction, result); - } - } - - private ComponentInstanceProperty buildResourceInstanceAttribute(AttributeValueData attributeValueData, ComponentInstanceProperty resourceInstanceAttribute) { - Boolean hidden = attributeValueData.isHidden(); - String uid = attributeValueData.getUniqueId(); - return new ComponentInstanceProperty(hidden, resourceInstanceAttribute, uid); - } - - @Override - public Either<ComponentInstanceProperty, StorageOperationStatus> updateAttributeValueInResourceInstance(ComponentInstanceProperty resourceInstanceAttribute, String resourceInstanceId, boolean inTransaction) { - - Either<ComponentInstanceProperty, StorageOperationStatus> result = null; - - try { - Either<AttributeValueData, TitanOperationStatus> eitherAttributeValue = updateAttributeOfResourceInstance(resourceInstanceAttribute, resourceInstanceId); - - if (eitherAttributeValue.isRight()) { - log.error("Failed to add attribute value {} to resource instance {} in Graph. status is {}", resourceInstanceAttribute, resourceInstanceId, eitherAttributeValue.right().value().name()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherAttributeValue.right().value())); - return result; - } else { - AttributeValueData attributeValueData = eitherAttributeValue.left().value(); - - ComponentInstanceProperty attributeValueResult = buildResourceInstanceAttribute(attributeValueData, resourceInstanceAttribute); - log.debug("The returned ResourceInstanceAttribute is {}", attributeValueResult); - - result = Either.left(attributeValueResult); - return result; - } - } - - finally { - handleTransactionCommitRollback(inTransaction, result); - } - - } - - @Override - public Either<ComponentInstanceInput, StorageOperationStatus> addInputValueToResourceInstance(ComponentInstanceInput resourceInstanceInput, String resourceInstanceId, Integer index, boolean inTransaction) { - - /// #RULES SUPPORT - /// Ignore rules received from client till support - resourceInstanceInput.setRules(null); - /// - /// - - Either<ComponentInstanceInput, StorageOperationStatus> result = null; - - try { - - Either<InputValueData, TitanOperationStatus> eitherStatus = addInputToResourceInstance(resourceInstanceInput, resourceInstanceId, index); - - if (eitherStatus.isRight()) { - log.error("Failed to add input value {} to resource instance {} in Graph. status is {}", resourceInstanceInput, resourceInstanceId, eitherStatus.right().value().name()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherStatus.right().value())); - return result; - } else { - InputValueData propertyValueData = eitherStatus.left().value(); - - ComponentInstanceInput propertyValueResult = inputOperation.buildResourceInstanceInput(propertyValueData, resourceInstanceInput); - log.debug("The returned ResourceInstanceProperty is {}", propertyValueResult); - - Either<String, TitanOperationStatus> findDefaultValue = propertyOperation.findDefaultValueFromSecondPosition(resourceInstanceInput.getPath(), resourceInstanceInput.getUniqueId(), resourceInstanceInput.getDefaultValue()); - if (findDefaultValue.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(findDefaultValue.right().value())); - return result; - } - String defaultValue = findDefaultValue.left().value(); - propertyValueResult.setDefaultValue(defaultValue); - log.debug("The returned default value in ResourceInstanceProperty is {}", defaultValue); - - result = Either.left(propertyValueResult); - return result; - } - } - - finally { - if (false == inTransaction) { - if (result == null || result.isRight()) { - log.error("Going to execute rollback on graph."); - titanGenericDao.rollback(); - } else { - log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } - - } - - @Override - public Either<ComponentInstanceInput, StorageOperationStatus> updateInputValueInResourceInstance(ComponentInstanceInput input, String resourceInstanceId, boolean b) { - return null; - } - - @Override - public StorageOperationStatus updateCustomizationUUID(String componentInstanceId) { - Either<TitanVertex, TitanOperationStatus> vertexByProperty = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), componentInstanceId); - if (vertexByProperty.isRight()) { - log.debug("Failed to fetch component instance by id {} error {}", componentInstanceId, vertexByProperty.right().value()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(vertexByProperty.right().value()); - } - UUID uuid = UUID.randomUUID(); - TitanVertex ciVertex = vertexByProperty.left().value(); - ciVertex.property(GraphPropertiesDictionary.CUSTOMIZATION_UUID.getProperty(), uuid.toString()); - - return StorageOperationStatus.OK; - } - - @Override - public Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) { - - log.debug("Going to update modification time of component instance {}. ", componentInstance.getName()); - Either<ComponentInstanceData, StorageOperationStatus> result = null; - try{ - ComponentInstanceData componentData = new ComponentInstanceData(componentInstance, componentInstance.getGroupInstances().size()); - componentData.getComponentInstDataDefinition().setModificationTime(modificationTime); - componentData.getComponentInstDataDefinition().setCustomizationUUID(UUID.randomUUID().toString()); - Either<ComponentInstanceData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(componentData, ComponentInstanceData.class); - if (updateNode.isRight()) { - log.error("Failed to update resource {}. status is {}", componentInstance.getUniqueId(), updateNode.right().value()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value())); - }else{ - result = Either.left(updateNode.left().value()); - } - }catch(Exception e){ - log.error("Exception occured during update modification date of compomemt instance{}. The message is {}. ", componentInstance.getName(), e.getMessage(), e); - result = Either.right(StorageOperationStatus.GENERAL_ERROR); - }finally { - if(!inTransaction){ - if (result == null || result.isRight()) { - log.error("Going to execute rollback on graph."); - titanGenericDao.rollback(); - } else { - log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } - return result; - } + public ComponentInstanceOperation() { + super(); + } + + private static final Logger log = Logger.getLogger(ComponentInstanceOperation.class.getName()); + + @Autowired + PropertyOperation propertyOperation; + + @Autowired + private IInputsOperation inputOperation; + + @Autowired + private ApplicationDataTypeCache dataTypeCache; + + /** + * FOR TEST ONLY + * + * @param titanGenericDao + */ + public void setTitanGenericDao(TitanGenericDao titanGenericDao) { + this.titanGenericDao = titanGenericDao; + } + + @Override + public Either<Integer, StorageOperationStatus> increaseAndGetResourceInstanceSpecificCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, boolean inTransaction) { + + Either<Integer, StorageOperationStatus> result = null; + try { + + Either<TitanGraph, TitanOperationStatus> graphResult = titanGenericDao.getGraph(); + if (graphResult.isRight()) { + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value())); + return result; + } + Either<TitanVertex, TitanOperationStatus> vertexService = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId); + if (vertexService.isRight()) { + log.debug("failed to fetch vertex of resource instance for id = {}", resourceInstanceId); + TitanOperationStatus status = vertexService.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexService.right().value())); + return result; + } + Vertex vertex = vertexService.left().value(); + + VertexProperty<Object> vertexProperty = vertex.property(counterType.getProperty()); + Integer counter = 0; + if (vertexProperty.isPresent()) { + if (vertexProperty.value() != null) { + counter = (Integer) vertexProperty.value(); + } + } + + counter++; + vertex.property(counterType.getProperty(), counter); + + result = Either.left(counter); + return result; + + } finally { + if (!inTransaction) { + if (result == null || result.isRight()) { + log.error("increaseAndGetResourceInstanceSpecificCounter operation : Going to execute rollback on graph."); + titanGenericDao.rollback(); + } else { + log.debug("increaseAndGetResourceInstanceSpecificCounter operation : Going to execute commit on graph."); + titanGenericDao.commit(); + } + } + } + + } + + private void connectAttValueDataToComponentInstanceData(Wrapper<TitanOperationStatus> errorWrapper, ComponentInstanceData compIns, AttributeValueData attValueData) { + + Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(compIns, attValueData, GraphEdgeLabels.ATTRIBUTE_VALUE, null); + + if (createRelResult.isRight()) { + TitanOperationStatus operationStatus = createRelResult.right().value(); + errorWrapper.setInnerElement(operationStatus); + BeEcompErrorManager.getInstance().logInternalFlowError("connectAttValueDataToComponentInstanceData", + "Failed to associate resource instance " + compIns.getUniqueId() + " attribute value " + attValueData.getUniqueId() + " in graph. status is " + operationStatus, ErrorSeverity.ERROR); + } + } + + private void connectAttValueDataToAttData(Wrapper<TitanOperationStatus> errorWrapper, AttributeData attData, AttributeValueData attValueData) { + + Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(attValueData, attData, GraphEdgeLabels.ATTRIBUTE_IMPL, null); + + if (createRelResult.isRight()) { + TitanOperationStatus operationStatus = createRelResult.right().value(); + BeEcompErrorManager.getInstance().logInternalFlowError("connectAttValueDataToAttData", + "Failed to associate attribute value " + attValueData.getUniqueId() + " to attribute " + attData.getUniqueId() + " in graph. status is " + operationStatus, ErrorSeverity.ERROR); + + errorWrapper.setInnerElement(operationStatus); + } + } + + private void createAttributeValueDataNode(ComponentInstanceProperty attributeInstanceProperty, Integer index, Wrapper<TitanOperationStatus> errorWrapper, ComponentInstanceData resourceInstanceData, + Wrapper<AttributeValueData> attValueDataWrapper) { + String valueUniqueUid = attributeInstanceProperty.getValueUniqueUid(); + if (valueUniqueUid == null) { + + String attValueDatauniqueId = UniqueIdBuilder.buildResourceInstanceAttributeValueUid(resourceInstanceData.getUniqueId(), index); + AttributeValueData attributeValueData = buildAttributeValueDataFromComponentInstanceAttribute(attributeInstanceProperty, attValueDatauniqueId); + + log.debug("Before adding attribute value to graph {}", attributeValueData); + Either<AttributeValueData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(attributeValueData, AttributeValueData.class); + log.debug("After adding attribute value to graph {}", attributeValueData); + + if (createNodeResult.isRight()) { + TitanOperationStatus operationStatus = createNodeResult.right().value(); + errorWrapper.setInnerElement(operationStatus); + } else { + attValueDataWrapper.setInnerElement(createNodeResult.left().value()); + } + + } else { + BeEcompErrorManager.getInstance().logInternalFlowError("CreateAttributeValueDataNode", "attribute value already exists.", ErrorSeverity.ERROR); + errorWrapper.setInnerElement(TitanOperationStatus.ALREADY_EXIST); + } + } + + private AttributeValueData buildAttributeValueDataFromComponentInstanceAttribute(ComponentInstanceProperty resourceInstanceAttribute, String uniqueId) { + AttributeValueData attributeValueData = new AttributeValueData(); + attributeValueData.setUniqueId(uniqueId); + attributeValueData.setHidden(resourceInstanceAttribute.isHidden()); + attributeValueData.setValue(resourceInstanceAttribute.getValue()); + attributeValueData.setType(resourceInstanceAttribute.getType()); + long currentTimeMillis = System.currentTimeMillis(); + attributeValueData.setCreationTime(currentTimeMillis); + attributeValueData.setModificationTime(currentTimeMillis); + return attributeValueData; + } + + private static final class UpdateDataContainer<SomeData, SomeValueData> { + final Wrapper<SomeValueData> valueDataWrapper; + final Wrapper<SomeData> dataWrapper; + final GraphEdgeLabels graphEdge; + final Supplier<Class<SomeData>> someDataClassGen; + final Supplier<Class<SomeValueData>> someValueDataClassGen; + final NodeTypeEnum nodeType; + final NodeTypeEnum nodeTypeValue; + + private UpdateDataContainer(GraphEdgeLabels graphEdge, Supplier<Class<SomeData>> someDataClassGen, Supplier<Class<SomeValueData>> someValueDataClassGen, NodeTypeEnum nodeType, NodeTypeEnum nodeTypeValue) { + super(); + this.valueDataWrapper = new Wrapper<>(); + this.dataWrapper = new Wrapper<>(); + this.graphEdge = graphEdge; + this.someDataClassGen = someDataClassGen; + this.someValueDataClassGen = someValueDataClassGen; + this.nodeType = nodeType; + this.nodeTypeValue = nodeTypeValue; + } + + public Wrapper<SomeValueData> getValueDataWrapper() { + return valueDataWrapper; + } + + public Wrapper<SomeData> getDataWrapper() { + return dataWrapper; + } + + public GraphEdgeLabels getGraphEdge() { + return graphEdge; + } + + public Supplier<Class<SomeData>> getSomeDataClassGen() { + return someDataClassGen; + } + + public Supplier<Class<SomeValueData>> getSomeValueDataClassGen() { + return someValueDataClassGen; + } + + public NodeTypeEnum getNodeType() { + return nodeType; + } + + public NodeTypeEnum getNodeTypeValue() { + return nodeTypeValue; + } + } + + /** + * update value of attribute on resource instance + * + * @param resourceInstanceAttribute + * @param resourceInstanceId + * @return + */ + private Either<AttributeValueData, TitanOperationStatus> updateAttributeOfResourceInstance(ComponentInstanceProperty resourceInstanceAttribute, String resourceInstanceId) { + + Either<AttributeValueData, TitanOperationStatus> result = null; + Wrapper<TitanOperationStatus> errorWrapper = new Wrapper<>(); + UpdateDataContainer<AttributeData, AttributeValueData> updateDataContainer = new UpdateDataContainer<>(GraphEdgeLabels.ATTRIBUTE_IMPL, (() -> AttributeData.class), (() -> AttributeValueData.class), NodeTypeEnum.Attribute, + NodeTypeEnum.AttributeValue); + preUpdateElementOfResourceInstanceValidations(updateDataContainer, resourceInstanceAttribute, resourceInstanceId, errorWrapper); + if (errorWrapper.isEmpty()) { + AttributeValueData attributeValueData = updateDataContainer.getValueDataWrapper().getInnerElement(); + attributeValueData.setHidden(resourceInstanceAttribute.isHidden()); + attributeValueData.setValue(resourceInstanceAttribute.getValue()); + Either<AttributeValueData, TitanOperationStatus> updateRes = titanGenericDao.updateNode(attributeValueData, AttributeValueData.class); + if (updateRes.isRight()) { + TitanOperationStatus status = updateRes.right().value(); + errorWrapper.setInnerElement(status); + } else { + result = Either.left(updateRes.left().value()); + } + } + if (!errorWrapper.isEmpty()) { + result = Either.right(errorWrapper.getInnerElement()); + } + return result; + + } + + private Either<AttributeValueData, TitanOperationStatus> addAttributeToResourceInstance(ComponentInstanceProperty attributeInstanceProperty, String resourceInstanceId, Integer index) { + Wrapper<TitanOperationStatus> errorWrapper = new Wrapper<>(); + Wrapper<ComponentInstanceData> compInsWrapper = new Wrapper<>(); + Wrapper<AttributeData> attDataWrapper = new Wrapper<>(); + Wrapper<AttributeValueData> attValueDataWrapper = new Wrapper<>(); + + // Verify RI Exist + validateRIExist(resourceInstanceId, compInsWrapper, errorWrapper); + + if (errorWrapper.isEmpty()) { + // Verify Attribute Exist + validateElementExistInGraph(attributeInstanceProperty.getUniqueId(), NodeTypeEnum.Attribute, () -> AttributeData.class, attDataWrapper, errorWrapper); + } + if (errorWrapper.isEmpty()) { + // Create AttributeValueData that is connected to RI + createAttributeValueDataNode(attributeInstanceProperty, index, errorWrapper, compInsWrapper.getInnerElement(), attValueDataWrapper); + } + if (errorWrapper.isEmpty()) { + // Connect AttributeValueData (Att on RI) to AttData (Att on + // Resource) + connectAttValueDataToAttData(errorWrapper, attDataWrapper.getInnerElement(), attValueDataWrapper.getInnerElement()); + } + if (errorWrapper.isEmpty()) { + // Connect AttributeValueData to RI + connectAttValueDataToComponentInstanceData(errorWrapper, compInsWrapper.getInnerElement(), attValueDataWrapper.getInnerElement()); + } + + if (errorWrapper.isEmpty()) { + return Either.left(attValueDataWrapper.getInnerElement()); + } else { + return Either.right(errorWrapper.getInnerElement()); + } + + } + + private <SomeData extends GraphNode, SomeValueData extends GraphNode> void preUpdateElementOfResourceInstanceValidations(UpdateDataContainer<SomeData, SomeValueData> updateDataContainer, IComponentInstanceConnectedElement resourceInstanceProerty, + String resourceInstanceId, Wrapper<TitanOperationStatus> errorWrapper) { + + if (errorWrapper.isEmpty()) { + // Verify VFC instance Exist + validateRIExist(resourceInstanceId, errorWrapper); + } + + if (errorWrapper.isEmpty()) { + // Example: Verify Property connected to VFC exist + validateElementConnectedToComponentExist(updateDataContainer, resourceInstanceProerty, errorWrapper); + } + + if (errorWrapper.isEmpty()) { + // Example: Verify PropertyValue connected to VFC Instance exist + validateElementConnectedToComponentInstanceExist(updateDataContainer, resourceInstanceProerty, errorWrapper); + } + + if (errorWrapper.isEmpty()) { + // Example: Verify PropertyValue connected Property + validateElementConnectedToInstance(updateDataContainer, resourceInstanceProerty, errorWrapper); + } + } + + private <SomeData extends GraphNode, SomeValueData extends GraphNode> void validateElementConnectedToInstance(UpdateDataContainer<SomeData, SomeValueData> updateDataContainer, IComponentInstanceConnectedElement resourceInstanceProerty, + Wrapper<TitanOperationStatus> errorWrapper) { + Either<ImmutablePair<SomeData, GraphEdge>, TitanOperationStatus> child = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(updateDataContainer.getNodeTypeValue()), resourceInstanceProerty.getValueUniqueUid(), + updateDataContainer.getGraphEdge(), updateDataContainer.getNodeType(), updateDataContainer.getSomeDataClassGen().get()); + + if (child.isRight()) { + TitanOperationStatus status = child.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + errorWrapper.setInnerElement(status); + + } else { + updateDataContainer.getDataWrapper().setInnerElement(child.left().value().left); + } + } + + private <SomeValueData extends GraphNode, SomeData extends GraphNode> void validateElementConnectedToComponentInstanceExist(UpdateDataContainer<SomeData, SomeValueData> updateDataContainer, + IComponentInstanceConnectedElement resourceInstanceProerty, Wrapper<TitanOperationStatus> errorWrapper) { + String valueUniqueUid = resourceInstanceProerty.getValueUniqueUid(); + if (valueUniqueUid == null) { + errorWrapper.setInnerElement(TitanOperationStatus.INVALID_ID); + } else { + Either<SomeValueData, TitanOperationStatus> findPropertyValueRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(updateDataContainer.getNodeTypeValue()), valueUniqueUid, updateDataContainer.getSomeValueDataClassGen().get()); + if (findPropertyValueRes.isRight()) { + TitanOperationStatus status = findPropertyValueRes.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + errorWrapper.setInnerElement(status); + } else { + updateDataContainer.getValueDataWrapper().setInnerElement(findPropertyValueRes.left().value()); + } + } + } + + private <SomeData extends GraphNode, SomeValueData extends GraphNode> void validateElementConnectedToComponentExist(UpdateDataContainer<SomeData, SomeValueData> updateDataContainer, + IComponentInstanceConnectedElement resourceInstanceElementConnected, Wrapper<TitanOperationStatus> errorWrapper) { + String uniqueId = resourceInstanceElementConnected.getUniqueId(); + Either<SomeData, TitanOperationStatus> findPropertyDefRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(updateDataContainer.getNodeType()), uniqueId, updateDataContainer.getSomeDataClassGen().get()); + + if (findPropertyDefRes.isRight()) { + TitanOperationStatus status = findPropertyDefRes.right().value(); + errorWrapper.setInnerElement(status); + } + } + + private void validateRIExist(String resourceInstanceId, Wrapper<TitanOperationStatus> errorWrapper) { + validateRIExist(resourceInstanceId, null, errorWrapper); + } + + private void validateRIExist(String resourceInstanceId, Wrapper<ComponentInstanceData> compInsDataWrapper, Wrapper<TitanOperationStatus> errorWrapper) { + validateElementExistInGraph(resourceInstanceId, NodeTypeEnum.ResourceInstance, () -> ComponentInstanceData.class, compInsDataWrapper, errorWrapper); + } + + public <ElementData extends GraphNode> void validateElementExistInGraph(String elementUniqueId, NodeTypeEnum elementNodeType, Supplier<Class<ElementData>> elementClassGen, Wrapper<ElementData> elementDataWrapper, + Wrapper<TitanOperationStatus> errorWrapper) { + Either<ElementData, TitanOperationStatus> findResInstanceRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(elementNodeType), elementUniqueId, elementClassGen.get()); + if (findResInstanceRes.isRight()) { + TitanOperationStatus status = findResInstanceRes.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + errorWrapper.setInnerElement(status); + } else { + if (elementDataWrapper != null) { + elementDataWrapper.setInnerElement(findResInstanceRes.left().value()); + } + } + } + + /** + * add property to resource instance + * + * @param resourceInstanceId + * @param index + * @return + */ + private Either<InputValueData, TitanOperationStatus> addInputToResourceInstance(ComponentInstanceInput resourceInstanceInput, String resourceInstanceId, Integer index) { + + Either<ComponentInstanceData, TitanOperationStatus> findResInstanceRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId, ComponentInstanceData.class); + + if (findResInstanceRes.isRight()) { + TitanOperationStatus status = findResInstanceRes.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + return Either.right(status); + } + + String propertyId = resourceInstanceInput.getUniqueId(); + Either<InputsData, TitanOperationStatus> findPropertyDefRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Input), propertyId, InputsData.class); + + if (findPropertyDefRes.isRight()) { + TitanOperationStatus status = findPropertyDefRes.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + return Either.right(status); + } + + String valueUniqueUid = resourceInstanceInput.getValueUniqueUid(); + if (valueUniqueUid == null) { + + InputsData propertyData = findPropertyDefRes.left().value(); + + ComponentInstanceData resourceInstanceData = findResInstanceRes.left().value(); + + ImmutablePair<TitanOperationStatus, String> isInputValueExists = inputOperation.findInputValue(resourceInstanceId, propertyId); + if (isInputValueExists.getLeft() == TitanOperationStatus.ALREADY_EXIST) { + log.debug("The property {} already added to the resource instance {}", propertyId, resourceInstanceId); + resourceInstanceInput.setValueUniqueUid(isInputValueExists.getRight()); + } + + if (isInputValueExists.getLeft() != TitanOperationStatus.NOT_FOUND) { + log.debug("After finding input value of {} on componenet instance {}", propertyId, resourceInstanceId); + return Either.right(isInputValueExists.getLeft()); + } + + String innerType = null; + + PropertyDataDefinition propDataDef = propertyData.getPropertyDataDefinition(); + String propertyType = propDataDef.getType(); + String value = resourceInstanceInput.getValue(); + ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); + + if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { + SchemaDefinition def = propDataDef.getSchema(); + if (def == null) { + log.debug("Schema doesn't exists for property of type {}", type); + return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + } + PropertyDataDefinition propDef = def.getProperty(); + if (propDef == null) { + log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); + return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + } + innerType = propDef.getType(); + } + + log.debug("Before validateAndUpdatePropertyValue"); + Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); + if (allDataTypes.isRight()) { + TitanOperationStatus status = allDataTypes.right().value(); + BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); + return Either.right(status); + } + + String uniqueId = UniqueIdBuilder.buildResourceInstanceInputValueUid(resourceInstanceData.getUniqueId(), index); + InputValueData propertyValueData = new InputValueData(); + propertyValueData.setUniqueId(uniqueId); + propertyValueData.setValue(value); + + log.debug("Before validateAndUpdateRules"); + ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, resourceInstanceInput.getRules(), innerType, allDataTypes.left().value(), true); + log.debug("After validateAndUpdateRules. pair = {} ", pair); + if (pair.getRight() != null && !pair.getRight()) { + BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), resourceInstanceInput.getName(), propertyType); + return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + } + log.debug("Before adding property value to graph {}", propertyValueData); + Either<InputValueData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(propertyValueData, InputValueData.class); + log.debug("After adding property value to graph {}", propertyValueData); + + if (createNodeResult.isRight()) { + TitanOperationStatus operationStatus = createNodeResult.right().value(); + return Either.right(operationStatus); + } + + Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(propertyValueData, propertyData, GraphEdgeLabels.INPUT_IMPL, null); + + if (createRelResult.isRight()) { + TitanOperationStatus operationStatus = createRelResult.right().value(); + log.error("Failed to associate property value {} to property {} in graph. status is {}", uniqueId, propertyId, operationStatus); + return Either.right(operationStatus); + } + + Map<String, Object> properties1 = new HashMap<>(); + + properties1.put(GraphEdgePropertiesDictionary.NAME.getProperty(), resourceInstanceData.getComponentInstDataDefinition().getName()); + properties1.put(GraphEdgePropertiesDictionary.OWNER_ID.getProperty(), resourceInstanceData.getComponentInstDataDefinition().getUniqueId()); + + createRelResult = titanGenericDao.createRelation(resourceInstanceData, propertyValueData, GraphEdgeLabels.INPUT_VALUE, properties1); + + if (createRelResult.isRight()) { + TitanOperationStatus operationStatus = createNodeResult.right().value(); + log.error("Failed to associate resource instance {} property value {} in graph. status is {}", resourceInstanceId, uniqueId, operationStatus); + return Either.right(operationStatus); + + } + + return Either.left(createNodeResult.left().value()); + } else { + log.error("property value already exists."); + return Either.right(TitanOperationStatus.ALREADY_EXIST); + } + + } + + @Override + public Either<ComponentInstanceProperty, StorageOperationStatus> addAttributeValueToResourceInstance(ComponentInstanceProperty resourceInstanceAttribute, String resourceInstanceId, Integer index, boolean inTransaction) { + Either<ComponentInstanceProperty, StorageOperationStatus> result = null; + + try { + + Either<AttributeValueData, TitanOperationStatus> eitherStatus = this.addAttributeToResourceInstance(resourceInstanceAttribute, resourceInstanceId, index); + + if (eitherStatus.isRight()) { + log.error("Failed to add attribute value {} to resource instance {} in Graph. status is {}", resourceInstanceAttribute, resourceInstanceId, eitherStatus.right().value().name()); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherStatus.right().value())); + return result; + } else { + AttributeValueData attributeValueData = eitherStatus.left().value(); + + ComponentInstanceProperty attributeValueResult = buildResourceInstanceAttribute(attributeValueData, resourceInstanceAttribute); + log.debug("The returned ResourceInstanceAttribute is {}", attributeValueResult); + + result = Either.left(attributeValueResult); + return result; + } + } + + finally { + handleTransactionCommitRollback(inTransaction, result); + } + } + + private ComponentInstanceProperty buildResourceInstanceAttribute(AttributeValueData attributeValueData, ComponentInstanceProperty resourceInstanceAttribute) { + Boolean hidden = attributeValueData.isHidden(); + String uid = attributeValueData.getUniqueId(); + return new ComponentInstanceProperty(hidden, resourceInstanceAttribute, uid); + } + + @Override + public Either<ComponentInstanceProperty, StorageOperationStatus> updateAttributeValueInResourceInstance(ComponentInstanceProperty resourceInstanceAttribute, String resourceInstanceId, boolean inTransaction) { + + Either<ComponentInstanceProperty, StorageOperationStatus> result = null; + + try { + Either<AttributeValueData, TitanOperationStatus> eitherAttributeValue = updateAttributeOfResourceInstance(resourceInstanceAttribute, resourceInstanceId); + + if (eitherAttributeValue.isRight()) { + log.error("Failed to add attribute value {} to resource instance {} in Graph. status is {}", resourceInstanceAttribute, resourceInstanceId, eitherAttributeValue.right().value().name()); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherAttributeValue.right().value())); + return result; + } else { + AttributeValueData attributeValueData = eitherAttributeValue.left().value(); + + ComponentInstanceProperty attributeValueResult = buildResourceInstanceAttribute(attributeValueData, resourceInstanceAttribute); + log.debug("The returned ResourceInstanceAttribute is {}", attributeValueResult); + + result = Either.left(attributeValueResult); + return result; + } + } + + finally { + handleTransactionCommitRollback(inTransaction, result); + } + + } + + @Override + public Either<ComponentInstanceInput, StorageOperationStatus> addInputValueToResourceInstance(ComponentInstanceInput resourceInstanceInput, String resourceInstanceId, Integer index, boolean inTransaction) { + + /// #RULES SUPPORT + /// Ignore rules received from client till support + resourceInstanceInput.setRules(null); + /// + /// + + Either<ComponentInstanceInput, StorageOperationStatus> result = null; + + try { + + Either<InputValueData, TitanOperationStatus> eitherStatus = addInputToResourceInstance(resourceInstanceInput, resourceInstanceId, index); + + if (eitherStatus.isRight()) { + log.error("Failed to add input value {} to resource instance {} in Graph. status is {}", resourceInstanceInput, resourceInstanceId, eitherStatus.right().value().name()); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherStatus.right().value())); + return result; + } else { + InputValueData propertyValueData = eitherStatus.left().value(); + + ComponentInstanceInput propertyValueResult = inputOperation.buildResourceInstanceInput(propertyValueData, resourceInstanceInput); + log.debug("The returned ResourceInstanceProperty is {}", propertyValueResult); + + Either<String, TitanOperationStatus> findDefaultValue = propertyOperation.findDefaultValueFromSecondPosition(resourceInstanceInput.getPath(), resourceInstanceInput.getUniqueId(), resourceInstanceInput.getDefaultValue()); + if (findDefaultValue.isRight()) { + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(findDefaultValue.right().value())); + return result; + } + String defaultValue = findDefaultValue.left().value(); + propertyValueResult.setDefaultValue(defaultValue); + log.debug("The returned default value in ResourceInstanceProperty is {}", defaultValue); + + result = Either.left(propertyValueResult); + return result; + } + } + + finally { + if (!inTransaction) { + if (result == null || result.isRight()) { + log.error("Going to execute rollback on graph."); + titanGenericDao.rollback(); + } else { + log.debug("Going to execute commit on graph."); + titanGenericDao.commit(); + } + } + } + + } + + @Override + public Either<ComponentInstanceInput, StorageOperationStatus> updateInputValueInResourceInstance(ComponentInstanceInput input, String resourceInstanceId, boolean b) { + return null; + } + + @Override + public StorageOperationStatus updateCustomizationUUID(String componentInstanceId) { + Either<TitanVertex, TitanOperationStatus> vertexByProperty = titanGenericDao.getVertexByProperty(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), componentInstanceId); + if (vertexByProperty.isRight()) { + log.debug("Failed to fetch component instance by id {} error {}", componentInstanceId, vertexByProperty.right().value()); + return DaoStatusConverter.convertTitanStatusToStorageStatus(vertexByProperty.right().value()); + } + UUID uuid = UUID.randomUUID(); + TitanVertex ciVertex = vertexByProperty.left().value(); + ciVertex.property(GraphPropertiesDictionary.CUSTOMIZATION_UUID.getProperty(), uuid.toString()); + + return StorageOperationStatus.OK; + } + + @Override + public Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) { + + log.debug("Going to update modification time of component instance {}. ", componentInstance.getName()); + Either<ComponentInstanceData, StorageOperationStatus> result = null; + try{ + ComponentInstanceData componentData = new ComponentInstanceData(componentInstance, componentInstance.getGroupInstances().size()); + componentData.getComponentInstDataDefinition().setModificationTime(modificationTime); + componentData.getComponentInstDataDefinition().setCustomizationUUID(UUID.randomUUID().toString()); + Either<ComponentInstanceData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(componentData, ComponentInstanceData.class); + if (updateNode.isRight()) { + log.error("Failed to update resource {}. status is {}", componentInstance.getUniqueId(), updateNode.right().value()); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value())); + }else{ + result = Either.left(updateNode.left().value()); + } + }catch(Exception e){ + log.error("Exception occured during update modification date of compomemt instance{}. The message is {}. ", componentInstance.getName(), e.getMessage(), e); + result = Either.right(StorageOperationStatus.GENERAL_ERROR); + }finally { + if(!inTransaction){ + if (result == null || result.isRight()) { + log.error("Going to execute rollback on graph."); + titanGenericDao.rollback(); + } else { + log.debug("Going to execute commit on graph."); + titanGenericDao.commit(); + } + } + } + return result; + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ConsumerOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ConsumerOperation.java index 198ad99ecb..c173b59020 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 @@ -20,9 +20,7 @@ package org.openecomp.sdc.be.model.operations.impl; -import java.util.Collections; -import java.util.List; - +import fj.data.Either; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.dao.titan.TitanGenericDao; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; @@ -30,134 +28,134 @@ 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; import org.openecomp.sdc.be.resources.data.ConsumerData; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; -import fj.data.Either; +import java.util.Collections; +import java.util.List; @Component("consumer-operation") public class ConsumerOperation implements IConsumerOperation { - private TitanGenericDao titanGenericDao; - - private static Logger log = LoggerFactory.getLogger(ConsumerOperation.class.getName()); - - public ConsumerOperation(@Qualifier("titan-generic-dao") TitanGenericDao titanGenericDao) { - this.titanGenericDao = titanGenericDao; - } - - @Override - public Either<ConsumerData, StorageOperationStatus> getCredentials(String consumerName) { - Either<ConsumerData, StorageOperationStatus> result = null; - log.debug("retriving Credentials for: {}", consumerName); - Either<ConsumerData, TitanOperationStatus> getNode = titanGenericDao.getNode(GraphPropertiesDictionary.CONSUMER_NAME.getProperty(), consumerName, ConsumerData.class); - if (getNode.isRight()) { - TitanOperationStatus status = getNode.right().value(); - log.error("Error returned after get Consumer Data node {}. status returned is {}", consumerName, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - ConsumerData consumerData = getNode.left().value(); - return Either.left(consumerData); - } - - @Override - public Either<List<ConsumerData>, StorageOperationStatus> getAll() { - log.debug("retrieving all consumers"); - return titanGenericDao.getByCriteria(NodeTypeEnum.ConsumerCredentials, Collections.emptyMap(), ConsumerData.class) - .right().map(DaoStatusConverter::convertTitanStatusToStorageStatus); - } - - @Override - public Either<ConsumerData, StorageOperationStatus> createCredentials(ConsumerData consumerData) { - return createCredentials(consumerData, false); - } - - @Override - public Either<ConsumerData, StorageOperationStatus> createCredentials(ConsumerData consumerData, boolean inTransaction) { - Either<ConsumerData, StorageOperationStatus> result = null; - try { - log.debug("creating Credentials for: {}", consumerData.getUniqueId()); - Either<ConsumerData, TitanOperationStatus> createNode = titanGenericDao.createNode(consumerData, ConsumerData.class); - if (createNode.isRight()) { - TitanOperationStatus status = createNode.right().value(); - log.error("Error returned after creating Consumer Data node {}. status returned is {}", consumerData.getUniqueId(), status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - ConsumerData createdConsumerData = createNode.left().value(); - result = Either.left(createdConsumerData); - return result; - } finally { - handleTransaction(inTransaction, result); - } - } - - @Override - public Either<ConsumerData, StorageOperationStatus> deleteCredentials(String consumerName) { - return deleteCredentials(consumerName, false); - } - - @Override - public Either<ConsumerData, StorageOperationStatus> deleteCredentials(String consumerName, boolean inTransaction) { - Either<ConsumerData, StorageOperationStatus> result = null; - try { - log.debug("delete Credentials for: {}", consumerName); - Either<ConsumerData, TitanOperationStatus> deleteNode = titanGenericDao.deleteNode(GraphPropertiesDictionary.CONSUMER_NAME.getProperty(), consumerName, ConsumerData.class); - if (deleteNode.isRight()) { - TitanOperationStatus status = deleteNode.right().value(); - log.error("Error returned after delete Consumer Data node {}. status returned is {}", consumerName, status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - - ConsumerData deletedConsumerData = deleteNode.left().value(); - result = Either.left(deletedConsumerData); - return result; - } finally { - handleTransaction(inTransaction, result); - } - - } - - @Override - public Either<ConsumerData, StorageOperationStatus> updateCredentials(ConsumerData consumerData) { - return updateCredentials(consumerData, false); - } - - @Override - public Either<ConsumerData, StorageOperationStatus> updateCredentials(ConsumerData consumerData, boolean inTransaction) { - - Either<ConsumerData, StorageOperationStatus> result = null; - try { - log.debug("update Credentials for: {}", consumerData.getUniqueId()); - Either<ConsumerData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(consumerData, ConsumerData.class); - if (updateNode.isRight()) { - TitanOperationStatus status = updateNode.right().value(); - log.error("Error returned after delete Consumer Data node {}. status returned is {}", consumerData.getUniqueId(), status); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - ConsumerData updatedConsumerData = updateNode.left().value(); - result = Either.left(updatedConsumerData); - return result; - } finally { - handleTransaction(inTransaction, result); - } - } - - private void handleTransaction(boolean inTransaction, Either<ConsumerData, StorageOperationStatus> result) { - if (false == inTransaction) { - if (result == null || result.isRight()) { - log.error("Going to execute rollback on graph."); - titanGenericDao.rollback(); - } else { - log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } + private TitanGenericDao titanGenericDao; + + private static final Logger log = Logger.getLogger(ConsumerOperation.class.getName()); + + public ConsumerOperation(@Qualifier("titan-generic-dao") TitanGenericDao titanGenericDao) { + this.titanGenericDao = titanGenericDao; + } + + @Override + public Either<ConsumerData, StorageOperationStatus> getCredentials(String consumerName) { + Either<ConsumerData, StorageOperationStatus> result = null; + log.debug("retriving Credentials for: {}", consumerName); + Either<ConsumerData, TitanOperationStatus> getNode = titanGenericDao.getNode(GraphPropertiesDictionary.CONSUMER_NAME.getProperty(), consumerName, ConsumerData.class); + if (getNode.isRight()) { + TitanOperationStatus status = getNode.right().value(); + log.error("Error returned after get Consumer Data node {}. status returned is {}", consumerName, status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + return result; + } + ConsumerData consumerData = getNode.left().value(); + return Either.left(consumerData); + } + + @Override + public Either<List<ConsumerData>, StorageOperationStatus> getAll() { + log.debug("retrieving all consumers"); + return titanGenericDao.getByCriteria(NodeTypeEnum.ConsumerCredentials, Collections.emptyMap(), ConsumerData.class) + .right().map(DaoStatusConverter::convertTitanStatusToStorageStatus); + } + + @Override + public Either<ConsumerData, StorageOperationStatus> createCredentials(ConsumerData consumerData) { + return createCredentials(consumerData, false); + } + + @Override + public Either<ConsumerData, StorageOperationStatus> createCredentials(ConsumerData consumerData, boolean inTransaction) { + Either<ConsumerData, StorageOperationStatus> result = null; + try { + log.debug("creating Credentials for: {}", consumerData.getUniqueId()); + Either<ConsumerData, TitanOperationStatus> createNode = titanGenericDao.createNode(consumerData, ConsumerData.class); + if (createNode.isRight()) { + TitanOperationStatus status = createNode.right().value(); + log.error("Error returned after creating Consumer Data node {}. status returned is {}", consumerData.getUniqueId(), status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + return result; + } + ConsumerData createdConsumerData = createNode.left().value(); + result = Either.left(createdConsumerData); + return result; + } finally { + handleTransaction(inTransaction, result); + } + } + + @Override + public Either<ConsumerData, StorageOperationStatus> deleteCredentials(String consumerName) { + return deleteCredentials(consumerName, false); + } + + @Override + public Either<ConsumerData, StorageOperationStatus> deleteCredentials(String consumerName, boolean inTransaction) { + Either<ConsumerData, StorageOperationStatus> result = null; + try { + log.debug("delete Credentials for: {}", consumerName); + Either<ConsumerData, TitanOperationStatus> deleteNode = titanGenericDao.deleteNode(GraphPropertiesDictionary.CONSUMER_NAME.getProperty(), consumerName, ConsumerData.class); + if (deleteNode.isRight()) { + TitanOperationStatus status = deleteNode.right().value(); + log.error("Error returned after delete Consumer Data node {}. status returned is {}", consumerName, status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + return result; + } + + ConsumerData deletedConsumerData = deleteNode.left().value(); + result = Either.left(deletedConsumerData); + return result; + } finally { + handleTransaction(inTransaction, result); + } + + } + + @Override + public Either<ConsumerData, StorageOperationStatus> updateCredentials(ConsumerData consumerData) { + return updateCredentials(consumerData, false); + } + + @Override + public Either<ConsumerData, StorageOperationStatus> updateCredentials(ConsumerData consumerData, boolean inTransaction) { + + Either<ConsumerData, StorageOperationStatus> result = null; + try { + log.debug("update Credentials for: {}", consumerData.getUniqueId()); + Either<ConsumerData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(consumerData, ConsumerData.class); + if (updateNode.isRight()) { + TitanOperationStatus status = updateNode.right().value(); + log.error("Error returned after delete Consumer Data node {}. status returned is {}", consumerData.getUniqueId(), status); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + return result; + } + ConsumerData updatedConsumerData = updateNode.left().value(); + result = Either.left(updatedConsumerData); + return result; + } finally { + handleTransaction(inTransaction, result); + } + } + + private void handleTransaction(boolean inTransaction, Either<ConsumerData, StorageOperationStatus> result) { + if (!inTransaction) { + if (result == null || result.isRight()) { + log.error("Going to execute rollback on graph."); + titanGenericDao.rollback(); + } else { + log.debug("Going to execute commit on graph."); + titanGenericDao.commit(); + } + } + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CsarOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CsarOperation.java index 88edb1fd9e..9ae2f252c9 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CsarOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/CsarOperation.java @@ -20,134 +20,130 @@ package org.openecomp.sdc.be.model.operations.impl; -import java.io.File; -import java.io.FileFilter; -import java.io.IOException; -import java.nio.file.Files; -import java.util.Map; - -import javax.annotation.PostConstruct; - -import org.apache.commons.io.filefilter.WildcardFileFilter; -import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.common.util.ZipUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonParser; - import fj.data.Either; +import org.apache.commons.io.filefilter.WildcardFileFilter; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.openecomp.sdc.common.util.ZipUtil; + +import javax.annotation.PostConstruct; +import java.io.File; +import java.io.FileFilter; +import java.io.IOException; +import java.nio.file.Files; +import java.util.Map; @org.springframework.stereotype.Component("csar-operation") public class CsarOperation { - private static Logger log = LoggerFactory.getLogger(CsarOperation.class.getName()); - - @javax.annotation.Resource - private OnboardingClient onboardingClient; - - public static void main(String[] args) { - - CsarOperation csarOperation = new CsarOperation(); - csarOperation.init(); - - String csarUuid = "70025CF6081B489CA7B1CBA583D5278D"; - Either<Map<String, byte[]>, StorageOperationStatus> csar = csarOperation.getCsar(csarUuid, null); - System.out.println(csar.left().value()); - - } - - @PostConstruct - public void init() { - - } - - public Either<Map<String, byte[]>, StorageOperationStatus> getMockCsar(String csarUuid) { - File dir = new File("/var/tmp/mockCsar"); - FileFilter fileFilter = new WildcardFileFilter("*.csar"); - File[] files = dir.listFiles(fileFilter); - for (int i = 0; i < files.length; i++) { - File csar = files[i]; - if (csar.getName().startsWith(csarUuid)) { - log.debug("Found CSAR file {} matching the passed csarUuid {}", csar.getAbsolutePath(), csarUuid); - byte[] data; - try { - data = Files.readAllBytes(csar.toPath()); - } catch (IOException e) { - log.debug("Error reading mock file for CSAR, error: {}", e); - return Either.right(StorageOperationStatus.NOT_FOUND); - } - Map<String, byte[]> readZip = ZipUtil.readZip(data); - return Either.left(readZip); - } - } - log.debug("Couldn't find mock file for CSAR starting with {}", csarUuid); - return Either.right(StorageOperationStatus.CSAR_NOT_FOUND); - } - - /** - * get csar from remote repository - * - * @param csarUuid - * @return - */ - public Either<Map<String, byte[]>, StorageOperationStatus> getCsar(String csarUuid, User user) { - - Either<Map<String, byte[]>, StorageOperationStatus> result = onboardingClient.getCsar(csarUuid, user.getUserId()); - - if (result.isRight()) { - log.debug("Cannot find csar {}. Staus returned is {}", csarUuid, result.right().value()); - } else { - Map<String, byte[]> values = result.left().value(); - if (values != null) { - log.debug("The returned files are {}", values.keySet()); - } - } - - return result; - } - - @SuppressWarnings("unchecked") - public Either<String, StorageOperationStatus> getCsarLatestVersion(String csarUuid, User user) { - - Either<String, StorageOperationStatus> result = onboardingClient.getPackages(user.getUserId()); - - if (result.isRight()) { - log.debug("Cannot find version for package with Id {}. Status returned is {}", csarUuid, result.right().value()); - } else { - String latestVersion = null; - JsonElement root = new JsonParser().parse(result.left().value()); - JsonArray csarsInfo = root.getAsJsonObject().get("results").getAsJsonArray(); - for (JsonElement csarInfo : csarsInfo) { - Map<String, String> csarInfoMap = new Gson().fromJson(csarInfo, Map.class); - if(csarInfoMap.get("packageId").equals(csarUuid)){ - String curVersion = csarInfoMap.get("version"); - if(latestVersion == null || isGreater(latestVersion, curVersion)){ - latestVersion = curVersion; - } - } - } - if (latestVersion != null) { - result = Either.left(latestVersion); - } else { - log.debug("The returned packages are {}. Failed to find latest version for package with Id {}. ", result.left().value(), csarUuid); - result = Either.right(StorageOperationStatus.NOT_FOUND); - } - } - - return result; - } - - private boolean isGreater(String latestVersion, String currentVersion) { - return Double.parseDouble(latestVersion) < Double.parseDouble(currentVersion); - } - - public OnboardingClient getOnboardingClient() { - return onboardingClient; - } + private static final Logger log = Logger.getLogger(CsarOperation.class.getName()); + + @javax.annotation.Resource + private OnboardingClient onboardingClient; + + public static void main(String[] args) { + + CsarOperation csarOperation = new CsarOperation(); + csarOperation.init(); + + String csarUuid = "70025CF6081B489CA7B1CBA583D5278D"; + Either<Map<String, byte[]>, StorageOperationStatus> csar = csarOperation.getCsar(csarUuid, null); + System.out.println(csar.left().value()); + + } + + @PostConstruct + public void init() { + + } + + public Either<Map<String, byte[]>, StorageOperationStatus> getMockCsar(String csarUuid) { + File dir = new File("/var/tmp/mockCsar"); + FileFilter fileFilter = new WildcardFileFilter("*.csar"); + File[] files = dir.listFiles(fileFilter); + for (int i = 0; i < files.length; i++) { + File csar = files[i]; + if (csar.getName().startsWith(csarUuid)) { + log.debug("Found CSAR file {} matching the passed csarUuid {}", csar.getAbsolutePath(), csarUuid); + byte[] data; + try { + data = Files.readAllBytes(csar.toPath()); + } catch (IOException e) { + log.debug("Error reading mock file for CSAR, error: {}", e); + return Either.right(StorageOperationStatus.NOT_FOUND); + } + Map<String, byte[]> readZip = ZipUtil.readZip(data); + return Either.left(readZip); + } + } + log.debug("Couldn't find mock file for CSAR starting with {}", csarUuid); + return Either.right(StorageOperationStatus.CSAR_NOT_FOUND); + } + + /** + * get csar from remote repository + * + * @param csarUuid + * @return + */ + public Either<Map<String, byte[]>, StorageOperationStatus> getCsar(String csarUuid, User user) { + + Either<Map<String, byte[]>, StorageOperationStatus> result = onboardingClient.getCsar(csarUuid, user.getUserId()); + + if (result.isRight()) { + log.debug("Cannot find csar {}. Staus returned is {}", csarUuid, result.right().value()); + } else { + Map<String, byte[]> values = result.left().value(); + if (values != null) { + log.debug("The returned files are {}", values.keySet()); + } + } + + return result; + } + + @SuppressWarnings("unchecked") + public Either<String, StorageOperationStatus> getCsarLatestVersion(String csarUuid, User user) { + + Either<String, StorageOperationStatus> result = onboardingClient.getPackages(user.getUserId()); + + if (result.isRight()) { + log.debug("Cannot find version for package with Id {}. Status returned is {}", csarUuid, result.right().value()); + } else { + String latestVersion = null; + JsonElement root = new JsonParser().parse(result.left().value()); + JsonArray csarsInfo = root.getAsJsonObject().get("results").getAsJsonArray(); + for (JsonElement csarInfo : csarsInfo) { + Map<String, String> csarInfoMap = new Gson().fromJson(csarInfo, Map.class); + if(csarInfoMap.get("packageId").equals(csarUuid)){ + String curVersion = csarInfoMap.get("version"); + if(latestVersion == null || isGreater(latestVersion, curVersion)){ + latestVersion = curVersion; + } + } + } + if (latestVersion != null) { + result = Either.left(latestVersion); + } else { + log.debug("The returned packages are {}. Failed to find latest version for package with Id {}. ", result.left().value(), csarUuid); + result = Either.right(StorageOperationStatus.NOT_FOUND); + } + } + + return result; + } + + private boolean isGreater(String latestVersion, String currentVersion) { + return Double.parseDouble(latestVersion) < Double.parseDouble(currentVersion); + } + + public OnboardingClient getOnboardingClient() { + return onboardingClient; + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/DaoStatusConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/DaoStatusConverter.java index 3bda11641b..a66dce139b 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/DaoStatusConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/DaoStatusConverter.java @@ -20,98 +20,78 @@ package org.openecomp.sdc.be.model.operations.impl; -import org.openecomp.sdc.be.dao.api.ResourceUploadStatus; import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; public class DaoStatusConverter { - public static StorageOperationStatus convertTitanStatusToStorageStatus(TitanOperationStatus titanStatus) { - - if (titanStatus == null) { - return StorageOperationStatus.GENERAL_ERROR; - } - - switch (titanStatus) { - - case OK: - return StorageOperationStatus.OK; - - case NOT_CONNECTED: - return StorageOperationStatus.CONNECTION_FAILURE; - - case NOT_FOUND: - return StorageOperationStatus.NOT_FOUND; - - case NOT_CREATED: - return StorageOperationStatus.SCHEMA_ERROR; - - case INDEX_CANNOT_BE_CHANGED: - return StorageOperationStatus.SCHEMA_ERROR; - - case MISSING_UNIQUE_ID: - return StorageOperationStatus.BAD_REQUEST; - case ALREADY_LOCKED: - return StorageOperationStatus.FAILED_TO_LOCK_ELEMENT; - - case TITAN_SCHEMA_VIOLATION: - return StorageOperationStatus.SCHEMA_VIOLATION; - - case INVALID_ID: - return StorageOperationStatus.INVALID_ID; - case MATCH_NOT_FOUND: - return StorageOperationStatus.MATCH_NOT_FOUND; - - case ILLEGAL_ARGUMENT: - return StorageOperationStatus.BAD_REQUEST; - case ALREADY_EXIST: - return StorageOperationStatus.ENTITY_ALREADY_EXISTS; - case PROPERTY_NAME_ALREADY_EXISTS: - return StorageOperationStatus.PROPERTY_NAME_ALREADY_EXISTS; - case INVALID_PROPERTY: - return StorageOperationStatus.INVALID_PROPERTY; - default: - return StorageOperationStatus.GENERAL_ERROR; - } - - } - - public static StorageOperationStatus convertRsrcUploadStatusToStorageStatus(ResourceUploadStatus resourceUploadStatus) { - if (resourceUploadStatus == null) { - return StorageOperationStatus.GENERAL_ERROR; - } - switch (resourceUploadStatus) { - case OK: - return StorageOperationStatus.OK; - case ALREADY_EXIST: - return StorageOperationStatus.ENTITY_ALREADY_EXISTS; - case NOT_EXIST: - return StorageOperationStatus.ARTIFACT_NOT_FOUND; - case SERVICE_NOT_EXIST: - case COMPONENT_NOT_EXIST: - return StorageOperationStatus.NOT_FOUND; - default: - return StorageOperationStatus.GENERAL_ERROR; - } - } - - public static StorageOperationStatus convertCassandraStatusToStorageStatus(CassandraOperationStatus status) { - if (status == null) { - return StorageOperationStatus.GENERAL_ERROR; - } - switch (status) { - case OK: - return StorageOperationStatus.OK; - case CLUSTER_NOT_CONNECTED: - return StorageOperationStatus.CONNECTION_FAILURE; - case KEYSPACE_NOT_CONNECTED: - return StorageOperationStatus.STORAGE_NOT_AVAILABLE; - case NOT_FOUND: - return StorageOperationStatus.NOT_FOUND; - - default: - return StorageOperationStatus.GENERAL_ERROR; - } - } + public static StorageOperationStatus convertTitanStatusToStorageStatus(TitanOperationStatus titanStatus) { + + if (titanStatus == null) { + return StorageOperationStatus.GENERAL_ERROR; + } + + switch (titanStatus) { + + case OK: + return StorageOperationStatus.OK; + + case NOT_CONNECTED: + return StorageOperationStatus.CONNECTION_FAILURE; + + case NOT_FOUND: + return StorageOperationStatus.NOT_FOUND; + + case NOT_CREATED: + return StorageOperationStatus.SCHEMA_ERROR; + + case INDEX_CANNOT_BE_CHANGED: + return StorageOperationStatus.SCHEMA_ERROR; + + case MISSING_UNIQUE_ID: + return StorageOperationStatus.BAD_REQUEST; + case ALREADY_LOCKED: + return StorageOperationStatus.FAILED_TO_LOCK_ELEMENT; + + case TITAN_SCHEMA_VIOLATION: + return StorageOperationStatus.SCHEMA_VIOLATION; + + case INVALID_ID: + return StorageOperationStatus.INVALID_ID; + case MATCH_NOT_FOUND: + return StorageOperationStatus.MATCH_NOT_FOUND; + + case ILLEGAL_ARGUMENT: + return StorageOperationStatus.BAD_REQUEST; + case ALREADY_EXIST: + return StorageOperationStatus.ENTITY_ALREADY_EXISTS; + case PROPERTY_NAME_ALREADY_EXISTS: + return StorageOperationStatus.PROPERTY_NAME_ALREADY_EXISTS; + case INVALID_PROPERTY: + return StorageOperationStatus.INVALID_PROPERTY; + default: + return StorageOperationStatus.GENERAL_ERROR; + } + + } + + public static StorageOperationStatus convertCassandraStatusToStorageStatus(CassandraOperationStatus status) { + if (status == null) { + return StorageOperationStatus.GENERAL_ERROR; + } + switch (status) { + case OK: + return StorageOperationStatus.OK; + case CLUSTER_NOT_CONNECTED: + return StorageOperationStatus.CONNECTION_FAILURE; + case KEYSPACE_NOT_CONNECTED: + return StorageOperationStatus.STORAGE_NOT_AVAILABLE; + 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/DefaultDerivedFromOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/DefaultDerivedFromOperation.java index 2e5da8ddda..6f9555899b 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/DefaultDerivedFromOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/DefaultDerivedFromOperation.java @@ -1,25 +1,29 @@ package org.openecomp.sdc.be.model.operations.impl; +import fj.data.Either; +import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; +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.neo4j.GraphEdgeLabels; +import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.dao.titan.TitanGenericDao; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.operations.api.DerivedFromOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.resources.data.UniqueIdData; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.stereotype.Component; -import fj.data.Either; +import java.util.*; +import java.util.function.Function; @Component public class DefaultDerivedFromOperation implements DerivedFromOperation { - private static final Logger log = LoggerFactory.getLogger(DefaultDerivedFromOperation.class); + private static final Logger log = Logger.getLogger(DefaultDerivedFromOperation.class.getName()); private TitanGenericDao titanGenericDao; public DefaultDerivedFromOperation(TitanGenericDao titanGenericDao) { @@ -28,8 +32,8 @@ public class DefaultDerivedFromOperation implements DerivedFromOperation { @Override public Either<GraphRelation, StorageOperationStatus> addDerivedFromRelation(String parentUniqueId, String derivedFromUniqueId, NodeTypeEnum nodeType) { - UniqueIdData from = new UniqueIdData(NodeTypeEnum.PolicyType, parentUniqueId); - UniqueIdData to = new UniqueIdData(NodeTypeEnum.PolicyType, derivedFromUniqueId); + UniqueIdData from = new UniqueIdData(nodeType, parentUniqueId); + UniqueIdData to = new UniqueIdData(nodeType, derivedFromUniqueId); return titanGenericDao.createRelation(from, to, GraphEdgeLabels.DERIVED_FROM, null) .right() .map(DaoStatusConverter::convertTitanStatusToStorageStatus); @@ -45,8 +49,8 @@ public class DefaultDerivedFromOperation implements DerivedFromOperation { @Override public StorageOperationStatus removeDerivedFromRelation(String uniqueId, String derivedFromUniqueId, NodeTypeEnum nodeType) { - UniqueIdData from = new UniqueIdData(NodeTypeEnum.PolicyType, uniqueId); - UniqueIdData to = new UniqueIdData(NodeTypeEnum.PolicyType, derivedFromUniqueId); + UniqueIdData from = new UniqueIdData(nodeType, uniqueId); + UniqueIdData to = new UniqueIdData(nodeType, derivedFromUniqueId); return isDerivedFromExists(from, to) .either(isRelationExist -> isRelationExist ? deleteDerivedFrom(from, to) : StorageOperationStatus.OK, DaoStatusConverter::convertTitanStatusToStorageStatus); @@ -63,6 +67,90 @@ public class DefaultDerivedFromOperation implements DerivedFromOperation { private Either<Boolean, TitanOperationStatus> isDerivedFromExists(UniqueIdData from, UniqueIdData to) { return titanGenericDao.isRelationExist(from, to, GraphEdgeLabels.DERIVED_FROM); } - + + @Override + public <T extends GraphNode> Either<Boolean, StorageOperationStatus> isTypeDerivedFrom(String childCandidateType, String parentCandidateType, String currentChildType, + NodeTypeEnum nodeType, Class<T> clazz, Function<T, String> typeProvider) { + Map<String, Object> propertiesToMatch = new HashMap<>(); + propertiesToMatch.put(GraphPropertiesDictionary.TYPE.getProperty(), childCandidateType); + + Either<List<T>, TitanOperationStatus> getResponse = titanGenericDao.getByCriteria(nodeType, propertiesToMatch, clazz); + if (getResponse.isRight()) { + TitanOperationStatus titanOperationStatus = getResponse.right().value(); + log.debug("Couldn't fetch type {}, error: {}", childCandidateType, titanOperationStatus); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(titanOperationStatus)); + } + T node = getResponse.left().value().get(0); + String childUniqueId = node.getUniqueId(); + String childType = typeProvider.apply(node); + + Set<String> travelledTypes = new HashSet<>(); + if (currentChildType != null) { + travelledTypes.add(currentChildType); + } + + do { + travelledTypes.add(childType); + Either<List<ImmutablePair<T, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeType), childUniqueId, GraphEdgeLabels.DERIVED_FROM, + nodeType, clazz); + if (childrenNodes.isRight()) { + if (childrenNodes.right().value() != TitanOperationStatus.NOT_FOUND) { + TitanOperationStatus titanOperationStatus = getResponse.right().value(); + log.debug("Couldn't fetch derived from node for type {}, error: {}", childCandidateType, titanOperationStatus); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(titanOperationStatus)); + } else { + log.debug("Derived from node is not found for type {} - this is OK for root capability.", childCandidateType); + return Either.left(false); + } + } + String derivedFromUniqueId = childrenNodes.left().value().get(0).getLeft().getUniqueId(); + String derivedFromType = typeProvider.apply(childrenNodes.left().value().get(0).getLeft()); + if (derivedFromType.equals(parentCandidateType)) { + log.debug("Verified that type {} derives from type {}", childCandidateType, parentCandidateType); + return Either.left(true); + } + childUniqueId = derivedFromUniqueId; + childType = derivedFromType; + } while (!travelledTypes.contains(childType)); + // this stop condition should never be used, if we use it, we have an + // illegal cycle in graph - "derived from" hierarchy cannot be cycled. + // It's here just to avoid infinite loop in case we have such cycle. + log.error("Detected a cycle of \"derived from\" edges starting at type node {}", childType); + return Either.right(StorageOperationStatus.GENERAL_ERROR); + } + + + + @Override + public <T extends GraphNode> StorageOperationStatus isUpdateParentAllowed(String oldTypeParent, String newTypeParent, String childType, + NodeTypeEnum nodeType, Class<T> clazz, + Function<T, String> typeProvider) { + StorageOperationStatus status; + if (oldTypeParent != null) { + + Either<Boolean, StorageOperationStatus> result = isTypeDerivedFrom(newTypeParent, oldTypeParent, childType, nodeType, clazz, typeProvider); + if (result.isRight()) { + log.debug("#isUpdateParentAllowed - failed to detect that new parent {} is derived from the current parent {}", newTypeParent, oldTypeParent); + status = result.right().value(); + } + else { + if (result.left().value()) { + log.debug("#isUpdateParentAllowed - update is allowed since new parent {} is derived from the current parent {}", newTypeParent, oldTypeParent); + status = StorageOperationStatus.OK; + } + else { + log.debug("#isUpdateParentAllowed - update is not allowed since new parent {} is not derived from the current parent {}", newTypeParent, oldTypeParent); + status = StorageOperationStatus.CANNOT_UPDATE_EXISTING_ENTITY; + } + } + + } + else { + log.debug("#isUpdateParentAllowed - the update is allowed since the parent still has been not set." ); + status = StorageOperationStatus.OK; + } + + return status; + } } 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 41f6ce9d00..fd455bcde8 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 @@ -20,12 +20,9 @@ package org.openecomp.sdc.be.model.operations.impl; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.TitanVertex; +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.ArtifactTypeConfig; @@ -55,776 +52,773 @@ import org.openecomp.sdc.be.resources.data.TagData; import org.openecomp.sdc.be.resources.data.category.CategoryData; import org.openecomp.sdc.be.resources.data.category.GroupingData; import org.openecomp.sdc.be.resources.data.category.SubCategoryData; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.util.ValidationUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; -import com.thinkaurelius.titan.core.TitanGraph; -//import com.tinkerpop.blueprints.Vertex; -import com.thinkaurelius.titan.core.TitanVertex; - -import fj.data.Either; +import java.util.*; @Component("element-operation") public class ElementOperation implements IElementOperation { + private static final String COULDN_T_FETCH_TITAN_GRAPH = "Couldn't fetch titan graph"; + private static final String UNKNOWN_CATEGORY_TYPE = "Unknown category type {}"; private TitanGenericDao titanGenericDao; - public ElementOperation(@Qualifier("titan-generic-dao") TitanGenericDao titanGenericDao) { - super(); - this.titanGenericDao = titanGenericDao; - } - - private static Logger log = LoggerFactory.getLogger(ElementOperation.class.getName()); - - /* - * Old flow - */ - @Override - public Either<List<CategoryDefinition>, ActionStatus> getAllServiceCategories() { - return getAllCategories(NodeTypeEnum.ServiceNewCategory, false); - } - - @Override - public Either<List<CategoryDefinition>, ActionStatus> getAllResourceCategories() { - return getAllCategories(NodeTypeEnum.ResourceNewCategory, false); - } - - @Override - public Either<List<CategoryDefinition>, ActionStatus> getAllProductCategories() { - return getAllCategories(NodeTypeEnum.ProductCategory, false); - } - /* - * - */ - - /* - * New flow - */ - @Override - public Either<CategoryDefinition, ActionStatus> createCategory(CategoryDefinition category, NodeTypeEnum nodeType) { - return createCategory(category, nodeType, false); - } - - @Override - public Either<CategoryDefinition, ActionStatus> createCategory(CategoryDefinition category, NodeTypeEnum nodeType, boolean inTransaction) { - Either<CategoryDefinition, ActionStatus> result = null; - category.setUniqueId(UniqueIdBuilder.buildCategoryUid(category.getNormalizedName(), nodeType)); - CategoryData categoryData = new CategoryData(nodeType, category); - - try { - Either<CategoryData, TitanOperationStatus> createNode = titanGenericDao.createNode(categoryData, CategoryData.class); - if (createNode.isRight()) { - TitanOperationStatus value = createNode.right().value(); - ActionStatus actionStatus = ActionStatus.GENERAL_ERROR; - log.debug("Problem while creating category, reason {}", value); - if (value == TitanOperationStatus.TITAN_SCHEMA_VIOLATION) { - actionStatus = ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS; - } - result = Either.right(actionStatus); - return result; - } - CategoryDefinition created = new CategoryDefinition(createNode.left().value().getCategoryDataDefinition()); - result = Either.left(created); - return result; - } finally { - if (inTransaction == false) { - if (result != null && result.isLeft()) { - titanGenericDao.commit(); - } else { - titanGenericDao.rollback(); - } - } - } - } - - @Override - public Either<SubCategoryDefinition, ActionStatus> createSubCategory(String categoryId, SubCategoryDefinition subCategory, NodeTypeEnum nodeType) { - return createSubCategory(categoryId, subCategory, nodeType, false); - } - - @Override - public Either<SubCategoryDefinition, ActionStatus> createSubCategory(String categoryId, SubCategoryDefinition subCategory, NodeTypeEnum nodeType, boolean inTransaction) { - - Either<SubCategoryDefinition, ActionStatus> result = null; - - try { - // create edge from category to sub-category - Either<CategoryData, TitanOperationStatus> categoryNode = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), categoryId, CategoryData.class); - ActionStatus actionStatus = ActionStatus.GENERAL_ERROR; - if (categoryNode.isRight()) { - TitanOperationStatus titanOperationStatus = categoryNode.right().value(); - log.debug("Problem while fetching category, reason {}", titanOperationStatus); - if (titanOperationStatus == TitanOperationStatus.NOT_FOUND) { - actionStatus = ActionStatus.COMPONENT_CATEGORY_NOT_FOUND; - } - result = Either.right(actionStatus); - return result; - } - - CategoryDataDefinition categoryDataDefinition = categoryNode.left().value().getCategoryDataDefinition(); - subCategory.setUniqueId(UniqueIdBuilder.buildSubCategoryUid(categoryDataDefinition.getUniqueId(), subCategory.getNormalizedName())); - SubCategoryData subCategoryData = new SubCategoryData(nodeType, subCategory); - - Either<SubCategoryData, TitanOperationStatus> subCategoryNode = titanGenericDao.createNode(subCategoryData, SubCategoryData.class); - if (subCategoryNode.isRight()) { - TitanOperationStatus titanOperationStatus = subCategoryNode.right().value(); - log.debug("Problem while creating category, reason {}", titanOperationStatus); - if (titanOperationStatus == TitanOperationStatus.TITAN_SCHEMA_VIOLATION) { - actionStatus = ActionStatus.COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY; - } - result = Either.right(actionStatus); - return result; - } - - Either<GraphRelation, TitanOperationStatus> relation = titanGenericDao.createRelation(categoryNode.left().value(), subCategoryNode.left().value(), GraphEdgeLabels.SUB_CATEGORY, null); - if (relation.isRight()) { - log.debug("Problem while create relation between category and sub-category ", relation.right().value()); - result = Either.right(actionStatus); - return result; - } - SubCategoryDefinition subCategoryCreated = new SubCategoryDefinition(subCategoryNode.left().value().getSubCategoryDataDefinition()); - result = Either.left(subCategoryCreated); - return result; - } finally { - if (inTransaction == false) { - if (result != null && result.isLeft()) { - titanGenericDao.commit(); - } else { - titanGenericDao.rollback(); - } - } - } - } - - @Override - public Either<GroupingDefinition, ActionStatus> createGrouping(String subCategoryId, GroupingDefinition grouping, NodeTypeEnum nodeType) { - - Either<GroupingDefinition, ActionStatus> result = null; - - try { - // create edge from sub-category to grouping - Either<SubCategoryData, TitanOperationStatus> subCategoryNode = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId, SubCategoryData.class); - ActionStatus actionStatus = ActionStatus.GENERAL_ERROR; - if (subCategoryNode.isRight()) { - TitanOperationStatus titanOperationStatus = subCategoryNode.right().value(); - log.debug("Problem while fetching category, reason {}", titanOperationStatus); - if (titanOperationStatus == TitanOperationStatus.TITAN_SCHEMA_VIOLATION) { - actionStatus = ActionStatus.COMPONENT_CATEGORY_NOT_FOUND; - } - result = Either.right(actionStatus); - return result; - } - - SubCategoryDataDefinition subCatData = subCategoryNode.left().value().getSubCategoryDataDefinition(); - grouping.setUniqueId(UniqueIdBuilder.buildGroupingUid(subCatData.getUniqueId(), grouping.getNormalizedName())); - GroupingData groupingData = new GroupingData(nodeType, grouping); - - Either<GroupingData, TitanOperationStatus> groupingNode = titanGenericDao.createNode(groupingData, GroupingData.class); - if (groupingNode.isRight()) { - TitanOperationStatus titanOperationStatus = groupingNode.right().value(); - log.debug("Problem while creating grouping, reason {}", titanOperationStatus); - if (titanOperationStatus == TitanOperationStatus.NOT_FOUND) { - actionStatus = ActionStatus.COMPONENT_GROUPING_EXISTS_FOR_SUB_CATEGORY; - } - result = Either.right(actionStatus); - return result; - } - - Either<GraphRelation, TitanOperationStatus> relation = titanGenericDao.createRelation(subCategoryNode.left().value(), groupingNode.left().value(), GraphEdgeLabels.GROUPING, null); - if (relation.isRight()) { - log.debug("Problem while create relation between sub-category and grouping", relation.right().value()); - result = Either.right(actionStatus); - return result; - } - GroupingDefinition groupingCreated = new GroupingDefinition(groupingNode.left().value().getGroupingDataDefinition()); - result = Either.left(groupingCreated); - return result; - } finally { - if (result != null && result.isLeft()) { - titanGenericDao.commit(); - } else { - titanGenericDao.rollback(); - } - } - } - - @Override - public Either<List<CategoryDefinition>, ActionStatus> getAllCategories(NodeTypeEnum nodeType, boolean inTransaction) { - try { - if (nodeType != NodeTypeEnum.ResourceNewCategory && nodeType != NodeTypeEnum.ServiceNewCategory && nodeType != NodeTypeEnum.ProductCategory) { - log.debug("Unknown category type {}", nodeType.name()); - return Either.right(ActionStatus.GENERAL_ERROR); - } - - Either<List<org.openecomp.sdc.be.resources.data.category.CategoryData>, TitanOperationStatus> either = titanGenericDao.getAll(nodeType, org.openecomp.sdc.be.resources.data.category.CategoryData.class); - if (either.isRight() && (either.right().value() != TitanOperationStatus.NOT_FOUND)) { - log.debug("Problem while get all categories. reason - {}", either.right().value()); - return Either.right(ActionStatus.GENERAL_ERROR); - } - List<CategoryData> categoryDataList = either.isLeft() ? either.left().value() : null; - List<CategoryDefinition> categoryList = new ArrayList<CategoryDefinition>(); - if (categoryDataList != null) { - for (CategoryData elem : categoryDataList) { - CategoryDataDefinition categoryDataDefinition = elem.getCategoryDataDefinition(); - - CategoryDefinition categoryDefinition = new CategoryDefinition(categoryDataDefinition); - String categoryName = categoryDataDefinition.getName(); - log.trace("Found category {}, category type {}", categoryName, nodeType); - TitanOperationStatus setSubCategories = setSubCategories(nodeType, categoryDefinition); - if (setSubCategories != TitanOperationStatus.OK) { - log.debug("Failed to set sub-categories for category {}, category type {}, error {}", categoryName, nodeType, setSubCategories); - return Either.right(ActionStatus.GENERAL_ERROR); - } - categoryList.add(categoryDefinition); - } - } - return Either.left(categoryList); - } finally { - if (!inTransaction) { - titanGenericDao.commit(); - } - } - } - - private TitanOperationStatus setSubCategories(NodeTypeEnum parentNodeType, CategoryDefinition parentCategory) { - NodeTypeEnum childNodeType = getChildNodeType(parentNodeType); - if (childNodeType != null) { - String categoryName = parentCategory.getName(); - log.trace("Getting sub-categories for category {}, category type {}", categoryName, parentNodeType); - Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, TitanOperationStatus> parentNode = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(parentNodeType), parentCategory.getUniqueId(), GraphEdgeLabels.SUB_CATEGORY, - childNodeType, SubCategoryData.class); - if (parentNode.isRight()) { - TitanOperationStatus titanOperationStatus = parentNode.right().value(); - if (titanOperationStatus == TitanOperationStatus.NOT_FOUND) { - log.trace("Didn't find subcategories for category {}, category type {}", categoryName, parentNodeType); - titanOperationStatus = TitanOperationStatus.OK; - } - return titanOperationStatus; - } - List<ImmutablePair<SubCategoryData, GraphEdge>> subsCategoriesData = parentNode.left().value(); - List<SubCategoryDefinition> subCategoriesDefinitions = new ArrayList<>(); - for (ImmutablePair<SubCategoryData, GraphEdge> subCatPair : subsCategoriesData) { - SubCategoryDataDefinition subCategoryDataDefinition = subCatPair.getLeft().getSubCategoryDataDefinition(); - SubCategoryDefinition subCategoryDefinition = new SubCategoryDefinition(subCategoryDataDefinition); - - log.trace("Found sub-category {} for category {}, category type {}", subCategoryDataDefinition.getName(), categoryName, parentNodeType); - TitanOperationStatus setGroupings = setGroupings(childNodeType, subCategoryDefinition); - if (setGroupings != TitanOperationStatus.OK) { - log.debug("Failed to set groupings for sub-category {}, sub-category type {}, error {}", subCategoryDataDefinition.getName(), childNodeType, setGroupings); - return TitanOperationStatus.GENERAL_ERROR; - } - subCategoriesDefinitions.add(subCategoryDefinition); - } - parentCategory.setSubcategories(subCategoriesDefinitions); - } - return TitanOperationStatus.OK; - } - - private TitanOperationStatus setGroupings(NodeTypeEnum parentNodeType, SubCategoryDefinition parentSubCategory) { - NodeTypeEnum childNodeType = getChildNodeType(parentNodeType); - if (childNodeType != null) { - String subCategoryName = parentSubCategory.getName(); - log.trace("Getting groupings for subcategory {}, subcategory type {}", subCategoryName, parentNodeType); - Either<List<ImmutablePair<GroupingData, GraphEdge>>, TitanOperationStatus> parentNode = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(parentNodeType), parentSubCategory.getUniqueId(), GraphEdgeLabels.GROUPING, - childNodeType, GroupingData.class); - if (parentNode.isRight()) { - TitanOperationStatus titanOperationStatus = parentNode.right().value(); - if (titanOperationStatus == TitanOperationStatus.NOT_FOUND) { - log.trace("Didn't find groupings for subcategory {}, subcategory type {}", subCategoryName, parentNodeType); - titanOperationStatus = TitanOperationStatus.OK; - } - return titanOperationStatus; - } - List<ImmutablePair<GroupingData, GraphEdge>> groupingData = parentNode.left().value(); - List<GroupingDefinition> groupingDefinitions = new ArrayList<>(); - for (ImmutablePair<GroupingData, GraphEdge> groupPair : groupingData) { - GroupingDataDefinition groupingDataDefinition = groupPair.getLeft().getGroupingDataDefinition(); - log.trace("Found grouping {} for sub-category {}, sub-category type {}", groupingDataDefinition.getName(), subCategoryName, parentNodeType); - groupingDefinitions.add(new GroupingDefinition(groupingDataDefinition)); - } - parentSubCategory.setGroupings(groupingDefinitions); - } - return TitanOperationStatus.OK; - } - - private static NodeTypeEnum getChildNodeType(NodeTypeEnum parentTypeEnum) { - NodeTypeEnum res = null; - switch (parentTypeEnum) { - case ResourceNewCategory: - res = NodeTypeEnum.ResourceSubcategory; - break; - case ProductCategory: - res = NodeTypeEnum.ProductSubcategory; - break; - case ProductSubcategory: - res = NodeTypeEnum.ProductGrouping; - break; - default: - break; - } - return res; - } - - @Override - public Either<CategoryDefinition, ActionStatus> getCategory(NodeTypeEnum nodeType, String categoryId) { - try { - if (nodeType != NodeTypeEnum.ResourceNewCategory && nodeType != NodeTypeEnum.ServiceNewCategory && nodeType != NodeTypeEnum.ProductCategory) { - log.debug("Unknown category type {}", nodeType.name()); - return Either.right(ActionStatus.GENERAL_ERROR); - } - - Either<CategoryData, TitanOperationStatus> categoryDataEither = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), categoryId, CategoryData.class); - if (categoryDataEither.isRight()) { - TitanOperationStatus titanOperationStatus = categoryDataEither.right().value(); - log.debug("Problem while get category by id {}. reason {}", categoryId, titanOperationStatus); - if (titanOperationStatus == TitanOperationStatus.NOT_FOUND) { - return Either.right(ActionStatus.COMPONENT_CATEGORY_NOT_FOUND); - } - return Either.right(ActionStatus.GENERAL_ERROR); - } - CategoryDataDefinition categoryDataDefinition = categoryDataEither.left().value().getCategoryDataDefinition(); - return Either.left(new CategoryDefinition(categoryDataDefinition)); - } finally { - titanGenericDao.commit(); - } - } - - @Override - public Either<SubCategoryDefinition, ActionStatus> getSubCategory(NodeTypeEnum nodeType, String subCategoryId) { - try { - if (nodeType != NodeTypeEnum.ResourceSubcategory && nodeType != NodeTypeEnum.ProductSubcategory) { - log.debug("Unknown sub-category type {}", nodeType.name()); - return Either.right(ActionStatus.GENERAL_ERROR); - } - - Either<SubCategoryData, TitanOperationStatus> subCategoryDataEither = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId, SubCategoryData.class); - if (subCategoryDataEither.isRight()) { - TitanOperationStatus titanOperationStatus = subCategoryDataEither.right().value(); - log.debug("Problem while get sub-category by id {}. reason {}", subCategoryId, titanOperationStatus); - if (titanOperationStatus == TitanOperationStatus.NOT_FOUND) { - return Either.right(ActionStatus.COMPONENT_CATEGORY_NOT_FOUND); - } - return Either.right(ActionStatus.GENERAL_ERROR); - } - SubCategoryDataDefinition subCategoryDataDefinition = subCategoryDataEither.left().value().getSubCategoryDataDefinition(); - return Either.left(new SubCategoryDefinition(subCategoryDataDefinition)); - } finally { - titanGenericDao.commit(); - } - } - - @Override - public Either<CategoryDefinition, ActionStatus> deleteCategory(NodeTypeEnum nodeType, String categoryId) { - Either<CategoryDefinition, ActionStatus> result = null; - try { - if (nodeType != NodeTypeEnum.ResourceNewCategory && nodeType != NodeTypeEnum.ServiceNewCategory && nodeType != NodeTypeEnum.ProductCategory) { - log.debug("Unknown category type {}", nodeType.name()); - result = Either.right(ActionStatus.GENERAL_ERROR); - return result; - } - Either<CategoryData, TitanOperationStatus> categoryDataEither = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), categoryId, CategoryData.class); - if (categoryDataEither.isRight()) { - log.debug("Failed to retrieve category for id {} ", categoryId); - result = Either.right(ActionStatus.GENERAL_ERROR); - return result; - } - - Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph(); - if (graph.isRight()) { - log.debug("Couldn't fetch titan graph"); - result = Either.right(ActionStatus.GENERAL_ERROR); - return result; - } - - TitanGraph tGraph = graph.left().value(); - - Iterable<TitanVertex> verticesArtifact = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(nodeType), categoryId).vertices(); - Iterator<TitanVertex> iterator = verticesArtifact.iterator(); - if (!iterator.hasNext()) { - log.debug("No category node for id = {}", categoryId); - result = Either.right(ActionStatus.GENERAL_ERROR); - return result; - } - Vertex artifactV = iterator.next(); - artifactV.remove(); - CategoryDefinition deleted = new CategoryDefinition(categoryDataEither.left().value().getCategoryDataDefinition()); - result = Either.left(deleted); - return result; - } finally { - if (result != null && result.isLeft()) { - titanGenericDao.commit(); - } else { - titanGenericDao.rollback(); - } - } - } - - @Override - public Either<SubCategoryDefinition, ActionStatus> deleteSubCategory(NodeTypeEnum nodeType, String subCategoryId) { - Either<SubCategoryDefinition, ActionStatus> result = null; - try { - if (nodeType != NodeTypeEnum.ResourceSubcategory && nodeType != NodeTypeEnum.ProductSubcategory) { - log.debug("Unknown sub-category type {}", nodeType.name()); - result = Either.right(ActionStatus.GENERAL_ERROR); - return result; - } - Either<SubCategoryData, TitanOperationStatus> subCategoryDataEither = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId, SubCategoryData.class); - if (subCategoryDataEither.isRight()) { - log.debug("Failed to retrieve sub-category for id {}", subCategoryId); - result = Either.right(ActionStatus.GENERAL_ERROR); - return result; - } - - Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph(); - if (graph.isRight()) { - log.debug("Couldn't fetch titan graph"); - result = Either.right(ActionStatus.GENERAL_ERROR); - return result; - } - - TitanGraph tGraph = graph.left().value(); - - Iterable<TitanVertex> verticesArtifact = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId).vertices(); - Iterator<TitanVertex> iterator = verticesArtifact.iterator(); - if (!iterator.hasNext()) { - log.debug("No sub-category node for id {}", subCategoryId); - result = Either.right(ActionStatus.GENERAL_ERROR); - return result; - } - Vertex artifactV = iterator.next(); - artifactV.remove(); - ; - SubCategoryDefinition deleted = new SubCategoryDefinition(subCategoryDataEither.left().value().getSubCategoryDataDefinition()); - result = Either.left(deleted); - return result; - } finally { - if (result != null && result.isLeft()) { - titanGenericDao.commit(); - } else { - titanGenericDao.rollback(); - } - } - - } - - @Override - public Either<GroupingDefinition, ActionStatus> deleteGrouping(NodeTypeEnum nodeType, String groupingId) { - Either<GroupingDefinition, ActionStatus> result = null; - try { - if (nodeType != NodeTypeEnum.ProductGrouping) { - log.debug("Unknown grouping type {}", nodeType.name()); - result = Either.right(ActionStatus.GENERAL_ERROR); - return result; - } - Either<GroupingData, TitanOperationStatus> groupingDataEither = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), groupingId, GroupingData.class); - if (groupingDataEither.isRight()) { - log.debug("Failed to retrieve grouping for id {}", groupingId); - result = Either.right(ActionStatus.GENERAL_ERROR); - return result; - } - - Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph(); - if (graph.isRight()) { - log.debug("Couldn't fetch titan graph"); - result = Either.right(ActionStatus.GENERAL_ERROR); - return result; - } - - TitanGraph tGraph = graph.left().value(); - - Iterable<TitanVertex> verticesArtifact = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(nodeType), groupingId).vertices(); - Iterator<TitanVertex> iterator = verticesArtifact.iterator(); - if (!iterator.hasNext()) { - log.debug("No grouping node for id {}", groupingId); - result = Either.right(ActionStatus.GENERAL_ERROR); - return result; - } - Vertex artifactV = iterator.next(); - artifactV.remove(); - ; - GroupingDefinition deleted = new GroupingDefinition(groupingDataEither.left().value().getGroupingDataDefinition()); - result = Either.left(deleted); - return result; - } finally { - if (result != null && result.isLeft()) { - titanGenericDao.commit(); - } else { - titanGenericDao.rollback(); - } - } - } - - @Override - public Either<Boolean, ActionStatus> isCategoryUniqueForType(NodeTypeEnum nodeType, String normalizedName) { - - Map<String, Object> properties = new HashMap<>(); - properties.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), normalizedName); - try { - Either<List<CategoryData>, TitanOperationStatus> categoryEither = titanGenericDao.getByCriteria(nodeType, properties, CategoryData.class); - if (categoryEither.isRight() && categoryEither.right().value() != TitanOperationStatus.NOT_FOUND) { - log.debug("Failed to get categories, nodeType {}, normalizedName {}, error {}", nodeType, normalizedName, categoryEither.right().value()); - return Either.right(ActionStatus.GENERAL_ERROR); - } - List<CategoryData> categoryList = (categoryEither.isLeft() ? categoryEither.left().value() : null); - if (categoryList != null && categoryList.size() > 0) { - log.debug("Found category for nodeType {} with normalizedName {}", nodeType, normalizedName); - if (categoryList.size() > 1) { - log.debug("Found more than 1 unique categories for nodeType {} with normalizedName", nodeType, normalizedName); - return Either.right(ActionStatus.GENERAL_ERROR); - } - return Either.left(false); - } else { - log.debug("Category for nodeType {} with normalizedName {} doesn't exist in graph", nodeType, normalizedName); - return Either.left(true); - } - } finally { - titanGenericDao.commit(); - } - } - - @Override - public Either<Boolean, ActionStatus> isSubCategoryUniqueForCategory(NodeTypeEnum nodeType, String subCategoryNormName, String parentCategoryId) { - - String subCategoryId = UniqueIdBuilder.buildSubCategoryUid(parentCategoryId, subCategoryNormName); - try { - Either<SubCategoryData, TitanOperationStatus> subCategoryDataEither = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId, SubCategoryData.class); - if (subCategoryDataEither.isRight() && subCategoryDataEither.right().value() != TitanOperationStatus.NOT_FOUND) { - log.debug("Failed to get sub-category with id {}, error {}", subCategoryId, subCategoryDataEither.right().value()); - return Either.right(ActionStatus.GENERAL_ERROR); - } - SubCategoryData subCategoryData = (subCategoryDataEither.isLeft() ? subCategoryDataEither.left().value() : null); - if (subCategoryData != null) { - log.debug("Found sub-category with id {}", subCategoryId); - return Either.left(false); - } else { - log.debug("Sub-category for id {} doesn't exist in graph", subCategoryId); - return Either.left(true); - } - } finally { - titanGenericDao.commit(); - } - } - - @Override - public Either<Boolean, ActionStatus> isGroupingUniqueForSubCategory(NodeTypeEnum nodeType, String groupingNormName, String parentSubCategoryId) { - - String groupingId = UniqueIdBuilder.buildGroupingUid(parentSubCategoryId, groupingNormName); - try { - Either<GroupingData, TitanOperationStatus> groupingDataEither = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), groupingId, GroupingData.class); - if (groupingDataEither.isRight() && groupingDataEither.right().value() != TitanOperationStatus.NOT_FOUND) { - log.debug("Failed to get grouping with id {}, error {}", groupingId, groupingDataEither.right().value()); - return Either.right(ActionStatus.GENERAL_ERROR); - } - GroupingData groupingData = (groupingDataEither.isLeft() ? groupingDataEither.left().value() : null); - if (groupingData != null) { - log.debug("Found grouping with id {}", groupingId); - return Either.left(false); - } else { - log.debug("Grouping for id {} doesn't exist in graph", groupingId); - return Either.left(true); - } - } finally { - titanGenericDao.commit(); - } - } - - @Override - public Either<SubCategoryDefinition, ActionStatus> getSubCategoryUniqueForType(NodeTypeEnum nodeType, String normalizedName) { - Map<String, Object> properties = new HashMap<>(); - properties.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), normalizedName); - try { - Either<List<SubCategoryData>, TitanOperationStatus> subCategoryEither = titanGenericDao.getByCriteria(nodeType, properties, SubCategoryData.class); - if (subCategoryEither.isRight() && subCategoryEither.right().value() != TitanOperationStatus.NOT_FOUND) { - log.debug("Failed to get sub-categories, nodeType {}, normalizedName {}, error {}", nodeType, normalizedName, subCategoryEither.right().value()); - return Either.right(ActionStatus.GENERAL_ERROR); - } - List<SubCategoryData> subCategoryList = (subCategoryEither.isLeft() ? subCategoryEither.left().value() : null); - if (subCategoryList != null && subCategoryList.size() > 0) { - log.debug("Found sub-category for nodeType {} with normalizedName {}", nodeType, normalizedName); - SubCategoryData subCategoryData = subCategoryList.get(0); - SubCategoryDefinition subCategoryDefinition = new SubCategoryDefinition(subCategoryData.getSubCategoryDataDefinition()); - return Either.left(subCategoryDefinition); - } else { - log.debug("Sub-category for nodeType {} with normalizedName {} doesn't exist in graph", nodeType, normalizedName); - return Either.left(null); - } - } finally { - titanGenericDao.commit(); - } - } - - @Override - public Either<GroupingDefinition, ActionStatus> getGroupingUniqueForType(NodeTypeEnum nodeType, String groupingNormalizedName) { - Map<String, Object> properties = new HashMap<>(); - properties.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), groupingNormalizedName); - try { - Either<List<GroupingData>, TitanOperationStatus> groupingEither = titanGenericDao.getByCriteria(nodeType, properties, GroupingData.class); - if (groupingEither.isRight() && groupingEither.right().value() != TitanOperationStatus.NOT_FOUND) { - log.debug("Failed to get grouping, nodeType {}, normalizedName {}, error {}", nodeType, groupingNormalizedName, groupingEither.right().value()); - return Either.right(ActionStatus.GENERAL_ERROR); - } - List<GroupingData> groupingList = (groupingEither.isLeft() ? groupingEither.left().value() : null); - if (groupingList != null && groupingList.size() > 0) { - log.debug("Found grouping for nodeType {} with normalizedName {}", nodeType, groupingNormalizedName); - GroupingData groupingData = groupingList.get(0); - GroupingDefinition groupingDefinition = new GroupingDefinition(groupingData.getGroupingDataDefinition()); - return Either.left(groupingDefinition); - } else { - log.debug("Grouping for nodeType {} with normalizedName {} doesn't exist in graph", nodeType, groupingNormalizedName); - return Either.left(null); - } - } finally { - titanGenericDao.commit(); - } - } - - /* - * - */ - - @Override - public Either<List<Tag>, ActionStatus> getAllTags() { - try { - Either<List<TagData>, TitanOperationStatus> either = titanGenericDao.getAll(NodeTypeEnum.Tag, TagData.class); - if (either.isRight()) { - log.debug("Problem while get all tags. reason - {}", either.right().value()); - return Either.right(ActionStatus.GENERAL_ERROR); - } - List<TagData> tagDataList = either.left().value(); - List<Tag> tagList = convertToListOfTag(tagDataList); - return Either.left(tagList); - } finally { - titanGenericDao.commit(); - } - } - - @Override - public <T extends GraphNode> Either<org.openecomp.sdc.be.resources.data.CategoryData, StorageOperationStatus> getCategoryData(String name, NodeTypeEnum type, Class<T> clazz) { - if (name != null) { - String categoryUid = null; - if (type == NodeTypeEnum.ResourceCategory) { - String[] categoryFields = name.split("/"); - if (categoryFields.length != 2) { - return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND); - } - categoryUid = UniqueIdBuilder.buildResourceCategoryUid(categoryFields[0], categoryFields[1], type); - } else { - categoryUid = UniqueIdBuilder.buildServiceCategoryUid(name, type); - } - Either<T, TitanOperationStatus> either = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(type), categoryUid, clazz); - - if (either.isRight()) { - TitanOperationStatus titanOperationStatus = either.right().value(); - log.debug("Problem while geting category with id {}. reason - {}", categoryUid, titanOperationStatus.name()); - if (titanOperationStatus == TitanOperationStatus.NOT_FOUND) { - return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND); - } else { - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - } - return Either.left((org.openecomp.sdc.be.resources.data.CategoryData) either.left().value()); - } else { - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - } - - private List<Tag> convertToListOfTag(List<TagData> tagDataList) { - List<Tag> tagList = new ArrayList<Tag>(); - for (TagData elem : tagDataList) { - Tag tag = new Tag(); - tag.setName(elem.getName()); - tagList.add(tag); - } - return tagList; - } - - @Override - public Either<List<PropertyScope>, ActionStatus> getAllPropertyScopes() { - // Mock - List<PropertyScope> propertyScopes = new ArrayList<PropertyScope>(); - PropertyScope propertyScope1 = new PropertyScope(); - propertyScope1.setName("A&AI"); - PropertyScope propertyScope2 = new PropertyScope(); - propertyScope2.setName("Order"); - PropertyScope propertyScope3 = new PropertyScope(); - propertyScope3.setName("Runtime"); - propertyScopes.add(propertyScope1); - propertyScopes.add(propertyScope2); - propertyScopes.add(propertyScope3); - return Either.left(propertyScopes); - } - - @Override - public Either<List<ArtifactType>, ActionStatus> getAllArtifactTypes() { - List<ArtifactType> artifactTypes = new ArrayList<ArtifactType>(); - - List<String> artifactTypesList = ConfigurationManager.getConfigurationManager().getConfiguration().getArtifactTypes(); - for (String artifactType : artifactTypesList) { - ArtifactType artifactT = new ArtifactType(); - artifactT.setName(artifactType); - artifactTypes.add(artifactT); - } - return Either.left(artifactTypes); - } - - @Override - public Either<Map<String, Object>, ActionStatus> getAllDeploymentArtifactTypes() { - - Map<String, Object> artifactTypes = new HashMap<String, Object>(); - Map<String, ArtifactTypeConfig> artifactResourceTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts(); - Map<String, ArtifactTypeConfig> artifactServiceTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts(); - Map<String, ArtifactTypeConfig> artifactResourceInstanceTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts(); - - artifactTypes.put("resourceDeploymentArtifacts", artifactResourceTypes); - artifactTypes.put("serviceDeploymentArtifacts", artifactServiceTypes); - artifactTypes.put("resourceInstanceDeploymentArtifacts", artifactResourceInstanceTypes); - - return Either.left(artifactTypes); - - } - - @Override - public Either<Integer, ActionStatus> getDefaultHeatTimeout() { - return Either.left(ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes()); - } - - @Override - public Either<Map<String, String>, ActionStatus> getResourceTypesMap() { - ResourceTypeEnum[] enumConstants = ResourceTypeEnum.class.getEnumConstants(); - Map<String, String> resourceTypes = new HashMap<String, String>(); - if (enumConstants != null) { - for (int i = 0; i < enumConstants.length; ++i) { - resourceTypes.put(enumConstants[i].name(), enumConstants[i].getValue()); - } - - } - return Either.left(resourceTypes); - } - - @Override - public <T extends GraphNode> Either<CategoryData, StorageOperationStatus> getNewCategoryData(String name, NodeTypeEnum type, Class<T> clazz) { - if (name != null) { - String categoryUid = UniqueIdBuilder.buildServiceCategoryUid(name, type); - Map props = new HashMap<>(); - props.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), ValidationUtils.normalizeCategoryName4Uniqueness(name)); - Either<List<T>, TitanOperationStatus> either = titanGenericDao.getByCriteria(type, props, clazz); - - if (either.isRight()) { - TitanOperationStatus titanOperationStatus = either.right().value(); - log.debug("Problem while geting category with id {}. reason - {}", categoryUid, titanOperationStatus.name()); - if (titanOperationStatus == TitanOperationStatus.NOT_FOUND) { - return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND); - } else { - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - } - return Either.left((CategoryData) either.left().value().get(0)); - } else { - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - } + public ElementOperation(@Qualifier("titan-generic-dao") TitanGenericDao titanGenericDao) { + super(); + this.titanGenericDao = titanGenericDao; + } + + private static final Logger log = Logger.getLogger(ElementOperation.class.getName()); + + /* + * Old flow + */ + @Override + public Either<List<CategoryDefinition>, ActionStatus> getAllServiceCategories() { + return getAllCategories(NodeTypeEnum.ServiceNewCategory, false); + } + + @Override + public Either<List<CategoryDefinition>, ActionStatus> getAllResourceCategories() { + return getAllCategories(NodeTypeEnum.ResourceNewCategory, false); + } + + @Override + public Either<List<CategoryDefinition>, ActionStatus> getAllProductCategories() { + return getAllCategories(NodeTypeEnum.ProductCategory, false); + } + /* + * + */ + + /* + * New flow + */ + @Override + public Either<CategoryDefinition, ActionStatus> createCategory(CategoryDefinition category, NodeTypeEnum nodeType) { + return createCategory(category, nodeType, false); + } + + @Override + public Either<CategoryDefinition, ActionStatus> createCategory(CategoryDefinition category, NodeTypeEnum nodeType, boolean inTransaction) { + Either<CategoryDefinition, ActionStatus> result = null; + category.setUniqueId(UniqueIdBuilder.buildCategoryUid(category.getNormalizedName(), nodeType)); + CategoryData categoryData = new CategoryData(nodeType, category); + + try { + Either<CategoryData, TitanOperationStatus> createNode = titanGenericDao.createNode(categoryData, CategoryData.class); + if (createNode.isRight()) { + TitanOperationStatus value = createNode.right().value(); + ActionStatus actionStatus = ActionStatus.GENERAL_ERROR; + log.debug("Problem while creating category, reason {}", value); + if (value == TitanOperationStatus.TITAN_SCHEMA_VIOLATION) { + actionStatus = ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS; + } + result = Either.right(actionStatus); + return result; + } + CategoryDefinition created = new CategoryDefinition(createNode.left().value().getCategoryDataDefinition()); + result = Either.left(created); + return result; + } finally { + if (!inTransaction) { + if (result != null && result.isLeft()) { + titanGenericDao.commit(); + } else { + titanGenericDao.rollback(); + } + } + } + } + + @Override + public Either<SubCategoryDefinition, ActionStatus> createSubCategory(String categoryId, SubCategoryDefinition subCategory, NodeTypeEnum nodeType) { + return createSubCategory(categoryId, subCategory, nodeType, false); + } + + @Override + public Either<SubCategoryDefinition, ActionStatus> createSubCategory(String categoryId, SubCategoryDefinition subCategory, NodeTypeEnum nodeType, boolean inTransaction) { + + Either<SubCategoryDefinition, ActionStatus> result = null; + + try { + // create edge from category to sub-category + Either<CategoryData, TitanOperationStatus> categoryNode = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), categoryId, CategoryData.class); + ActionStatus actionStatus = ActionStatus.GENERAL_ERROR; + if (categoryNode.isRight()) { + TitanOperationStatus titanOperationStatus = categoryNode.right().value(); + log.debug("Problem while fetching category, reason {}", titanOperationStatus); + if (titanOperationStatus == TitanOperationStatus.NOT_FOUND) { + actionStatus = ActionStatus.COMPONENT_CATEGORY_NOT_FOUND; + } + result = Either.right(actionStatus); + return result; + } + + CategoryDataDefinition categoryDataDefinition = categoryNode.left().value().getCategoryDataDefinition(); + subCategory.setUniqueId(UniqueIdBuilder.buildSubCategoryUid(categoryDataDefinition.getUniqueId(), subCategory.getNormalizedName())); + SubCategoryData subCategoryData = new SubCategoryData(nodeType, subCategory); + + Either<SubCategoryData, TitanOperationStatus> subCategoryNode = titanGenericDao.createNode(subCategoryData, SubCategoryData.class); + if (subCategoryNode.isRight()) { + TitanOperationStatus titanOperationStatus = subCategoryNode.right().value(); + log.debug("Problem while creating category, reason {}", titanOperationStatus); + if (titanOperationStatus == TitanOperationStatus.TITAN_SCHEMA_VIOLATION) { + actionStatus = ActionStatus.COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY; + } + result = Either.right(actionStatus); + return result; + } + + Either<GraphRelation, TitanOperationStatus> relation = titanGenericDao.createRelation(categoryNode.left().value(), subCategoryNode.left().value(), GraphEdgeLabels.SUB_CATEGORY, null); + if (relation.isRight()) { + log.debug("Problem while create relation between category and sub-category ", relation.right().value()); + result = Either.right(actionStatus); + return result; + } + SubCategoryDefinition subCategoryCreated = new SubCategoryDefinition(subCategoryNode.left().value().getSubCategoryDataDefinition()); + result = Either.left(subCategoryCreated); + return result; + } finally { + if (!inTransaction) { + if (result != null && result.isLeft()) { + titanGenericDao.commit(); + } else { + titanGenericDao.rollback(); + } + } + } + } + + @Override + public Either<GroupingDefinition, ActionStatus> createGrouping(String subCategoryId, GroupingDefinition grouping, NodeTypeEnum nodeType) { + + Either<GroupingDefinition, ActionStatus> result = null; + + try { + // create edge from sub-category to grouping + Either<SubCategoryData, TitanOperationStatus> subCategoryNode = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId, SubCategoryData.class); + ActionStatus actionStatus = ActionStatus.GENERAL_ERROR; + if (subCategoryNode.isRight()) { + TitanOperationStatus titanOperationStatus = subCategoryNode.right().value(); + log.debug("Problem while fetching category, reason {}", titanOperationStatus); + if (titanOperationStatus == TitanOperationStatus.TITAN_SCHEMA_VIOLATION) { + actionStatus = ActionStatus.COMPONENT_CATEGORY_NOT_FOUND; + } + result = Either.right(actionStatus); + return result; + } + + SubCategoryDataDefinition subCatData = subCategoryNode.left().value().getSubCategoryDataDefinition(); + grouping.setUniqueId(UniqueIdBuilder.buildGroupingUid(subCatData.getUniqueId(), grouping.getNormalizedName())); + GroupingData groupingData = new GroupingData(nodeType, grouping); + + Either<GroupingData, TitanOperationStatus> groupingNode = titanGenericDao.createNode(groupingData, GroupingData.class); + if (groupingNode.isRight()) { + TitanOperationStatus titanOperationStatus = groupingNode.right().value(); + log.debug("Problem while creating grouping, reason {}", titanOperationStatus); + if (titanOperationStatus == TitanOperationStatus.NOT_FOUND) { + actionStatus = ActionStatus.COMPONENT_GROUPING_EXISTS_FOR_SUB_CATEGORY; + } + result = Either.right(actionStatus); + return result; + } + + Either<GraphRelation, TitanOperationStatus> relation = titanGenericDao.createRelation(subCategoryNode.left().value(), groupingNode.left().value(), GraphEdgeLabels.GROUPING, null); + if (relation.isRight()) { + log.debug("Problem while create relation between sub-category and grouping", relation.right().value()); + result = Either.right(actionStatus); + return result; + } + GroupingDefinition groupingCreated = new GroupingDefinition(groupingNode.left().value().getGroupingDataDefinition()); + result = Either.left(groupingCreated); + return result; + } finally { + if (result != null && result.isLeft()) { + titanGenericDao.commit(); + } else { + titanGenericDao.rollback(); + } + } + } + + @Override + public Either<List<CategoryDefinition>, ActionStatus> getAllCategories(NodeTypeEnum nodeType, boolean inTransaction) { + try { + if (nodeType != NodeTypeEnum.ResourceNewCategory && nodeType != NodeTypeEnum.ServiceNewCategory && nodeType != NodeTypeEnum.ProductCategory) { + log.debug(UNKNOWN_CATEGORY_TYPE, nodeType.name()); + return Either.right(ActionStatus.GENERAL_ERROR); + } + + Either<List<org.openecomp.sdc.be.resources.data.category.CategoryData>, TitanOperationStatus> either = titanGenericDao.getAll(nodeType, org.openecomp.sdc.be.resources.data.category.CategoryData.class); + if (either.isRight() && (either.right().value() != TitanOperationStatus.NOT_FOUND)) { + log.debug("Problem while get all categories. reason - {}", either.right().value()); + return Either.right(ActionStatus.GENERAL_ERROR); + } + List<CategoryData> categoryDataList = either.isLeft() ? either.left().value() : null; + List<CategoryDefinition> categoryList = new ArrayList<>(); + if (categoryDataList != null) { + for (CategoryData elem : categoryDataList) { + CategoryDataDefinition categoryDataDefinition = elem.getCategoryDataDefinition(); + + CategoryDefinition categoryDefinition = new CategoryDefinition(categoryDataDefinition); + String categoryName = categoryDataDefinition.getName(); + log.trace("Found category {}, category type {}", categoryName, nodeType); + TitanOperationStatus setSubCategories = setSubCategories(nodeType, categoryDefinition); + if (setSubCategories != TitanOperationStatus.OK) { + log.debug("Failed to set sub-categories for category {}, category type {}, error {}", categoryName, nodeType, setSubCategories); + return Either.right(ActionStatus.GENERAL_ERROR); + } + categoryList.add(categoryDefinition); + } + } + return Either.left(categoryList); + } finally { + if (!inTransaction) { + titanGenericDao.commit(); + } + } + } + + private TitanOperationStatus setSubCategories(NodeTypeEnum parentNodeType, CategoryDefinition parentCategory) { + NodeTypeEnum childNodeType = getChildNodeType(parentNodeType); + if (childNodeType != null) { + String categoryName = parentCategory.getName(); + log.trace("Getting sub-categories for category {}, category type {}", categoryName, parentNodeType); + Either<List<ImmutablePair<SubCategoryData, GraphEdge>>, TitanOperationStatus> parentNode = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(parentNodeType), parentCategory.getUniqueId(), GraphEdgeLabels.SUB_CATEGORY, + childNodeType, SubCategoryData.class); + if (parentNode.isRight()) { + TitanOperationStatus titanOperationStatus = parentNode.right().value(); + if (titanOperationStatus == TitanOperationStatus.NOT_FOUND) { + log.trace("Didn't find subcategories for category {}, category type {}", categoryName, parentNodeType); + titanOperationStatus = TitanOperationStatus.OK; + } + return titanOperationStatus; + } + List<ImmutablePair<SubCategoryData, GraphEdge>> subsCategoriesData = parentNode.left().value(); + List<SubCategoryDefinition> subCategoriesDefinitions = new ArrayList<>(); + for (ImmutablePair<SubCategoryData, GraphEdge> subCatPair : subsCategoriesData) { + SubCategoryDataDefinition subCategoryDataDefinition = subCatPair.getLeft().getSubCategoryDataDefinition(); + SubCategoryDefinition subCategoryDefinition = new SubCategoryDefinition(subCategoryDataDefinition); + + log.trace("Found sub-category {} for category {}, category type {}", subCategoryDataDefinition.getName(), categoryName, parentNodeType); + TitanOperationStatus setGroupings = setGroupings(childNodeType, subCategoryDefinition); + if (setGroupings != TitanOperationStatus.OK) { + log.debug("Failed to set groupings for sub-category {}, sub-category type {}, error {}", subCategoryDataDefinition.getName(), childNodeType, setGroupings); + return TitanOperationStatus.GENERAL_ERROR; + } + subCategoriesDefinitions.add(subCategoryDefinition); + } + parentCategory.setSubcategories(subCategoriesDefinitions); + } + return TitanOperationStatus.OK; + } + + private TitanOperationStatus setGroupings(NodeTypeEnum parentNodeType, SubCategoryDefinition parentSubCategory) { + NodeTypeEnum childNodeType = getChildNodeType(parentNodeType); + if (childNodeType != null) { + String subCategoryName = parentSubCategory.getName(); + log.trace("Getting groupings for subcategory {}, subcategory type {}", subCategoryName, parentNodeType); + Either<List<ImmutablePair<GroupingData, GraphEdge>>, TitanOperationStatus> parentNode = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(parentNodeType), parentSubCategory.getUniqueId(), GraphEdgeLabels.GROUPING, + childNodeType, GroupingData.class); + if (parentNode.isRight()) { + TitanOperationStatus titanOperationStatus = parentNode.right().value(); + if (titanOperationStatus == TitanOperationStatus.NOT_FOUND) { + log.trace("Didn't find groupings for subcategory {}, subcategory type {}", subCategoryName, parentNodeType); + titanOperationStatus = TitanOperationStatus.OK; + } + return titanOperationStatus; + } + List<ImmutablePair<GroupingData, GraphEdge>> groupingData = parentNode.left().value(); + List<GroupingDefinition> groupingDefinitions = new ArrayList<>(); + for (ImmutablePair<GroupingData, GraphEdge> groupPair : groupingData) { + GroupingDataDefinition groupingDataDefinition = groupPair.getLeft().getGroupingDataDefinition(); + log.trace("Found grouping {} for sub-category {}, sub-category type {}", groupingDataDefinition.getName(), subCategoryName, parentNodeType); + groupingDefinitions.add(new GroupingDefinition(groupingDataDefinition)); + } + parentSubCategory.setGroupings(groupingDefinitions); + } + return TitanOperationStatus.OK; + } + + private static NodeTypeEnum getChildNodeType(NodeTypeEnum parentTypeEnum) { + NodeTypeEnum res = null; + switch (parentTypeEnum) { + case ResourceNewCategory: + res = NodeTypeEnum.ResourceSubcategory; + break; + case ProductCategory: + res = NodeTypeEnum.ProductSubcategory; + break; + case ProductSubcategory: + res = NodeTypeEnum.ProductGrouping; + break; + default: + break; + } + return res; + } + + @Override + public Either<CategoryDefinition, ActionStatus> getCategory(NodeTypeEnum nodeType, String categoryId) { + try { + if (nodeType != NodeTypeEnum.ResourceNewCategory && nodeType != NodeTypeEnum.ServiceNewCategory && nodeType != NodeTypeEnum.ProductCategory) { + log.debug(UNKNOWN_CATEGORY_TYPE, nodeType.name()); + return Either.right(ActionStatus.GENERAL_ERROR); + } + + Either<CategoryData, TitanOperationStatus> categoryDataEither = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), categoryId, CategoryData.class); + if (categoryDataEither.isRight()) { + TitanOperationStatus titanOperationStatus = categoryDataEither.right().value(); + log.debug("Problem while get category by id {}. reason {}", categoryId, titanOperationStatus); + if (titanOperationStatus == TitanOperationStatus.NOT_FOUND) { + return Either.right(ActionStatus.COMPONENT_CATEGORY_NOT_FOUND); + } + return Either.right(ActionStatus.GENERAL_ERROR); + } + CategoryDataDefinition categoryDataDefinition = categoryDataEither.left().value().getCategoryDataDefinition(); + return Either.left(new CategoryDefinition(categoryDataDefinition)); + } finally { + titanGenericDao.commit(); + } + } + + @Override + public Either<SubCategoryDefinition, ActionStatus> getSubCategory(NodeTypeEnum nodeType, String subCategoryId) { + try { + if (nodeType != NodeTypeEnum.ResourceSubcategory && nodeType != NodeTypeEnum.ProductSubcategory) { + log.debug("Unknown sub-category type {}", nodeType.name()); + return Either.right(ActionStatus.GENERAL_ERROR); + } + + Either<SubCategoryData, TitanOperationStatus> subCategoryDataEither = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId, SubCategoryData.class); + if (subCategoryDataEither.isRight()) { + TitanOperationStatus titanOperationStatus = subCategoryDataEither.right().value(); + log.debug("Problem while get sub-category by id {}. reason {}", subCategoryId, titanOperationStatus); + if (titanOperationStatus == TitanOperationStatus.NOT_FOUND) { + return Either.right(ActionStatus.COMPONENT_CATEGORY_NOT_FOUND); + } + return Either.right(ActionStatus.GENERAL_ERROR); + } + SubCategoryDataDefinition subCategoryDataDefinition = subCategoryDataEither.left().value().getSubCategoryDataDefinition(); + return Either.left(new SubCategoryDefinition(subCategoryDataDefinition)); + } finally { + titanGenericDao.commit(); + } + } + + @Override + public Either<CategoryDefinition, ActionStatus> deleteCategory(NodeTypeEnum nodeType, String categoryId) { + Either<CategoryDefinition, ActionStatus> result = null; + try { + if (nodeType != NodeTypeEnum.ResourceNewCategory && nodeType != NodeTypeEnum.ServiceNewCategory && nodeType != NodeTypeEnum.ProductCategory) { + log.debug(UNKNOWN_CATEGORY_TYPE, nodeType.name()); + result = Either.right(ActionStatus.GENERAL_ERROR); + return result; + } + Either<CategoryData, TitanOperationStatus> categoryDataEither = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), categoryId, CategoryData.class); + if (categoryDataEither.isRight()) { + log.debug("Failed to retrieve category for id {} ", categoryId); + result = Either.right(ActionStatus.GENERAL_ERROR); + return result; + } + + Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph(); + if (graph.isRight()) { + log.debug(COULDN_T_FETCH_TITAN_GRAPH); + result = Either.right(ActionStatus.GENERAL_ERROR); + return result; + } + + TitanGraph tGraph = graph.left().value(); + + Iterable<TitanVertex> verticesArtifact = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(nodeType), categoryId).vertices(); + Iterator<TitanVertex> iterator = verticesArtifact.iterator(); + if (!iterator.hasNext()) { + log.debug("No category node for id = {}", categoryId); + result = Either.right(ActionStatus.GENERAL_ERROR); + return result; + } + Vertex artifactV = iterator.next(); + artifactV.remove(); + CategoryDefinition deleted = new CategoryDefinition(categoryDataEither.left().value().getCategoryDataDefinition()); + result = Either.left(deleted); + return result; + } finally { + if (result != null && result.isLeft()) { + titanGenericDao.commit(); + } else { + titanGenericDao.rollback(); + } + } + } + + @Override + public Either<SubCategoryDefinition, ActionStatus> deleteSubCategory(NodeTypeEnum nodeType, String subCategoryId) { + Either<SubCategoryDefinition, ActionStatus> result = null; + try { + if (nodeType != NodeTypeEnum.ResourceSubcategory && nodeType != NodeTypeEnum.ProductSubcategory) { + log.debug("Unknown sub-category type {}", nodeType.name()); + result = Either.right(ActionStatus.GENERAL_ERROR); + return result; + } + Either<SubCategoryData, TitanOperationStatus> subCategoryDataEither = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId, SubCategoryData.class); + if (subCategoryDataEither.isRight()) { + log.debug("Failed to retrieve sub-category for id {}", subCategoryId); + result = Either.right(ActionStatus.GENERAL_ERROR); + return result; + } + + Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph(); + if (graph.isRight()) { + log.debug(COULDN_T_FETCH_TITAN_GRAPH); + result = Either.right(ActionStatus.GENERAL_ERROR); + return result; + } + + TitanGraph tGraph = graph.left().value(); + + Iterable<TitanVertex> verticesArtifact = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId).vertices(); + Iterator<TitanVertex> iterator = verticesArtifact.iterator(); + if (!iterator.hasNext()) { + log.debug("No sub-category node for id {}", subCategoryId); + result = Either.right(ActionStatus.GENERAL_ERROR); + return result; + } + Vertex artifactV = iterator.next(); + artifactV.remove(); + ; + SubCategoryDefinition deleted = new SubCategoryDefinition(subCategoryDataEither.left().value().getSubCategoryDataDefinition()); + result = Either.left(deleted); + return result; + } finally { + if (result != null && result.isLeft()) { + titanGenericDao.commit(); + } else { + titanGenericDao.rollback(); + } + } + + } + + @Override + public Either<GroupingDefinition, ActionStatus> deleteGrouping(NodeTypeEnum nodeType, String groupingId) { + Either<GroupingDefinition, ActionStatus> result = null; + try { + if (nodeType != NodeTypeEnum.ProductGrouping) { + log.debug("Unknown grouping type {}", nodeType.name()); + result = Either.right(ActionStatus.GENERAL_ERROR); + return result; + } + Either<GroupingData, TitanOperationStatus> groupingDataEither = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), groupingId, GroupingData.class); + if (groupingDataEither.isRight()) { + log.debug("Failed to retrieve grouping for id {}", groupingId); + result = Either.right(ActionStatus.GENERAL_ERROR); + return result; + } + + Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph(); + if (graph.isRight()) { + log.debug(COULDN_T_FETCH_TITAN_GRAPH); + result = Either.right(ActionStatus.GENERAL_ERROR); + return result; + } + + TitanGraph tGraph = graph.left().value(); + + Iterable<TitanVertex> verticesArtifact = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(nodeType), groupingId).vertices(); + Iterator<TitanVertex> iterator = verticesArtifact.iterator(); + if (!iterator.hasNext()) { + log.debug("No grouping node for id {}", groupingId); + result = Either.right(ActionStatus.GENERAL_ERROR); + return result; + } + Vertex artifactV = iterator.next(); + artifactV.remove(); + ; + GroupingDefinition deleted = new GroupingDefinition(groupingDataEither.left().value().getGroupingDataDefinition()); + result = Either.left(deleted); + return result; + } finally { + if (result != null && result.isLeft()) { + titanGenericDao.commit(); + } else { + titanGenericDao.rollback(); + } + } + } + + @Override + public Either<Boolean, ActionStatus> isCategoryUniqueForType(NodeTypeEnum nodeType, String normalizedName) { + + Map<String, Object> properties = new HashMap<>(); + properties.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), normalizedName); + try { + Either<List<CategoryData>, TitanOperationStatus> categoryEither = titanGenericDao.getByCriteria(nodeType, properties, CategoryData.class); + if (categoryEither.isRight() && categoryEither.right().value() != TitanOperationStatus.NOT_FOUND) { + log.debug("Failed to get categories, nodeType {}, normalizedName {}, error {}", nodeType, normalizedName, categoryEither.right().value()); + return Either.right(ActionStatus.GENERAL_ERROR); + } + List<CategoryData> categoryList = (categoryEither.isLeft() ? categoryEither.left().value() : null); + if (categoryList != null && categoryList.size() > 0) { + log.debug("Found category for nodeType {} with normalizedName {}", nodeType, normalizedName); + if (categoryList.size() > 1) { + log.debug("Found more than 1 unique categories for nodeType {} with normalizedName", nodeType, normalizedName); + return Either.right(ActionStatus.GENERAL_ERROR); + } + return Either.left(false); + } else { + log.debug("Category for nodeType {} with normalizedName {} doesn't exist in graph", nodeType, normalizedName); + return Either.left(true); + } + } finally { + titanGenericDao.commit(); + } + } + + @Override + public Either<Boolean, ActionStatus> isSubCategoryUniqueForCategory(NodeTypeEnum nodeType, String subCategoryNormName, String parentCategoryId) { + + String subCategoryId = UniqueIdBuilder.buildSubCategoryUid(parentCategoryId, subCategoryNormName); + try { + Either<SubCategoryData, TitanOperationStatus> subCategoryDataEither = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), subCategoryId, SubCategoryData.class); + if (subCategoryDataEither.isRight() && subCategoryDataEither.right().value() != TitanOperationStatus.NOT_FOUND) { + log.debug("Failed to get sub-category with id {}, error {}", subCategoryId, subCategoryDataEither.right().value()); + return Either.right(ActionStatus.GENERAL_ERROR); + } + SubCategoryData subCategoryData = (subCategoryDataEither.isLeft() ? subCategoryDataEither.left().value() : null); + if (subCategoryData != null) { + log.debug("Found sub-category with id {}", subCategoryId); + return Either.left(false); + } else { + log.debug("Sub-category for id {} doesn't exist in graph", subCategoryId); + return Either.left(true); + } + } finally { + titanGenericDao.commit(); + } + } + + @Override + public Either<Boolean, ActionStatus> isGroupingUniqueForSubCategory(NodeTypeEnum nodeType, String groupingNormName, String parentSubCategoryId) { + + String groupingId = UniqueIdBuilder.buildGroupingUid(parentSubCategoryId, groupingNormName); + try { + Either<GroupingData, TitanOperationStatus> groupingDataEither = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(nodeType), groupingId, GroupingData.class); + if (groupingDataEither.isRight() && groupingDataEither.right().value() != TitanOperationStatus.NOT_FOUND) { + log.debug("Failed to get grouping with id {}, error {}", groupingId, groupingDataEither.right().value()); + return Either.right(ActionStatus.GENERAL_ERROR); + } + GroupingData groupingData = (groupingDataEither.isLeft() ? groupingDataEither.left().value() : null); + if (groupingData != null) { + log.debug("Found grouping with id {}", groupingId); + return Either.left(false); + } else { + log.debug("Grouping for id {} doesn't exist in graph", groupingId); + return Either.left(true); + } + } finally { + titanGenericDao.commit(); + } + } + + @Override + public Either<SubCategoryDefinition, ActionStatus> getSubCategoryUniqueForType(NodeTypeEnum nodeType, String normalizedName) { + Map<String, Object> properties = new HashMap<>(); + properties.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), normalizedName); + try { + Either<List<SubCategoryData>, TitanOperationStatus> subCategoryEither = titanGenericDao.getByCriteria(nodeType, properties, SubCategoryData.class); + if (subCategoryEither.isRight() && subCategoryEither.right().value() != TitanOperationStatus.NOT_FOUND) { + log.debug("Failed to get sub-categories, nodeType {}, normalizedName {}, error {}", nodeType, normalizedName, subCategoryEither.right().value()); + return Either.right(ActionStatus.GENERAL_ERROR); + } + List<SubCategoryData> subCategoryList = (subCategoryEither.isLeft() ? subCategoryEither.left().value() : null); + if (subCategoryList != null && subCategoryList.size() > 0) { + log.debug("Found sub-category for nodeType {} with normalizedName {}", nodeType, normalizedName); + SubCategoryData subCategoryData = subCategoryList.get(0); + SubCategoryDefinition subCategoryDefinition = new SubCategoryDefinition(subCategoryData.getSubCategoryDataDefinition()); + return Either.left(subCategoryDefinition); + } else { + log.debug("Sub-category for nodeType {} with normalizedName {} doesn't exist in graph", nodeType, normalizedName); + return Either.left(null); + } + } finally { + titanGenericDao.commit(); + } + } + + @Override + public Either<GroupingDefinition, ActionStatus> getGroupingUniqueForType(NodeTypeEnum nodeType, String groupingNormalizedName) { + Map<String, Object> properties = new HashMap<>(); + properties.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), groupingNormalizedName); + try { + Either<List<GroupingData>, TitanOperationStatus> groupingEither = titanGenericDao.getByCriteria(nodeType, properties, GroupingData.class); + if (groupingEither.isRight() && groupingEither.right().value() != TitanOperationStatus.NOT_FOUND) { + log.debug("Failed to get grouping, nodeType {}, normalizedName {}, error {}", nodeType, groupingNormalizedName, groupingEither.right().value()); + return Either.right(ActionStatus.GENERAL_ERROR); + } + List<GroupingData> groupingList = (groupingEither.isLeft() ? groupingEither.left().value() : null); + if (groupingList != null && groupingList.size() > 0) { + log.debug("Found grouping for nodeType {} with normalizedName {}", nodeType, groupingNormalizedName); + GroupingData groupingData = groupingList.get(0); + GroupingDefinition groupingDefinition = new GroupingDefinition(groupingData.getGroupingDataDefinition()); + return Either.left(groupingDefinition); + } else { + log.debug("Grouping for nodeType {} with normalizedName {} doesn't exist in graph", nodeType, groupingNormalizedName); + return Either.left(null); + } + } finally { + titanGenericDao.commit(); + } + } + + /* + * + */ + + @Override + public Either<List<Tag>, ActionStatus> getAllTags() { + try { + Either<List<TagData>, TitanOperationStatus> either = titanGenericDao.getAll(NodeTypeEnum.Tag, TagData.class); + if (either.isRight()) { + log.debug("Problem while get all tags. reason - {}", either.right().value()); + return Either.right(ActionStatus.GENERAL_ERROR); + } + List<TagData> tagDataList = either.left().value(); + List<Tag> tagList = convertToListOfTag(tagDataList); + return Either.left(tagList); + } finally { + titanGenericDao.commit(); + } + } + + @Override + public <T extends GraphNode> Either<org.openecomp.sdc.be.resources.data.CategoryData, StorageOperationStatus> getCategoryData(String name, NodeTypeEnum type, Class<T> clazz) { + if (name != null) { + String categoryUid = null; + if (type == NodeTypeEnum.ResourceCategory) { + String[] categoryFields = name.split("/"); + if (categoryFields.length != 2) { + return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND); + } + categoryUid = UniqueIdBuilder.buildResourceCategoryUid(categoryFields[0], categoryFields[1], type); + } else { + categoryUid = UniqueIdBuilder.buildServiceCategoryUid(name, type); + } + Either<T, TitanOperationStatus> either = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(type), categoryUid, clazz); + + if (either.isRight()) { + TitanOperationStatus titanOperationStatus = either.right().value(); + log.debug("Problem while geting category with id {}. reason - {}", categoryUid, titanOperationStatus.name()); + if (titanOperationStatus == TitanOperationStatus.NOT_FOUND) { + return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND); + } else { + return Either.right(StorageOperationStatus.GENERAL_ERROR); + } + } + return Either.left((org.openecomp.sdc.be.resources.data.CategoryData) either.left().value()); + } else { + return Either.right(StorageOperationStatus.GENERAL_ERROR); + } + } + + private List<Tag> convertToListOfTag(List<TagData> tagDataList) { + List<Tag> tagList = new ArrayList<>(); + for (TagData elem : tagDataList) { + Tag tag = new Tag(); + tag.setName(elem.getName()); + tagList.add(tag); + } + return tagList; + } + + @Override + public Either<List<PropertyScope>, ActionStatus> getAllPropertyScopes() { + // Mock + List<PropertyScope> propertyScopes = new ArrayList<>(); + PropertyScope propertyScope1 = new PropertyScope(); + propertyScope1.setName("A&AI"); + PropertyScope propertyScope2 = new PropertyScope(); + propertyScope2.setName("Order"); + PropertyScope propertyScope3 = new PropertyScope(); + propertyScope3.setName("Runtime"); + propertyScopes.add(propertyScope1); + propertyScopes.add(propertyScope2); + propertyScopes.add(propertyScope3); + return Either.left(propertyScopes); + } + + @Override + public Either<List<ArtifactType>, ActionStatus> getAllArtifactTypes() { + List<ArtifactType> artifactTypes = new ArrayList<>(); + + List<String> artifactTypesList = ConfigurationManager.getConfigurationManager().getConfiguration().getArtifactTypes(); + for (String artifactType : artifactTypesList) { + ArtifactType artifactT = new ArtifactType(); + artifactT.setName(artifactType); + artifactTypes.add(artifactT); + } + return Either.left(artifactTypes); + } + + @Override + public Either<Map<String, Object>, ActionStatus> getAllDeploymentArtifactTypes() { + + Map<String, Object> artifactTypes = new HashMap<>(); + Map<String, ArtifactTypeConfig> artifactResourceTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts(); + Map<String, ArtifactTypeConfig> artifactServiceTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts(); + Map<String, ArtifactTypeConfig> artifactResourceInstanceTypes = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts(); + + artifactTypes.put("resourceDeploymentArtifacts", artifactResourceTypes); + artifactTypes.put("serviceDeploymentArtifacts", artifactServiceTypes); + artifactTypes.put("resourceInstanceDeploymentArtifacts", artifactResourceInstanceTypes); + + return Either.left(artifactTypes); + + } + + @Override + public Either<Integer, ActionStatus> getDefaultHeatTimeout() { + return Either.left(ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes()); + } + + @Override + public Either<Map<String, String>, ActionStatus> getResourceTypesMap() { + ResourceTypeEnum[] enumConstants = ResourceTypeEnum.class.getEnumConstants(); + Map<String, String> resourceTypes = new HashMap<>(); + if (enumConstants != null) { + for (int i = 0; i < enumConstants.length; ++i) { + resourceTypes.put(enumConstants[i].name(), enumConstants[i].getValue()); + } + + } + return Either.left(resourceTypes); + } + + @Override + public <T extends GraphNode> Either<CategoryData, StorageOperationStatus> getNewCategoryData(String name, NodeTypeEnum type, Class<T> clazz) { + if (name != null) { + String categoryUid = UniqueIdBuilder.buildServiceCategoryUid(name, type); + Map props = new HashMap<>(); + props.put(GraphPropertiesDictionary.NORMALIZED_NAME.getProperty(), ValidationUtils.normalizeCategoryName4Uniqueness(name)); + Either<List<T>, TitanOperationStatus> either = titanGenericDao.getByCriteria(type, props, clazz); + + if (either.isRight()) { + TitanOperationStatus titanOperationStatus = either.right().value(); + log.debug("Problem while geting category with id {}. reason - {}", categoryUid, titanOperationStatus.name()); + if (titanOperationStatus == TitanOperationStatus.NOT_FOUND) { + return Either.right(StorageOperationStatus.CATEGORY_NOT_FOUND); + } else { + return Either.right(StorageOperationStatus.GENERAL_ERROR); + } + } + return Either.left((CategoryData) either.left().value().get(0)); + } else { + return Either.right(StorageOperationStatus.GENERAL_ERROR); + } + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GraphLockOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GraphLockOperation.java index e5a743af8f..b87da5ad9a 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GraphLockOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GraphLockOperation.java @@ -25,74 +25,71 @@ import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.stereotype.Component; @Component("graph-lock-operation") public class GraphLockOperation implements IGraphLockOperation { - private static Logger log = LoggerFactory.getLogger(GraphLockOperation.class.getName()); - - @javax.annotation.Resource - private TitanGenericDao titanGenericDao; - - public GraphLockOperation() { - super(); - } - - /* - * (non-Javadoc) - * - * @see org.openecomp.sdc.be.model.operations.impl.IGraphLockOperation# lockResource(java.lang.String, org.openecomp.sdc.be.model.operations.api.IResourceOperation) - */ - @Override - public StorageOperationStatus lockComponent(String componentId, NodeTypeEnum nodeType) { - log.info("lock resource with id {}", componentId); - TitanOperationStatus lockElementStatus = null; - try { - lockElementStatus = titanGenericDao.lockElement(componentId, nodeType); - } catch (Exception e) { - lockElementStatus = TitanOperationStatus.ALREADY_LOCKED; - - } - - return DaoStatusConverter.convertTitanStatusToStorageStatus(lockElementStatus); - - } - - /* - * (non-Javadoc) - * - * @see org.openecomp.sdc.be.model.operations.impl.IGraphLockOperation# unlockResource(java.lang.String, org.openecomp.sdc.be.model.operations.api.IResourceOperation) - */ - @Override - public StorageOperationStatus unlockComponent(String componentId, NodeTypeEnum nodeType) { - - TitanOperationStatus lockElementStatus = titanGenericDao.releaseElement(componentId, nodeType); - - return DaoStatusConverter.convertTitanStatusToStorageStatus(lockElementStatus); - } - - @Override - public StorageOperationStatus unlockComponentByName(String name, String componentId, NodeTypeEnum nodeType) { - TitanOperationStatus lockElementStatus = titanGenericDao.releaseElement(name, nodeType); - return DaoStatusConverter.convertTitanStatusToStorageStatus(lockElementStatus); - } - - @Override - public StorageOperationStatus lockComponentByName(String name, NodeTypeEnum nodeType) { - log.info("lock resource with name {}", name); - TitanOperationStatus lockElementStatus = null; - try { - - lockElementStatus = titanGenericDao.lockElement(name, nodeType); - - } catch (Exception e) { - lockElementStatus = TitanOperationStatus.ALREADY_LOCKED; - - } - - return DaoStatusConverter.convertTitanStatusToStorageStatus(lockElementStatus); - - } + private static final Logger log = Logger.getLogger(GraphLockOperation.class.getName()); + + @javax.annotation.Resource + private TitanGenericDao titanGenericDao; + + public GraphLockOperation() { + super(); + } + + /* + * (non-Javadoc) + * + * @see org.openecomp.sdc.be.model.operations.impl.IGraphLockOperation# lockResource(java.lang.String, org.openecomp.sdc.be.model.operations.api.IResourceOperation) + */ + @Override + public StorageOperationStatus lockComponent(String componentId, NodeTypeEnum nodeType) { + log.info("lock resource with id {}", componentId); + TitanOperationStatus lockElementStatus = null; + try { + lockElementStatus = titanGenericDao.lockElement(componentId, nodeType); + } catch (Exception e) { + lockElementStatus = TitanOperationStatus.ALREADY_LOCKED; + + } + + return DaoStatusConverter.convertTitanStatusToStorageStatus(lockElementStatus); + + } + + /* + * (non-Javadoc) + * + * @see org.openecomp.sdc.be.model.operations.impl.IGraphLockOperation# unlockResource(java.lang.String, org.openecomp.sdc.be.model.operations.api.IResourceOperation) + */ + @Override + public StorageOperationStatus unlockComponent(String componentId, NodeTypeEnum nodeType) { + TitanOperationStatus lockElementStatus = titanGenericDao.releaseElement(componentId, nodeType); + return DaoStatusConverter.convertTitanStatusToStorageStatus(lockElementStatus); + } + + @Override + public StorageOperationStatus unlockComponentByName(String name, String componentId, NodeTypeEnum nodeType) { + TitanOperationStatus lockElementStatus = titanGenericDao.releaseElement(name, nodeType); + return DaoStatusConverter.convertTitanStatusToStorageStatus(lockElementStatus); + } + + @Override + public StorageOperationStatus lockComponentByName(String name, NodeTypeEnum nodeType) { + log.info("lock resource with name {}", name); + TitanOperationStatus lockElementStatus = null; + try { + + lockElementStatus = titanGenericDao.lockElement(name, nodeType); + + } catch (Exception e) { + lockElementStatus = TitanOperationStatus.ALREADY_LOCKED; + + } + + return DaoStatusConverter.convertTitanStatusToStorageStatus(lockElementStatus); + + } } 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 0b13fe1962..4c86af45e5 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 @@ -20,19 +20,12 @@ package org.openecomp.sdc.be.model.operations.impl; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.function.Supplier; -import java.util.stream.Collectors; - +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.TitanVertex; +import fj.data.Either; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.apache.tinkerpop.gremlin.structure.VertexProperty; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; @@ -40,772 +33,719 @@ import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation; import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; -import org.openecomp.sdc.be.dao.titan.TitanGenericDao; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.GroupDefinition; -import org.openecomp.sdc.be.model.GroupInstance; -import org.openecomp.sdc.be.model.GroupInstanceProperty; -import org.openecomp.sdc.be.model.GroupProperty; -import org.openecomp.sdc.be.model.IComponentInstanceConnectedElement; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; -import org.openecomp.sdc.be.resources.data.ArtifactData; -import org.openecomp.sdc.be.resources.data.GroupInstanceData; -import org.openecomp.sdc.be.resources.data.PropertyData; -import org.openecomp.sdc.be.resources.data.PropertyValueData; -import org.openecomp.sdc.be.resources.data.UniqueIdData; +import org.openecomp.sdc.be.resources.data.*; import org.openecomp.sdc.common.datastructure.Wrapper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.beans.factory.annotation.Autowired; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanVertex; - -import fj.data.Either; +import java.util.*; +import java.util.function.Supplier; +import java.util.stream.Collectors; @org.springframework.stereotype.Component("group-instance-operation") public class GroupInstanceOperation extends AbstractOperation implements IGroupInstanceOperation { - private static Logger log = LoggerFactory.getLogger(GroupInstanceOperation.class.getName()); - - @Autowired - TitanGenericDao titanGenericDao; - @Autowired - GroupOperation groupOperation; - - @Autowired - PropertyOperation propertyOperation; - - @javax.annotation.Resource - private ApplicationDataTypeCache dataTypeCache; - - - @Override - public Either<List<GroupInstance>, StorageOperationStatus> getAllGroupInstances(String parentId, NodeTypeEnum parentType) { - Either<List<GroupInstance>, StorageOperationStatus> result = null; - List<GroupInstance> groupInstanceRes = new ArrayList<>(); - - Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph(); - if (graph.isRight()) { - log.debug("Failed to work with graph {}", graph.right().value()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value())); - } - TitanGraph tGraph = graph.left().value(); - @SuppressWarnings("unchecked") - Iterable<TitanVertex> vertices = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(parentType), parentId).vertices(); - if (vertices == null || vertices.iterator() == null || false == vertices.iterator().hasNext()) { - log.debug("No nodes for type {} for id = {}", parentType, parentId); - result = Either.right(StorageOperationStatus.NOT_FOUND); - return result; - } - - Iterator<TitanVertex> iterator = vertices.iterator(); - Vertex vertex = iterator.next(); - - Map<String, Object> edgeProperties = null; - - Either<List<ImmutablePair<GroupInstanceData, GraphEdge>>, TitanOperationStatus> childrenByEdgeCriteria = titanGenericDao.getChildrenByEdgeCriteria(vertex, parentId, GraphEdgeLabels.GROUP_INST, NodeTypeEnum.GroupInstance, - GroupInstanceData.class, edgeProperties); - - if (childrenByEdgeCriteria.isRight()) { - TitanOperationStatus status = childrenByEdgeCriteria.right().value(); - log.debug("Failed to find group instance {} on graph", childrenByEdgeCriteria.right().value()); - - if (status == TitanOperationStatus.NOT_FOUND) { - result = Either.left(groupInstanceRes); - return result; - } - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - - } - - List<ImmutablePair<GroupInstanceData, GraphEdge>> list = childrenByEdgeCriteria.left().value(); - - for (ImmutablePair<GroupInstanceData, GraphEdge> pair : list) { - GroupInstanceData groupInstData = pair.getLeft(); - GroupInstance groupInstance = new GroupInstance(groupInstData.getGroupDataDefinition()); - String instOriginGroupId = groupInstance.getGroupUid(); - Either<GroupDefinition, TitanOperationStatus> groupRes = groupOperation.getGroupFromGraph(instOriginGroupId, false, true, false); - - if (groupRes.isRight()) { - TitanOperationStatus status = groupRes.right().value(); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - - } - GroupDefinition groupDefinition = groupRes.left().value(); - Either<Map<String, PropertyValueData>, TitanOperationStatus> groupInstancePropertyValuesRes = getAllGroupInstancePropertyValuesData(groupInstData); - if(groupInstancePropertyValuesRes.isRight()){ - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(groupInstancePropertyValuesRes.right().value())); - } - buildGroupInstanceFromGroup(groupInstance, groupDefinition, groupInstancePropertyValuesRes.left().value()); - /* - * Either<List<GroupProperty>, TitanOperationStatus> groupInsPropStatus = getGroupInstanceProperties(groupInstance, groupDefinition); if (groupInsPropStatus.isRight()) { - * - * return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(groupInsPropStatus.right().value())); } - */ - - Either<List<ImmutablePair<String, String>>, TitanOperationStatus> artifactsRes = getGroupArtifactsPairs(groupInstance.getUniqueId()); - if (artifactsRes.isRight()) { - TitanOperationStatus status = artifactsRes.right().value(); - if (status != TitanOperationStatus.OK) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - return result; - } - } else { - List<String> artifactsUid = new ArrayList<>(); - List<String> artifactsUUID = new ArrayList<>(); - - List<ImmutablePair<String, String>> list1 = artifactsRes.left().value(); - if (list != null) { - for (ImmutablePair<String, String> pair1 : list1) { - String uid = pair1.left; - String UUID = pair1.right; - artifactsUid.add(uid); - artifactsUUID.add(UUID); - } - groupInstance.setGroupInstanceArtifacts(artifactsUid); - groupInstance.setGroupInstanceArtifactsUuid(artifactsUUID); - } - } - - groupInstanceRes.add(groupInstance); - log.debug("GroupInstance {} was added to list ", groupInstance.getUniqueId()); - } - - result = Either.left(groupInstanceRes); - return result; - - } - - @Override - public Either<Integer, StorageOperationStatus> increaseAndGetGroupInstancePropertyCounter(String groupInstanceId) { - Either<Integer, StorageOperationStatus> result = null; - - Either<TitanGraph, TitanOperationStatus> graphResult = titanGenericDao.getGraph(); - if (graphResult.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value())); - return result; - } - Either<TitanVertex, TitanOperationStatus> vertexService = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupInstance), groupInstanceId); - if (vertexService.isRight()) { - log.debug("failed to fetch vertex of resource instance for id = {}", groupInstanceId); - TitanOperationStatus status = vertexService.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexService.right().value())); - return result; - } - Vertex vertex = vertexService.left().value(); - - VertexProperty<Object> vertexProperty = vertex.property(GraphPropertiesDictionary.PROPERTY_COUNTER.getProperty()); - Integer counter = 0; - if (vertexProperty.isPresent()) { - if (vertexProperty.value() != null) { - counter = (Integer) vertexProperty.value(); - } - } - - counter++; - vertex.property(GraphPropertiesDictionary.PROPERTY_COUNTER.getProperty(), counter); - - result = Either.left(counter); - return result; - - } - - @Override - public Either<ComponentInstanceProperty, StorageOperationStatus> addPropertyValueToGroupInstance(ComponentInstanceProperty groupInstanceProperty, String groupInstanceId, Integer index, boolean inTransaction) { - /// #RULES SUPPORT - /// Ignore rules received from client till support - groupInstanceProperty.setRules(null); - /// - /// - - Either<ComponentInstanceProperty, StorageOperationStatus> result = null; - - try { - - Either<PropertyValueData, TitanOperationStatus> eitherStatus = addPropertyToGroupInstance(groupInstanceProperty, groupInstanceId, index); - - if (eitherStatus.isRight()) { - log.error("Failed to add property value {} to resource instance {} in Graph. status is {}", groupInstanceProperty, groupInstanceId, eitherStatus.right().value().name()); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherStatus.right().value())); - return result; - } else { - PropertyValueData propertyValueData = eitherStatus.left().value(); - - ComponentInstanceProperty propertyValueResult = propertyOperation.buildResourceInstanceProperty(propertyValueData, groupInstanceProperty); - log.debug("The returned GroupInstanceProperty is {}", propertyValueResult); - - Either<String, TitanOperationStatus> findDefaultValue = propertyOperation.findDefaultValueFromSecondPosition(groupInstanceProperty.getPath(), groupInstanceProperty.getUniqueId(), groupInstanceProperty.getDefaultValue()); - if (findDefaultValue.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(findDefaultValue.right().value())); - return result; - } - String defaultValue = findDefaultValue.left().value(); - propertyValueResult.setDefaultValue(defaultValue); - log.debug("The returned default value in ResourceInstanceProperty is {}", defaultValue); - - result = Either.left(propertyValueResult); - return result; - } - } - - finally { - if (false == inTransaction) { - if (result == null || result.isRight()) { - log.error("Going to execute rollback on graph."); - titanGenericDao.rollback(); - } else { - log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } - - } - - @Override - public Either<ComponentInstanceProperty, StorageOperationStatus> updatePropertyValueInGroupInstance(ComponentInstanceProperty gropuInstanceProperty, String groupInstanceId, boolean inTransaction) { - // TODO Auto-generated method stub - // change Propety class - return null; - } - - public void generateCustomizationUUID(GroupInstance groupInstance) { - UUID uuid = UUID.randomUUID(); - groupInstance.setCustomizationUUID(uuid.toString()); - } - - /** - * add property to resource instance - * - * @param index - * @return - */ - public Either<PropertyValueData, TitanOperationStatus> addPropertyToGroupInstance(ComponentInstanceProperty groupInstanceProperty, String groupInstanceId, Integer index) { - - Either<GroupInstanceData, TitanOperationStatus> findResInstanceRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupInstance), groupInstanceId, GroupInstanceData.class); - - if (findResInstanceRes.isRight()) { - TitanOperationStatus status = findResInstanceRes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - return Either.right(status); - } - - String propertyId = groupInstanceProperty.getUniqueId(); - Either<PropertyData, TitanOperationStatus> findPropertyDefRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), propertyId, PropertyData.class); - - if (findPropertyDefRes.isRight()) { - TitanOperationStatus status = findPropertyDefRes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - return Either.right(status); - } - - String valueUniqueUid = groupInstanceProperty.getValueUniqueUid(); - if (valueUniqueUid == null) { - - PropertyData propertyData = findPropertyDefRes.left().value(); - GroupInstanceData resourceInstanceData = findResInstanceRes.left().value(); - - ImmutablePair<TitanOperationStatus, String> isPropertyValueExists = propertyOperation.findPropertyValue(groupInstanceId, propertyId); - if (isPropertyValueExists.getLeft() == TitanOperationStatus.ALREADY_EXIST) { - log.debug("The property {} already added to the resource instance {}", propertyId, groupInstanceId); - groupInstanceProperty.setValueUniqueUid(isPropertyValueExists.getRight()); - Either<PropertyValueData, TitanOperationStatus> updatePropertyOfResourceInstance = updatePropertyOfGroupInstance(groupInstanceProperty, groupInstanceId); - if (updatePropertyOfResourceInstance.isRight()) { - BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + updatePropertyOfResourceInstance.right().value(), ErrorSeverity.ERROR); - return Either.right(updatePropertyOfResourceInstance.right().value()); - } - return Either.left(updatePropertyOfResourceInstance.left().value()); - } - - if (isPropertyValueExists.getLeft() != TitanOperationStatus.NOT_FOUND) { - log.debug("After finding property value of {} on componenet instance {}", propertyId, groupInstanceId); - return Either.right(isPropertyValueExists.getLeft()); - } - - String innerType = null; - - PropertyDataDefinition propDataDef = propertyData.getPropertyDataDefinition(); - String propertyType = propDataDef.getType(); - String value = groupInstanceProperty.getValue(); - ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); - - if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { - SchemaDefinition def = propDataDef.getSchema(); - if (def == null) { - log.debug("Schema doesn't exists for property of type {}", type); - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); - } - PropertyDataDefinition propDef = def.getProperty(); - if (propDef == null) { - log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); - } - innerType = propDef.getType(); - } - - log.debug("Before validateAndUpdatePropertyValue"); - Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); - if (allDataTypes.isRight()) { - TitanOperationStatus status = allDataTypes.right().value(); - BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); - return Either.right(status); - } - Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes.left().value()); - log.debug("After validateAndUpdatePropertyValue. isValid = {}", isValid); - - String newValue = value; - if (isValid.isRight()) { - Boolean res = isValid.right().value(); - if (res == false) { - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); - } - } else { - Object object = isValid.left().value(); - if (object != null) { - newValue = object.toString(); - } - } - - String uniqueId = UniqueIdBuilder.buildResourceInstancePropertyValueUid(resourceInstanceData.getUniqueId(), index); - PropertyValueData propertyValueData = new PropertyValueData(); - propertyValueData.setUniqueId(uniqueId); - propertyValueData.setValue(newValue); - - log.debug("Before validateAndUpdateRules"); - ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, groupInstanceProperty.getRules(), innerType, allDataTypes.left().value(), false); - log.debug("After validateAndUpdateRules. pair = {}", pair); - if (pair.getRight() != null && pair.getRight() == false) { - BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), groupInstanceProperty.getName(), propertyType); - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); - } - propertyOperation.addRulesToNewPropertyValue(propertyValueData, groupInstanceProperty, groupInstanceId); - - log.debug("Before adding property value to graph {}", propertyValueData); - Either<PropertyValueData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(propertyValueData, PropertyValueData.class); - log.debug("After adding property value to graph {}", propertyValueData); - - if (createNodeResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); - return Either.right(operationStatus); - } - propertyValueData = createNodeResult.left().value(); - - Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(propertyValueData, propertyData, GraphEdgeLabels.PROPERTY_IMPL, null); - - if (createRelResult.isRight()) { - TitanOperationStatus operationStatus = createRelResult.right().value(); - log.error("Failed to associate property value {} to property {} in graph. status is {}", uniqueId, propertyId, operationStatus); - return Either.right(operationStatus); - } - - createRelResult = titanGenericDao.createRelation(resourceInstanceData, propertyValueData, GraphEdgeLabels.PROPERTY_VALUE, null); - - if (createRelResult.isRight()) { - TitanOperationStatus operationStatus = createRelResult.right().value(); - log.error("Failed to associate resource instance {} property value {} in graph. status is {}", groupInstanceId, uniqueId, operationStatus); - return Either.right(operationStatus); - } - - return Either.left(propertyValueData); - } else { - log.error("property value already exists."); - return Either.right(TitanOperationStatus.ALREADY_EXIST); - } - - } - - /** - * update value of attribute on resource instance - * - * @return - */ - public Either<PropertyValueData, TitanOperationStatus> updatePropertyOfGroupInstance(ComponentInstanceProperty groupInstanceProerty, String groupInstanceId) { - - Wrapper<TitanOperationStatus> errorWrapper = new Wrapper<>(); - UpdateDataContainer<PropertyData, PropertyValueData> updateDataContainer = new UpdateDataContainer<>(GraphEdgeLabels.PROPERTY_IMPL, (() -> PropertyData.class), (() -> PropertyValueData.class), NodeTypeEnum.Property, - NodeTypeEnum.PropertyValue); - - preUpdateElementOfResourceInstanceValidations(updateDataContainer, groupInstanceProerty, groupInstanceId, errorWrapper); - if (!errorWrapper.isEmpty()) { - return Either.right(errorWrapper.getInnerElement()); - } - - else { - String value = groupInstanceProerty.getValue(); - // Specific Validation Logic - PropertyData propertyData = updateDataContainer.getDataWrapper().getInnerElement(); - - String innerType = null; - - PropertyDataDefinition propDataDef = propertyData.getPropertyDataDefinition(); - String propertyType = propDataDef.getType(); - ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); - log.debug("The type of the property {} is {}", propertyData.getUniqueId(), propertyType); - - if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { - SchemaDefinition def = propDataDef.getSchema(); - if (def == null) { - log.debug("Schema doesn't exists for property of type {}", type); - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); - } - PropertyDataDefinition propDef = def.getProperty(); - if (propDef == null) { - log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); - } - innerType = propDef.getType(); - } - // Specific Update Logic - Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); - if (allDataTypes.isRight()) { - TitanOperationStatus status = allDataTypes.right().value(); - BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); - return Either.right(status); - } - Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes.left().value()); - - String newValue = value; - if (isValid.isRight()) { - Boolean res = isValid.right().value(); - if (res == false) { - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); - } - } else { - Object object = isValid.left().value(); - if (object != null) { - newValue = object.toString(); - } - } - PropertyValueData propertyValueData = updateDataContainer.getValueDataWrapper().getInnerElement(); - log.debug("Going to update property value from {} to {}", propertyValueData.getValue(), newValue); - propertyValueData.setValue(newValue); - - ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, groupInstanceProerty.getRules(), innerType, allDataTypes.left().value(), true); - if (pair.getRight() != null && pair.getRight() == false) { - BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), groupInstanceProerty.getName(), propertyType); - return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); - } - propertyOperation.updateRulesInPropertyValue(propertyValueData, groupInstanceProerty, groupInstanceId); - - Either<PropertyValueData, TitanOperationStatus> updateRes = titanGenericDao.updateNode(propertyValueData, PropertyValueData.class); - if (updateRes.isRight()) { - TitanOperationStatus status = updateRes.right().value(); - return Either.right(status); - } else { - return Either.left(updateRes.left().value()); - } - } - - } - - private static final class UpdateDataContainer<SomeData, SomeValueData> { - final Wrapper<SomeValueData> valueDataWrapper; - final Wrapper<SomeData> dataWrapper; - final GraphEdgeLabels graphEdge; - final Supplier<Class<SomeData>> someDataClassGen; - final Supplier<Class<SomeValueData>> someValueDataClassGen; - final NodeTypeEnum nodeType; - final NodeTypeEnum nodeTypeValue; - - private UpdateDataContainer(GraphEdgeLabels graphEdge, Supplier<Class<SomeData>> someDataClassGen, Supplier<Class<SomeValueData>> someValueDataClassGen, NodeTypeEnum nodeType, NodeTypeEnum nodeTypeValue) { - super(); - this.valueDataWrapper = new Wrapper<>(); - this.dataWrapper = new Wrapper<>(); - this.graphEdge = graphEdge; - this.someDataClassGen = someDataClassGen; - this.someValueDataClassGen = someValueDataClassGen; - this.nodeType = nodeType; - this.nodeTypeValue = nodeTypeValue; - } - - public Wrapper<SomeValueData> getValueDataWrapper() { - return valueDataWrapper; - } - - public Wrapper<SomeData> getDataWrapper() { - return dataWrapper; - } - - public GraphEdgeLabels getGraphEdge() { - return graphEdge; - } - - public Supplier<Class<SomeData>> getSomeDataClassGen() { - return someDataClassGen; - } - - public Supplier<Class<SomeValueData>> getSomeValueDataClassGen() { - return someValueDataClassGen; - } - - public NodeTypeEnum getNodeType() { - return nodeType; - } - - public NodeTypeEnum getNodeTypeValue() { - return nodeTypeValue; - } - } - - private <SomeData extends GraphNode, SomeValueData extends GraphNode> void preUpdateElementOfResourceInstanceValidations(UpdateDataContainer<SomeData, SomeValueData> updateDataContainer, IComponentInstanceConnectedElement resourceInstanceProerty, - String resourceInstanceId, Wrapper<TitanOperationStatus> errorWrapper) { - - if (errorWrapper.isEmpty()) { - // Verify VFC instance Exist - validateGIExist(resourceInstanceId, errorWrapper); - } - - if (errorWrapper.isEmpty()) { - // Example: Verify Property connected to VFC exist - validateElementConnectedToComponentExist(updateDataContainer, resourceInstanceProerty, errorWrapper); - } - - if (errorWrapper.isEmpty()) { - // Example: Verify PropertyValue connected to VFC Instance exist - validateElementConnectedToComponentInstanceExist(updateDataContainer, resourceInstanceProerty, errorWrapper); - } - - if (errorWrapper.isEmpty()) { - // Example: Verify PropertyValue connected Property - validateElementConnectedToInstance(updateDataContainer, resourceInstanceProerty, errorWrapper); - } - } - - private <SomeData extends GraphNode, SomeValueData extends GraphNode> void validateElementConnectedToInstance(UpdateDataContainer<SomeData, SomeValueData> updateDataContainer, IComponentInstanceConnectedElement resourceInstanceProerty, - Wrapper<TitanOperationStatus> errorWrapper) { - Either<ImmutablePair<SomeData, GraphEdge>, TitanOperationStatus> child = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(updateDataContainer.getNodeTypeValue()), resourceInstanceProerty.getValueUniqueUid(), - updateDataContainer.getGraphEdge(), updateDataContainer.getNodeType(), updateDataContainer.getSomeDataClassGen().get()); - - if (child.isRight()) { - TitanOperationStatus status = child.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - errorWrapper.setInnerElement(status); - - } else { - updateDataContainer.getDataWrapper().setInnerElement(child.left().value().left); - } - } - - private <SomeValueData extends GraphNode, SomeData extends GraphNode> void validateElementConnectedToComponentInstanceExist(UpdateDataContainer<SomeData, SomeValueData> updateDataContainer, - IComponentInstanceConnectedElement resourceInstanceProerty, Wrapper<TitanOperationStatus> errorWrapper) { - String valueUniqueUid = resourceInstanceProerty.getValueUniqueUid(); - if (valueUniqueUid == null) { - errorWrapper.setInnerElement(TitanOperationStatus.INVALID_ID); - } else { - Either<SomeValueData, TitanOperationStatus> findPropertyValueRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(updateDataContainer.getNodeTypeValue()), valueUniqueUid, updateDataContainer.getSomeValueDataClassGen().get()); - if (findPropertyValueRes.isRight()) { - TitanOperationStatus status = findPropertyValueRes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - errorWrapper.setInnerElement(status); - } else { - updateDataContainer.getValueDataWrapper().setInnerElement(findPropertyValueRes.left().value()); - } - } - } - - private <SomeData extends GraphNode, SomeValueData extends GraphNode> void validateElementConnectedToComponentExist(UpdateDataContainer<SomeData, SomeValueData> updateDataContainer, - IComponentInstanceConnectedElement resourceInstanceElementConnected, Wrapper<TitanOperationStatus> errorWrapper) { - String uniqueId = resourceInstanceElementConnected.getUniqueId(); - Either<SomeData, TitanOperationStatus> findPropertyDefRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(updateDataContainer.getNodeType()), uniqueId, updateDataContainer.getSomeDataClassGen().get()); - - if (findPropertyDefRes.isRight()) { - TitanOperationStatus status = findPropertyDefRes.right().value(); - errorWrapper.setInnerElement(status); - } - } - - private void validateGIExist(String resourceInstanceId, Wrapper<TitanOperationStatus> errorWrapper) { - validateGIExist(resourceInstanceId, null, errorWrapper); - } - - private void validateGIExist(String resourceInstanceId, Wrapper<GroupInstanceData> compInsDataWrapper, Wrapper<TitanOperationStatus> errorWrapper) { - validateElementExistInGraph(resourceInstanceId, NodeTypeEnum.GroupInstance, () -> GroupInstanceData.class, compInsDataWrapper, errorWrapper); - } - - public <ElementData extends GraphNode> void validateElementExistInGraph(String elementUniqueId, NodeTypeEnum elementNodeType, Supplier<Class<ElementData>> elementClassGen, Wrapper<ElementData> elementDataWrapper, - Wrapper<TitanOperationStatus> errorWrapper) { - Either<ElementData, TitanOperationStatus> findResInstanceRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(elementNodeType), elementUniqueId, elementClassGen.get()); - if (findResInstanceRes.isRight()) { - TitanOperationStatus status = findResInstanceRes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - errorWrapper.setInnerElement(status); - } else { - if (elementDataWrapper != null) { - elementDataWrapper.setInnerElement(findResInstanceRes.left().value()); - } - } - } - - private void buildGroupInstanceFromGroup(GroupInstance groupInstance, GroupDefinition groupDefinition, Map<String, PropertyValueData> groupInstancePropertyValues) { - - groupInstance.setGroupName(groupDefinition.getName()); - groupInstance.setInvariantUUID(groupDefinition.getInvariantUUID()); - groupInstance.setDescription(groupDefinition.getDescription()); - groupInstance.setVersion(groupDefinition.getVersion()); - groupInstance.setArtifacts(groupDefinition.getArtifacts()); - groupInstance.setArtifactsUuid(groupDefinition.getArtifactsUuid()); - groupInstance.setType(groupDefinition.getType()); - groupInstance.setGroupUUID(groupDefinition.getGroupUUID()); - - List<GroupInstanceProperty> groupInstanceProperties = groupDefinition.convertToGroupProperties() - //converts List of GroupProperties to List of GroupInstanceProperties and updates it with group instance property data - .stream().map(p -> getUpdatedConvertedProperty(p, groupInstancePropertyValues)).collect(Collectors.toList()); - groupInstance.convertFromGroupInstancesProperties(groupInstanceProperties); - } - - private GroupInstanceProperty getUpdatedConvertedProperty(GroupProperty groupProperty, Map<String, PropertyValueData> groupInstancePropertyValues){ - - GroupInstanceProperty updatedProperty = new GroupInstanceProperty(groupProperty, groupProperty.getValue()); - if(!MapUtils.isEmpty(groupInstancePropertyValues) && groupInstancePropertyValues.containsKey(groupProperty.getName())){ - PropertyValueData groupInstancePropertyValue = groupInstancePropertyValues.get(groupProperty.getName()); - updatedProperty.setValue(groupInstancePropertyValue.getValue()); - updatedProperty.setValueUniqueUid(groupInstancePropertyValue.getUniqueId()); - } - return updatedProperty; - } - - private Either<List<ImmutablePair<String, String>>, TitanOperationStatus> getGroupArtifactsPairs(String groupUniqueId) { - - Either<List<ImmutablePair<String, String>>, TitanOperationStatus> result = null; - - Either<List<ImmutablePair<ArtifactData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupInstance), groupUniqueId, GraphEdgeLabels.GROUP_ARTIFACT_REF, - NodeTypeEnum.ArtifactRef, ArtifactData.class); - if (childrenNodes.isRight()) { - TitanOperationStatus status = childrenNodes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.OK; - } - result = Either.right(status); - - } else { - - List<ImmutablePair<String, String>> artifactsList = new ArrayList<>(); - List<ImmutablePair<ArtifactData, GraphEdge>> list = childrenNodes.left().value(); - if (list != null) { - for (ImmutablePair<ArtifactData, GraphEdge> pair : list) { - ArtifactData artifactData = pair.getKey(); - String uniqueId = artifactData.getArtifactDataDefinition().getUniqueId(); - String UUID = artifactData.getArtifactDataDefinition().getArtifactUUID(); - ImmutablePair<String, String> artifact = new ImmutablePair<String, String>(uniqueId, UUID); - artifactsList.add(artifact); - } - } - - log.debug("The artifacts list related to group {} is {}",groupUniqueId,artifactsList); - result = Either.left(artifactsList); - } - - return result; - - } - - @Override - public StorageOperationStatus dissociateAndAssociateGroupsInstanceFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact) { - - return this.dissociateAndAssociateGroupsInstanceFromArtifactOnGraph(componentId, componentTypeEnum, oldArtifactId, newArtifact); - - } - - private StorageOperationStatus dissociateAndAssociateGroupsInstanceFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact) { - - Either<List<GroupInstance>, StorageOperationStatus> allGroupsFromGraph = getAllGroupInstances(componentId, componentTypeEnum); - if (allGroupsFromGraph.isRight()) { - StorageOperationStatus status = allGroupsFromGraph.right().value(); - return status; - } - - List<GroupInstance> allGroups = allGroupsFromGraph.left().value(); - if (allGroups == null || allGroups.isEmpty()) { - return StorageOperationStatus.OK; - } - - // Find all groups which contains this artifact id - List<GroupInstance> associatedGroups = allGroups.stream().filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts().contains(oldArtifactId)).collect(Collectors.toList()); - - if (associatedGroups != null && false == associatedGroups.isEmpty()) { - - log.debug("The groups {} contains the artifact {}",associatedGroups.stream().map(p -> p.getName()).collect(Collectors.toList()),oldArtifactId); - - UniqueIdData oldArtifactData = new UniqueIdData(NodeTypeEnum.ArtifactRef, oldArtifactId); - UniqueIdData newArtifactData = new UniqueIdData(NodeTypeEnum.ArtifactRef, newArtifact.getArtifactDataDefinition().getUniqueId()); - Map<String, Object> props = new HashMap<String, Object>(); - props.put(GraphPropertiesDictionary.NAME.getProperty(), newArtifactData.getLabel()); - - for (GroupInstance groupDefinition : associatedGroups) { - UniqueIdData groupData = new UniqueIdData(NodeTypeEnum.GroupInstance, groupDefinition.getUniqueId()); - - Either<GraphRelation, TitanOperationStatus> deleteRelation = titanGenericDao.deleteRelation(groupData, oldArtifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF); - log.trace("After dissociate group {} from artifact {}", groupDefinition.getName(), oldArtifactId); - if (deleteRelation.isRight()) { - TitanOperationStatus status = deleteRelation.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - return DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - - Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(groupData, newArtifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF, props); - log.trace("After associate group {} to artifact {}", groupDefinition.getName(), newArtifact.getUniqueIdKey()); - if (createRelation.isRight()) { - TitanOperationStatus status = createRelation.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - return DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - } - - } - return StorageOperationStatus.OK; - } - - private Either<Map<String, PropertyValueData>, TitanOperationStatus> getAllGroupInstancePropertyValuesData(GroupInstanceData groupInstData) { - - Either<Map<String, PropertyValueData>, TitanOperationStatus> result = null; - try{ - Either<List<ImmutablePair<PropertyValueData, GraphEdge>>, TitanOperationStatus> getPropertyValueChildrenRes = - titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), groupInstData.getUniqueId(), GraphEdgeLabels.PROPERTY_VALUE, - NodeTypeEnum.PropertyValue, PropertyValueData.class, true); - if(getPropertyValueChildrenRes.isRight()){ - TitanOperationStatus status = getPropertyValueChildrenRes.right().value(); - log.debug("Failed to fetch property value nodes for group instance {}. Status is {}. ", groupInstData.getName(), status); - if(status == TitanOperationStatus.NOT_FOUND){ - result = Either.left(null); - }else{ - result = Either.right(status); - } - }else{ - result = Either.left(getPropertyValueChildrenRes.left().value().stream() - .collect(Collectors.toMap(pair->(String)(pair.getRight().getProperties().get(GraphPropertiesDictionary.PROPERTY_NAME.getProperty())), pair->pair.getLeft()))); - } - } catch(Exception e){ - log.debug("The Exception occured during fetch group instance () property values. The message is {}. ", groupInstData.getName(), e.getMessage(), e); - if(result == null){ - result = Either.right(TitanOperationStatus.GENERAL_ERROR); - } - } - return result; - } + private static final String UPDATE_PROPERTY_VALUE_ON_COMPONENT_INSTANCE = "UpdatePropertyValueOnComponentInstance"; + private static final String FAILED_TO_UPDATE_PROPERTY_VALUE_ON_INSTANCE_STATUS_IS = "Failed to update property value on instance. Status is "; + private static final Logger log = Logger.getLogger(GroupInstanceOperation.class.getName()); + + @Autowired + GroupOperation groupOperation; + + @Autowired + PropertyOperation propertyOperation; + + @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<>(); + + Either<TitanGraph, TitanOperationStatus> graph = titanGenericDao.getGraph(); + if (graph.isRight()) { + log.debug("Failed to work with graph {}", graph.right().value()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graph.right().value())); + } + TitanGraph tGraph = graph.left().value(); + @SuppressWarnings("unchecked") + Iterable<TitanVertex> vertices = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(parentType), parentId).vertices(); + if (vertices == null || vertices.iterator() == null || !vertices.iterator().hasNext()) { + log.debug("No nodes for type {} for id = {}", parentType, parentId); + result = Either.right(StorageOperationStatus.NOT_FOUND); + return result; + } + + Iterator<TitanVertex> iterator = vertices.iterator(); + Vertex vertex = iterator.next(); + + Map<String, Object> edgeProperties = null; + + Either<List<ImmutablePair<GroupInstanceData, GraphEdge>>, TitanOperationStatus> childrenByEdgeCriteria = titanGenericDao.getChildrenByEdgeCriteria(vertex, parentId, GraphEdgeLabels.GROUP_INST, NodeTypeEnum.GroupInstance, + GroupInstanceData.class, edgeProperties); + + if (childrenByEdgeCriteria.isRight()) { + TitanOperationStatus status = childrenByEdgeCriteria.right().value(); + log.debug("Failed to find group instance {} on graph", childrenByEdgeCriteria.right().value()); + + if (status == TitanOperationStatus.NOT_FOUND) { + return Either.left(groupInstanceRes); + } + + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + + List<ImmutablePair<GroupInstanceData, GraphEdge>> list = childrenByEdgeCriteria.left().value(); + + for (ImmutablePair<GroupInstanceData, GraphEdge> pair : list) { + GroupInstanceData groupInstData = pair.getLeft(); + GroupInstance groupInstance = new GroupInstance(groupInstData.getGroupDataDefinition()); + String instOriginGroupId = groupInstance.getGroupUid(); + Either<GroupDefinition, StorageOperationStatus> groupRes = groupOperation.getGroupFromGraph(instOriginGroupId, false, true, false); + + if (groupRes.isRight()) { + return Either.right(groupRes.right().value()); + } + + GroupDefinition groupDefinition = groupRes.left().value(); + Either<Map<String, PropertyValueData>, TitanOperationStatus> groupInstancePropertyValuesRes = getAllGroupInstancePropertyValuesData(groupInstData); + if(groupInstancePropertyValuesRes.isRight()){ + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(groupInstancePropertyValuesRes.right().value())); + } + buildGroupInstanceFromGroup(groupInstance, groupDefinition, groupInstancePropertyValuesRes.left().value()); + Either<List<ImmutablePair<String, String>>, TitanOperationStatus> artifactsRes = getGroupArtifactsPairs(groupInstance.getUniqueId()); + if (artifactsRes.isRight()) { + TitanOperationStatus status = artifactsRes.right().value(); + if (status != TitanOperationStatus.OK) { + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + return result; + } + } else { + List<String> artifactsUid = new ArrayList<>(); + List<String> artifactsUUID = new ArrayList<>(); + + List<ImmutablePair<String, String>> list1 = artifactsRes.left().value(); + if (list != null) { + for (ImmutablePair<String, String> pair1 : list1) { + String uid = pair1.left; + String UUID = pair1.right; + artifactsUid.add(uid); + artifactsUUID.add(UUID); + } + groupInstance.setGroupInstanceArtifacts(artifactsUid); + groupInstance.setGroupInstanceArtifactsUuid(artifactsUUID); + } + } + + groupInstanceRes.add(groupInstance); + log.debug("GroupInstance {} was added to list ", groupInstance.getUniqueId()); + } + + result = Either.left(groupInstanceRes); + return result; + + } + + @Override + public Either<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 + groupInstanceProperty.setRules(null); + /// + /// + + Either<ComponentInstanceProperty, StorageOperationStatus> result = null; + + try { + + Either<PropertyValueData, TitanOperationStatus> eitherStatus = addPropertyToGroupInstance(groupInstanceProperty, groupInstanceId, index); + + if (eitherStatus.isRight()) { + log.error("Failed to add property value {} to resource instance {} in Graph. status is {}", groupInstanceProperty, groupInstanceId, eitherStatus.right().value().name()); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherStatus.right().value())); + return result; + } else { + PropertyValueData propertyValueData = eitherStatus.left().value(); + + ComponentInstanceProperty propertyValueResult = propertyOperation.buildResourceInstanceProperty(propertyValueData, groupInstanceProperty); + log.debug("The returned GroupInstanceProperty is {}", propertyValueResult); + + Either<String, TitanOperationStatus> findDefaultValue = propertyOperation.findDefaultValueFromSecondPosition(groupInstanceProperty.getPath(), groupInstanceProperty.getUniqueId(), groupInstanceProperty.getDefaultValue()); + if (findDefaultValue.isRight()) { + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(findDefaultValue.right().value())); + return result; + } + String defaultValue = findDefaultValue.left().value(); + propertyValueResult.setDefaultValue(defaultValue); + log.debug("The returned default value in ResourceInstanceProperty is {}", defaultValue); + + result = Either.left(propertyValueResult); + return result; + } + } + + finally { + if (!inTransaction) { + if (result == null || result.isRight()) { + log.error("Going to execute rollback on graph."); + titanGenericDao.rollback(); + } else { + log.debug("Going to execute commit on graph."); + titanGenericDao.commit(); + } + } + } + + } + + @Override + public Either<ComponentInstanceProperty, StorageOperationStatus> updatePropertyValueInGroupInstance(ComponentInstanceProperty gropuInstanceProperty, String groupInstanceId, boolean inTransaction) { + // TODO Auto-generated method stub + // change Propety class + return null; + } + + public void generateCustomizationUUID(GroupInstance groupInstance) { + UUID uuid = UUID.randomUUID(); + groupInstance.setCustomizationUUID(uuid.toString()); + } + + /** + * add property to resource instance + * + * @param index + * @return + */ + public Either<PropertyValueData, TitanOperationStatus> addPropertyToGroupInstance(ComponentInstanceProperty groupInstanceProperty, String groupInstanceId, Integer index) { + + Either<GroupInstanceData, TitanOperationStatus> findResInstanceRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupInstance), groupInstanceId, GroupInstanceData.class); + + if (findResInstanceRes.isRight()) { + TitanOperationStatus status = findResInstanceRes.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + return Either.right(status); + } + + String propertyId = groupInstanceProperty.getUniqueId(); + Either<PropertyData, TitanOperationStatus> findPropertyDefRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), propertyId, PropertyData.class); + + if (findPropertyDefRes.isRight()) { + TitanOperationStatus status = findPropertyDefRes.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + return Either.right(status); + } + + String valueUniqueUid = groupInstanceProperty.getValueUniqueUid(); + if (valueUniqueUid == null) { + + PropertyData propertyData = findPropertyDefRes.left().value(); + GroupInstanceData resourceInstanceData = findResInstanceRes.left().value(); + + ImmutablePair<TitanOperationStatus, String> isPropertyValueExists = propertyOperation.findPropertyValue(groupInstanceId, propertyId); + if (isPropertyValueExists.getLeft() == TitanOperationStatus.ALREADY_EXIST) { + log.debug("The property {} already added to the resource instance {}", propertyId, groupInstanceId); + groupInstanceProperty.setValueUniqueUid(isPropertyValueExists.getRight()); + Either<PropertyValueData, TitanOperationStatus> updatePropertyOfResourceInstance = updatePropertyOfGroupInstance(groupInstanceProperty, groupInstanceId); + if (updatePropertyOfResourceInstance.isRight()) { + BeEcompErrorManager.getInstance().logInternalFlowError(UPDATE_PROPERTY_VALUE_ON_COMPONENT_INSTANCE, FAILED_TO_UPDATE_PROPERTY_VALUE_ON_INSTANCE_STATUS_IS + updatePropertyOfResourceInstance.right().value(), ErrorSeverity.ERROR); + return Either.right(updatePropertyOfResourceInstance.right().value()); + } + return Either.left(updatePropertyOfResourceInstance.left().value()); + } + + if (isPropertyValueExists.getLeft() != TitanOperationStatus.NOT_FOUND) { + log.debug("After finding property value of {} on componenet instance {}", propertyId, groupInstanceId); + return Either.right(isPropertyValueExists.getLeft()); + } + + String innerType = null; + + PropertyDataDefinition propDataDef = propertyData.getPropertyDataDefinition(); + String propertyType = propDataDef.getType(); + String value = groupInstanceProperty.getValue(); + ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); + + if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { + SchemaDefinition def = propDataDef.getSchema(); + if (def == null) { + log.debug("Schema doesn't exists for property of type {}", type); + return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + } + PropertyDataDefinition propDef = def.getProperty(); + if (propDef == null) { + log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); + return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + } + innerType = propDef.getType(); + } + + log.debug("Before validateAndUpdatePropertyValue"); + Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); + if (allDataTypes.isRight()) { + TitanOperationStatus status = allDataTypes.right().value(); + BeEcompErrorManager.getInstance().logInternalFlowError(UPDATE_PROPERTY_VALUE_ON_COMPONENT_INSTANCE, FAILED_TO_UPDATE_PROPERTY_VALUE_ON_INSTANCE_STATUS_IS + status, ErrorSeverity.ERROR); + return Either.right(status); + } + Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes.left().value()); + log.debug("After validateAndUpdatePropertyValue. isValid = {}", isValid); + + String newValue = value; + if (isValid.isRight()) { + Boolean res = isValid.right().value(); + if (!res) { + return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + } + } else { + Object object = isValid.left().value(); + if (object != null) { + newValue = object.toString(); + } + } + + String uniqueId = UniqueIdBuilder.buildResourceInstancePropertyValueUid(resourceInstanceData.getUniqueId(), index); + PropertyValueData propertyValueData = new PropertyValueData(); + propertyValueData.setUniqueId(uniqueId); + propertyValueData.setValue(newValue); + + log.debug("Before validateAndUpdateRules"); + ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, groupInstanceProperty.getRules(), innerType, allDataTypes.left().value(), false); + log.debug("After validateAndUpdateRules. pair = {}", pair); + if (pair.getRight() != null && !pair.getRight()) { + BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), groupInstanceProperty.getName(), propertyType); + return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + } + propertyOperation.addRulesToNewPropertyValue(propertyValueData, groupInstanceProperty, groupInstanceId); + + log.debug("Before adding property value to graph {}", propertyValueData); + Either<PropertyValueData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(propertyValueData, PropertyValueData.class); + log.debug("After adding property value to graph {}", propertyValueData); + + if (createNodeResult.isRight()) { + TitanOperationStatus operationStatus = createNodeResult.right().value(); + return Either.right(operationStatus); + } + propertyValueData = createNodeResult.left().value(); + + Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(propertyValueData, propertyData, GraphEdgeLabels.PROPERTY_IMPL, null); + + if (createRelResult.isRight()) { + TitanOperationStatus operationStatus = createRelResult.right().value(); + log.error("Failed to associate property value {} to property {} in graph. status is {}", uniqueId, propertyId, operationStatus); + return Either.right(operationStatus); + } + + createRelResult = titanGenericDao.createRelation(resourceInstanceData, propertyValueData, GraphEdgeLabels.PROPERTY_VALUE, null); + + if (createRelResult.isRight()) { + TitanOperationStatus operationStatus = createRelResult.right().value(); + log.error("Failed to associate resource instance {} property value {} in graph. status is {}", groupInstanceId, uniqueId, operationStatus); + return Either.right(operationStatus); + } + + return Either.left(propertyValueData); + } else { + log.error("property value already exists."); + return Either.right(TitanOperationStatus.ALREADY_EXIST); + } + + } + + /** + * update value of attribute on resource instance + * + * @return + */ + public Either<PropertyValueData, TitanOperationStatus> updatePropertyOfGroupInstance(ComponentInstanceProperty groupInstanceProerty, String groupInstanceId) { + + Wrapper<TitanOperationStatus> errorWrapper = new Wrapper<>(); + UpdateDataContainer<PropertyData, PropertyValueData> updateDataContainer = new UpdateDataContainer<>(GraphEdgeLabels.PROPERTY_IMPL, (() -> PropertyData.class), (() -> PropertyValueData.class), NodeTypeEnum.Property, + NodeTypeEnum.PropertyValue); + + preUpdateElementOfResourceInstanceValidations(updateDataContainer, groupInstanceProerty, groupInstanceId, errorWrapper); + if (!errorWrapper.isEmpty()) { + return Either.right(errorWrapper.getInnerElement()); + } + + else { + String value = groupInstanceProerty.getValue(); + // Specific Validation Logic + PropertyData propertyData = updateDataContainer.getDataWrapper().getInnerElement(); + + String innerType = null; + + PropertyDataDefinition propDataDef = propertyData.getPropertyDataDefinition(); + String propertyType = propDataDef.getType(); + ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); + log.debug("The type of the property {} is {}", propertyData.getUniqueId(), propertyType); + + if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) { + SchemaDefinition def = propDataDef.getSchema(); + if (def == null) { + log.debug("Schema doesn't exists for property of type {}", type); + return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + } + PropertyDataDefinition propDef = def.getProperty(); + if (propDef == null) { + log.debug("Property in Schema Definition inside property of type {} doesn't exist", type); + return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + } + innerType = propDef.getType(); + } + // Specific Update Logic + Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); + if (allDataTypes.isRight()) { + TitanOperationStatus status = allDataTypes.right().value(); + BeEcompErrorManager.getInstance().logInternalFlowError(UPDATE_PROPERTY_VALUE_ON_COMPONENT_INSTANCE, FAILED_TO_UPDATE_PROPERTY_VALUE_ON_INSTANCE_STATUS_IS + status, ErrorSeverity.ERROR); + return Either.right(status); + } + Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, value, innerType, allDataTypes.left().value()); + + String newValue = value; + if (isValid.isRight()) { + Boolean res = isValid.right().value(); + if (!res) { + return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + } + } else { + Object object = isValid.left().value(); + if (object != null) { + newValue = object.toString(); + } + } + PropertyValueData propertyValueData = updateDataContainer.getValueDataWrapper().getInnerElement(); + log.debug("Going to update property value from {} to {}", propertyValueData.getValue(), newValue); + propertyValueData.setValue(newValue); + + ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, groupInstanceProerty.getRules(), innerType, allDataTypes.left().value(), true); + if (pair.getRight() != null && !pair.getRight()) { + BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), groupInstanceProerty.getName(), propertyType); + return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); + } + propertyOperation.updateRulesInPropertyValue(propertyValueData, groupInstanceProerty, groupInstanceId); + + Either<PropertyValueData, TitanOperationStatus> updateRes = titanGenericDao.updateNode(propertyValueData, PropertyValueData.class); + if (updateRes.isRight()) { + TitanOperationStatus status = updateRes.right().value(); + return Either.right(status); + } else { + return Either.left(updateRes.left().value()); + } + } + + } + + private static final class UpdateDataContainer<SomeData, SomeValueData> { + final Wrapper<SomeValueData> valueDataWrapper; + final Wrapper<SomeData> dataWrapper; + final GraphEdgeLabels graphEdge; + final Supplier<Class<SomeData>> someDataClassGen; + final Supplier<Class<SomeValueData>> someValueDataClassGen; + final NodeTypeEnum nodeType; + final NodeTypeEnum nodeTypeValue; + + private UpdateDataContainer(GraphEdgeLabels graphEdge, Supplier<Class<SomeData>> someDataClassGen, Supplier<Class<SomeValueData>> someValueDataClassGen, NodeTypeEnum nodeType, NodeTypeEnum nodeTypeValue) { + super(); + this.valueDataWrapper = new Wrapper<>(); + this.dataWrapper = new Wrapper<>(); + this.graphEdge = graphEdge; + this.someDataClassGen = someDataClassGen; + this.someValueDataClassGen = someValueDataClassGen; + this.nodeType = nodeType; + this.nodeTypeValue = nodeTypeValue; + } + + public Wrapper<SomeValueData> getValueDataWrapper() { + return valueDataWrapper; + } + + public Wrapper<SomeData> getDataWrapper() { + return dataWrapper; + } + + public GraphEdgeLabels getGraphEdge() { + return graphEdge; + } + + public Supplier<Class<SomeData>> getSomeDataClassGen() { + return someDataClassGen; + } + + public Supplier<Class<SomeValueData>> getSomeValueDataClassGen() { + return someValueDataClassGen; + } + + public NodeTypeEnum getNodeType() { + return nodeType; + } + + public NodeTypeEnum getNodeTypeValue() { + return nodeTypeValue; + } + } + + private <SomeData extends GraphNode, SomeValueData extends GraphNode> void preUpdateElementOfResourceInstanceValidations(UpdateDataContainer<SomeData, SomeValueData> updateDataContainer, IComponentInstanceConnectedElement resourceInstanceProerty, + String resourceInstanceId, Wrapper<TitanOperationStatus> errorWrapper) { + + if (errorWrapper.isEmpty()) { + // Verify VFC instance Exist + validateGIExist(resourceInstanceId, errorWrapper); + } + + if (errorWrapper.isEmpty()) { + // Example: Verify Property connected to VFC exist + validateElementConnectedToComponentExist(updateDataContainer, resourceInstanceProerty, errorWrapper); + } + + if (errorWrapper.isEmpty()) { + // Example: Verify PropertyValue connected to VFC Instance exist + validateElementConnectedToComponentInstanceExist(updateDataContainer, resourceInstanceProerty, errorWrapper); + } + + if (errorWrapper.isEmpty()) { + // Example: Verify PropertyValue connected Property + validateElementConnectedToInstance(updateDataContainer, resourceInstanceProerty, errorWrapper); + } + } + + private <SomeData extends GraphNode, SomeValueData extends GraphNode> void validateElementConnectedToInstance(UpdateDataContainer<SomeData, SomeValueData> updateDataContainer, IComponentInstanceConnectedElement resourceInstanceProerty, + Wrapper<TitanOperationStatus> errorWrapper) { + Either<ImmutablePair<SomeData, GraphEdge>, TitanOperationStatus> child = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(updateDataContainer.getNodeTypeValue()), resourceInstanceProerty.getValueUniqueUid(), + updateDataContainer.getGraphEdge(), updateDataContainer.getNodeType(), updateDataContainer.getSomeDataClassGen().get()); + + if (child.isRight()) { + TitanOperationStatus status = child.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + errorWrapper.setInnerElement(status); + + } else { + updateDataContainer.getDataWrapper().setInnerElement(child.left().value().left); + } + } + + private <SomeValueData extends GraphNode, SomeData extends GraphNode> void validateElementConnectedToComponentInstanceExist(UpdateDataContainer<SomeData, SomeValueData> updateDataContainer, + IComponentInstanceConnectedElement resourceInstanceProerty, Wrapper<TitanOperationStatus> errorWrapper) { + String valueUniqueUid = resourceInstanceProerty.getValueUniqueUid(); + if (valueUniqueUid == null) { + errorWrapper.setInnerElement(TitanOperationStatus.INVALID_ID); + } else { + Either<SomeValueData, TitanOperationStatus> findPropertyValueRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(updateDataContainer.getNodeTypeValue()), valueUniqueUid, updateDataContainer.getSomeValueDataClassGen().get()); + if (findPropertyValueRes.isRight()) { + TitanOperationStatus status = findPropertyValueRes.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + errorWrapper.setInnerElement(status); + } else { + updateDataContainer.getValueDataWrapper().setInnerElement(findPropertyValueRes.left().value()); + } + } + } + + private <SomeData extends GraphNode, SomeValueData extends GraphNode> void validateElementConnectedToComponentExist(UpdateDataContainer<SomeData, SomeValueData> updateDataContainer, + IComponentInstanceConnectedElement resourceInstanceElementConnected, Wrapper<TitanOperationStatus> errorWrapper) { + String uniqueId = resourceInstanceElementConnected.getUniqueId(); + Either<SomeData, TitanOperationStatus> findPropertyDefRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(updateDataContainer.getNodeType()), uniqueId, updateDataContainer.getSomeDataClassGen().get()); + + if (findPropertyDefRes.isRight()) { + TitanOperationStatus status = findPropertyDefRes.right().value(); + errorWrapper.setInnerElement(status); + } + } + + private void validateGIExist(String resourceInstanceId, Wrapper<TitanOperationStatus> errorWrapper) { + validateGIExist(resourceInstanceId, null, errorWrapper); + } + + private void validateGIExist(String resourceInstanceId, Wrapper<GroupInstanceData> compInsDataWrapper, Wrapper<TitanOperationStatus> errorWrapper) { + validateElementExistInGraph(resourceInstanceId, NodeTypeEnum.GroupInstance, () -> GroupInstanceData.class, compInsDataWrapper, errorWrapper); + } + + public <ElementData extends GraphNode> void validateElementExistInGraph(String elementUniqueId, NodeTypeEnum elementNodeType, Supplier<Class<ElementData>> elementClassGen, Wrapper<ElementData> elementDataWrapper, + Wrapper<TitanOperationStatus> errorWrapper) { + Either<ElementData, TitanOperationStatus> findResInstanceRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(elementNodeType), elementUniqueId, elementClassGen.get()); + if (findResInstanceRes.isRight()) { + TitanOperationStatus status = findResInstanceRes.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + errorWrapper.setInnerElement(status); + } else { + if (elementDataWrapper != null) { + elementDataWrapper.setInnerElement(findResInstanceRes.left().value()); + } + } + } + + private void buildGroupInstanceFromGroup(GroupInstance groupInstance, GroupDefinition groupDefinition, Map<String, PropertyValueData> groupInstancePropertyValues) { + + groupInstance.setGroupName(groupDefinition.getName()); + groupInstance.setInvariantUUID(groupDefinition.getInvariantUUID()); + groupInstance.setDescription(groupDefinition.getDescription()); + groupInstance.setVersion(groupDefinition.getVersion()); + groupInstance.setArtifacts(groupDefinition.getArtifacts()); + groupInstance.setArtifactsUuid(groupDefinition.getArtifactsUuid()); + groupInstance.setType(groupDefinition.getType()); + groupInstance.setGroupUUID(groupDefinition.getGroupUUID()); + + List<GroupInstanceProperty> groupInstanceProperties = groupDefinition.convertToGroupProperties() + //converts List of GroupProperties to List of GroupInstanceProperties and updates it with group instance property data + .stream().map(p -> getUpdatedConvertedProperty(p, groupInstancePropertyValues)).collect(Collectors.toList()); + groupInstance.convertFromGroupInstancesProperties(groupInstanceProperties); + } + + private GroupInstanceProperty getUpdatedConvertedProperty(GroupProperty groupProperty, Map<String, PropertyValueData> groupInstancePropertyValues){ + + GroupInstanceProperty updatedProperty = new GroupInstanceProperty(groupProperty, groupProperty.getValue()); + if(!MapUtils.isEmpty(groupInstancePropertyValues) && groupInstancePropertyValues.containsKey(groupProperty.getName())){ + PropertyValueData groupInstancePropertyValue = groupInstancePropertyValues.get(groupProperty.getName()); + updatedProperty.setValue(groupInstancePropertyValue.getValue()); + updatedProperty.setValueUniqueUid(groupInstancePropertyValue.getUniqueId()); + } + return updatedProperty; + } + + private Either<List<ImmutablePair<String, String>>, TitanOperationStatus> getGroupArtifactsPairs(String groupUniqueId) { + + Either<List<ImmutablePair<String, String>>, TitanOperationStatus> result = null; + + Either<List<ImmutablePair<ArtifactData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupInstance), groupUniqueId, GraphEdgeLabels.GROUP_ARTIFACT_REF, + NodeTypeEnum.ArtifactRef, ArtifactData.class); + if (childrenNodes.isRight()) { + TitanOperationStatus status = childrenNodes.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.OK; + } + result = Either.right(status); + + } else { + + List<ImmutablePair<String, String>> artifactsList = new ArrayList<>(); + List<ImmutablePair<ArtifactData, GraphEdge>> list = childrenNodes.left().value(); + if (list != null) { + for (ImmutablePair<ArtifactData, GraphEdge> pair : list) { + ArtifactData artifactData = pair.getKey(); + String uniqueId = artifactData.getArtifactDataDefinition().getUniqueId(); + String UUID = artifactData.getArtifactDataDefinition().getArtifactUUID(); + ImmutablePair<String, String> artifact = new ImmutablePair<>(uniqueId, UUID); + artifactsList.add(artifact); + } + } + + log.debug("The artifacts list related to group {} is {}",groupUniqueId,artifactsList); + result = Either.left(artifactsList); + } + + return result; + + } + + @Override + public StorageOperationStatus dissociateAndAssociateGroupsInstanceFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact) { + + return this.dissociateAndAssociateGroupsInstanceFromArtifactOnGraph(componentId, componentTypeEnum, oldArtifactId, newArtifact); + + } + + private StorageOperationStatus dissociateAndAssociateGroupsInstanceFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact) { + + Either<List<GroupInstance>, StorageOperationStatus> allGroupsFromGraph = getAllGroupInstances(componentId, componentTypeEnum); + if (allGroupsFromGraph.isRight()) { + return allGroupsFromGraph.right().value(); + } + + List<GroupInstance> allGroups = allGroupsFromGraph.left().value(); + if (allGroups == null || allGroups.isEmpty()) { + return StorageOperationStatus.OK; + } + + // Find all groups which contains this artifact id + List<GroupInstance> associatedGroups = allGroups.stream().filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts().contains(oldArtifactId)).collect(Collectors.toList()); + + if (associatedGroups != null && !associatedGroups.isEmpty()) { + + log.debug("The groups {} contains the artifact {}",associatedGroups.stream().map(GroupInstanceDataDefinition::getName).collect(Collectors.toList()),oldArtifactId); + + UniqueIdData oldArtifactData = new UniqueIdData(NodeTypeEnum.ArtifactRef, oldArtifactId); + UniqueIdData newArtifactData = new UniqueIdData(NodeTypeEnum.ArtifactRef, newArtifact.getArtifactDataDefinition().getUniqueId()); + Map<String, Object> props = new HashMap<>(); + props.put(GraphPropertiesDictionary.NAME.getProperty(), newArtifactData.getLabel()); + + for (GroupInstance groupDefinition : associatedGroups) { + UniqueIdData groupData = new UniqueIdData(NodeTypeEnum.GroupInstance, groupDefinition.getUniqueId()); + + Either<GraphRelation, TitanOperationStatus> deleteRelation = titanGenericDao.deleteRelation(groupData, oldArtifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF); + log.trace("After dissociate group {} from artifact {}", groupDefinition.getName(), oldArtifactId); + if (deleteRelation.isRight()) { + TitanOperationStatus status = deleteRelation.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + return DaoStatusConverter.convertTitanStatusToStorageStatus(status); + } + + Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(groupData, newArtifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF, props); + log.trace("After associate group {} to artifact {}", groupDefinition.getName(), newArtifact.getUniqueIdKey()); + if (createRelation.isRight()) { + TitanOperationStatus status = createRelation.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + return DaoStatusConverter.convertTitanStatusToStorageStatus(status); + } + } + + } + return StorageOperationStatus.OK; + } + + private Either<Map<String, PropertyValueData>, TitanOperationStatus> getAllGroupInstancePropertyValuesData(GroupInstanceData groupInstData) { + + Either<Map<String, PropertyValueData>, TitanOperationStatus> result = null; + try{ + Either<List<ImmutablePair<PropertyValueData, GraphEdge>>, TitanOperationStatus> getPropertyValueChildrenRes = + titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), groupInstData.getUniqueId(), GraphEdgeLabels.PROPERTY_VALUE, + NodeTypeEnum.PropertyValue, PropertyValueData.class, true); + if(getPropertyValueChildrenRes.isRight()){ + TitanOperationStatus status = getPropertyValueChildrenRes.right().value(); + log.debug("Failed to fetch property value nodes for group instance {}. Status is {}. ", groupInstData.getName(), status); + if(status == TitanOperationStatus.NOT_FOUND){ + result = Either.left(null); + }else{ + result = Either.right(status); + } + }else{ + result = Either.left(getPropertyValueChildrenRes.left().value().stream() + .collect(Collectors.toMap(pair->(String)(pair.getRight().getProperties().get(GraphPropertiesDictionary.PROPERTY_NAME.getProperty())), ImmutablePair::getLeft))); + } + } catch(Exception e){ + log.debug("The Exception occured during fetch group instance () property values. The message is {}. ", groupInstData.getName(), e.getMessage(), e); + if(result == null){ + result = Either.right(TitanOperationStatus.GENERAL_ERROR); + } + } + return result; + } } 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 77e7ba1f2d..11878376f5 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 @@ -20,549 +20,600 @@ package org.openecomp.sdc.be.model.operations.impl; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation; +import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.dao.utils.MapUtil; +import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.GroupDefinition; -import org.openecomp.sdc.be.model.GroupProperty; -import org.openecomp.sdc.be.model.GroupTypeDefinition; -import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; +import org.openecomp.sdc.be.model.jsontitan.operations.TopologyTemplateOperation; +import org.openecomp.sdc.be.model.operations.StorageException; import org.openecomp.sdc.be.model.operations.api.IGroupOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.resources.data.ArtifactData; -import org.openecomp.sdc.be.resources.data.ComponentInstanceData; -import org.openecomp.sdc.be.resources.data.GroupData; -import org.openecomp.sdc.be.resources.data.GroupTypeData; -import org.openecomp.sdc.be.resources.data.PropertyData; -import org.openecomp.sdc.be.resources.data.PropertyValueData; -import org.openecomp.sdc.be.resources.data.UniqueIdData; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.be.resources.data.*; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.stereotype.Component; -import fj.data.Either; - -@Component("group-operation") -public class GroupOperation extends AbstractOperation implements IGroupOperation { - - - private static Logger log = LoggerFactory.getLogger(GroupOperation.class.getName()); - - @javax.annotation.Resource - private PropertyOperation propertyOperation; - - @javax.annotation.Resource - private GroupTypeOperation groupTypeOperation; - - @javax.annotation.Resource - private ApplicationDataTypeCache dataTypeCache; - - private GroupDefinition convertGroupDataToGroupDefinition(GroupData groupData) { - GroupDefinition newGroupDefinition = new GroupDefinition(groupData.getGroupDataDefinition()); - return newGroupDefinition; - } - - /** - * get members of group - * - * @param groupUniqueId - * @return - */ - private Either<Map<String, String>, TitanOperationStatus> getGroupMembers(String groupUniqueId) { - - Either<Map<String, String>, TitanOperationStatus> result = null; - - Either<List<ImmutablePair<ComponentInstanceData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupUniqueId, GraphEdgeLabels.GROUP_MEMBER, - NodeTypeEnum.ResourceInstance, ComponentInstanceData.class); - - if (childrenNodes.isRight()) { - TitanOperationStatus status = childrenNodes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.OK; - } - result = Either.right(status); - - } else { - - Map<String, String> compInstaMap = new HashMap<>(); - List<ImmutablePair<ComponentInstanceData, GraphEdge>> list = childrenNodes.left().value(); - if (list != null) { - for (ImmutablePair<ComponentInstanceData, GraphEdge> pair : list) { - ComponentInstanceData componentInstanceData = pair.getKey(); - - String compInstUniqueId = componentInstanceData.getComponentInstDataDefinition().getUniqueId(); - String compInstName = componentInstanceData.getName(); - compInstaMap.put(compInstName, compInstUniqueId); - } - } - - result = Either.left(compInstaMap); - } - - return result; - } - - private Either<GroupTypeDefinition, TitanOperationStatus> getGroupTypeOfGroup(String groupUniqueId) { - - Either<ImmutablePair<GroupTypeData, GraphEdge>, TitanOperationStatus> groupTypeRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupUniqueId, GraphEdgeLabels.TYPE_OF, NodeTypeEnum.GroupType, - GroupTypeData.class); - - if (groupTypeRes.isRight()) { - TitanOperationStatus status = groupTypeRes.right().value(); - log.debug("Cannot find group type associated with capability {}. Status is {}", groupUniqueId, status); - - BeEcompErrorManager.getInstance().logBeFailedFindAssociationError("Fetch Group type", NodeTypeEnum.GroupType.getName(), groupUniqueId, String.valueOf(status)); - return Either.right(groupTypeRes.right().value()); - } - - GroupTypeData groupTypeData = groupTypeRes.left().value().getKey(); - - return groupTypeOperation.getGroupTypeByUid(groupTypeData.getGroupTypeDataDefinition().getUniqueId()); - - } - - /** - * get all properties of the group. - * - * the propert definition is taken from the group type. - * - * @param groupUid - * @return - */ - private Either<List<GroupProperty>, TitanOperationStatus> getGroupProperties(String groupUid) { - - List<GroupProperty> groupPropertiesList = new ArrayList<>(); - - Either<GroupTypeDefinition, TitanOperationStatus> groupTypeOfGroupRes = getGroupTypeOfGroup(groupUid); - - if (groupTypeOfGroupRes.isRight()) { - TitanOperationStatus status = groupTypeOfGroupRes.right().value(); - return Either.right(status); - } - - GroupTypeDefinition groupTypeDefinition = groupTypeOfGroupRes.left().value(); - - // Get the properties on the group type of this group - List<PropertyDefinition> groupTypeProperties = groupTypeDefinition.getProperties(); - - if (groupTypeProperties == null || true == groupTypeProperties.isEmpty()) { - return Either.right(TitanOperationStatus.OK); - } - - Map<String, PropertyDefinition> uidToPropDefMap = groupTypeProperties.stream().collect(Collectors.toMap(p -> p.getUniqueId(), p -> p)); - - // Find all properties values on the group - Either<List<ImmutablePair<PropertyValueData, GraphEdge>>, TitanOperationStatus> propertyImplNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupUid, GraphEdgeLabels.PROPERTY_VALUE, - NodeTypeEnum.PropertyValue, PropertyValueData.class); - - if (propertyImplNodes.isRight()) { - TitanOperationStatus status = propertyImplNodes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - groupPropertiesList = groupTypeProperties.stream().map(p -> new GroupProperty(p, p.getDefaultValue(), null)).collect(Collectors.toList()); - return Either.left(groupPropertiesList); - } else { - return Either.right(status); - } - } - - List<ImmutablePair<PropertyValueData, GraphEdge>> list = propertyImplNodes.left().value(); - if (list == null || true == list.isEmpty()) { - return Either.right(TitanOperationStatus.OK); - } - - List<String> processedProps = new ArrayList<>(); - - for (ImmutablePair<PropertyValueData, GraphEdge> propertyValue : list) { - - PropertyValueData propertyValueData = propertyValue.getLeft(); - String propertyValueUid = propertyValueData.getUniqueId(); - String value = propertyValueData.getValue(); - - Either<ImmutablePair<PropertyData, GraphEdge>, TitanOperationStatus> propertyDefRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PropertyValue), propertyValueUid, GraphEdgeLabels.PROPERTY_IMPL, - NodeTypeEnum.Property, PropertyData.class); - if (propertyDefRes.isRight()) { - TitanOperationStatus status = propertyDefRes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - return Either.right(status); - } +import java.util.*; +import java.util.function.Function; +import java.util.stream.Collectors; - ImmutablePair<PropertyData, GraphEdge> propertyDefPair = propertyDefRes.left().value(); +import static org.apache.commons.collections.CollectionUtils.isNotEmpty; +import static org.springframework.util.CollectionUtils.isEmpty; - PropertyData propertyData = propertyDefPair.left; - String propertyUniqueId = propertyData.getPropertyDataDefinition().getUniqueId(); - PropertyDefinition propertyDefinition = uidToPropDefMap.get(propertyUniqueId); - GroupProperty groupProperty = new GroupProperty(propertyDefinition, value, propertyValueUid); +@Component +public class GroupOperation extends AbstractOperation implements IGroupOperation { - processedProps.add(propertyUniqueId); - groupPropertiesList.add(groupProperty); + private static final Logger log = Logger.getLogger(GroupOperation.class.getName()); + private final TitanDao titanDao; + private final TopologyTemplateOperation topologyTemplateOperation; + private final PropertyOperation propertyOperation; + private final GroupTypeOperation groupTypeOperation; + private final ApplicationDataTypeCache dataTypeCache; - } + public GroupOperation(TitanDao titanDao, TopologyTemplateOperation topologyTemplateOperation, PropertyOperation propertyOperation, GroupTypeOperation groupTypeOperation, ApplicationDataTypeCache dataTypeCache) { + this.titanDao = titanDao; + this.topologyTemplateOperation = topologyTemplateOperation; + this.propertyOperation = propertyOperation; + this.groupTypeOperation = groupTypeOperation; + this.dataTypeCache = dataTypeCache; + } - // Find all properties which does not have property value on the group. - List<GroupProperty> leftProps = groupTypeProperties.stream() - // filter out the group type properties which already processed - .filter(p -> false == processedProps.contains(p.getUniqueId())).map(p -> new GroupProperty(p, p.getDefaultValue(), null)).collect(Collectors.toList()); - if (leftProps != null) { - groupPropertiesList.addAll(leftProps); - } + private GroupDefinition convertGroupDataToGroupDefinition(GroupData groupData) { + return new GroupDefinition(groupData.getGroupDataDefinition()); - return Either.left(groupPropertiesList); } - @Override - public Either<List<GraphRelation>, TitanOperationStatus> dissociateAllGroupsFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String artifactId) { - - List<GraphRelation> relations = new ArrayList<>(); - Either<List<GraphRelation>, TitanOperationStatus> result = Either.left(relations); - - Either<List<GroupDefinition>, TitanOperationStatus> allGroupsFromGraph = getAllGroupsFromGraph(componentId, componentTypeEnum, true, true, false); - if (allGroupsFromGraph.isRight()) { - TitanOperationStatus status = allGroupsFromGraph.right().value(); - return Either.right(status); - } - - List<GroupDefinition> allGroups = allGroupsFromGraph.left().value(); - if (allGroups == null || allGroups.isEmpty()) { - return Either.right(TitanOperationStatus.OK); - } - - // Find all groups which contains this artifact id - List<GroupDefinition> associatedGroups = allGroups.stream().filter(p -> p.getArtifacts() != null && p.getArtifacts().contains(artifactId)).collect(Collectors.toList()); - - if (associatedGroups != null && false == associatedGroups.isEmpty()) { - log.debug("The groups {} contains the artifact {}", associatedGroups.stream().map(p -> p.getName()).collect(Collectors.toList()), artifactId); + /** + * get members of group + * + * @param groupUniqueId + * @return + */ + private Either<Map<String, String>, TitanOperationStatus> getGroupMembers(String groupUniqueId) { - UniqueIdData artifactData = new UniqueIdData(NodeTypeEnum.ArtifactRef, artifactId); - for (GroupDefinition groupDefinition : associatedGroups) { - UniqueIdData groupData = new UniqueIdData(NodeTypeEnum.Group, groupDefinition.getUniqueId()); - Either<GraphRelation, TitanOperationStatus> deleteRelation = titanGenericDao.deleteRelation(groupData, artifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF); - if (deleteRelation.isRight()) { - TitanOperationStatus status = deleteRelation.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - return Either.right(status); - } + Either<Map<String, String>, TitanOperationStatus> result = null; - relations.add(deleteRelation.left().value()); - } + Either<List<ImmutablePair<ComponentInstanceData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupUniqueId, GraphEdgeLabels.GROUP_MEMBER, + NodeTypeEnum.ResourceInstance, ComponentInstanceData.class); - return result; + if (childrenNodes.isRight()) { + TitanOperationStatus status = childrenNodes.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.OK; + } + result = Either.right(status); - } else { - log.debug("No group under component id {} is associated to artifact {}", componentId, artifactId); - return Either.right(TitanOperationStatus.OK); - } + } else { - } + Map<String, String> compInstaMap = new HashMap<>(); + List<ImmutablePair<ComponentInstanceData, GraphEdge>> list = childrenNodes.left().value(); + if (list != null) { + for (ImmutablePair<ComponentInstanceData, GraphEdge> pair : list) { + ComponentInstanceData componentInstanceData = pair.getKey(); + + String compInstUniqueId = componentInstanceData.getComponentInstDataDefinition().getUniqueId(); + String compInstName = componentInstanceData.getName(); + compInstaMap.put(compInstName, compInstUniqueId); + } + } - public Either<GroupDefinition, TitanOperationStatus> getGroupFromGraph(String uniqueId, boolean skipProperties, boolean skipMembers, boolean skipArtifacts) { + result = Either.left(compInstaMap); + } - Either<GroupDefinition, TitanOperationStatus> result = null; + return result; + } - Either<GroupData, TitanOperationStatus> groupRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), uniqueId, GroupData.class); - if (groupRes.isRight()) { - TitanOperationStatus status = groupRes.right().value(); - log.debug("Failed to retrieve group {} from graph. Status is {}", uniqueId, status); - BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("Fetch Group", uniqueId, String.valueOf(status)); - result = Either.right(status); - return result; - } + private Either<GroupTypeDefinition, StorageOperationStatus> getGroupTypeOfGroup(String groupUniqueId) { - GroupData groupData = groupRes.left().value(); + Either<ImmutablePair<GroupTypeData, GraphEdge>, StorageOperationStatus> groupTypeRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupUniqueId, GraphEdgeLabels.TYPE_OF, NodeTypeEnum.GroupType, + GroupTypeData.class) + .right() + .map(DaoStatusConverter::convertTitanStatusToStorageStatus); - GroupDefinition groupDefinition = convertGroupDataToGroupDefinition(groupData); + if (groupTypeRes.isRight()) { + StorageOperationStatus status = groupTypeRes.right().value(); + log.debug("Cannot find group type associated with capability {}. Status is {}", groupUniqueId, status); - Either<GroupTypeDefinition, TitanOperationStatus> groupTypeOfGroup = getGroupTypeOfGroup(uniqueId); + BeEcompErrorManager.getInstance().logBeFailedFindAssociationError("Fetch Group type", NodeTypeEnum.GroupType.getName(), groupUniqueId, String.valueOf(status)); + return Either.right(groupTypeRes.right().value()); + } + + GroupTypeData groupTypeData = groupTypeRes.left().value().getKey(); - if (groupTypeOfGroup.isRight()) { - TitanOperationStatus status = groupTypeOfGroup.right().value(); - log.debug("Failed to retrieve capability type of capability {}. Status is {}", uniqueId, status); + return groupTypeOperation.getGroupTypeByUid(groupTypeData.getGroupTypeDataDefinition().getUniqueId()); - result = Either.right(status); - return result; - } + } - GroupTypeDefinition groupTypeDefinition = groupTypeOfGroup.left().value(); - - groupDefinition.setTypeUid(groupTypeDefinition.getUniqueId()); - - if (false == skipMembers) { - Either<Map<String, String>, TitanOperationStatus> membersRes = getGroupMembers(uniqueId); - if (membersRes.isRight()) { - TitanOperationStatus status = membersRes.right().value(); - if (status != TitanOperationStatus.OK) { - result = Either.right(status); - return result; - } - } else { - Map<String, String> members = membersRes.left().value(); - groupDefinition.setMembers(members); - } - } + /** + * get all properties of the group. + * + * the propert definition is taken from the group type. + * + * @param groupUid + * @return + */ + private Either<List<GroupProperty>, StorageOperationStatus> getGroupProperties(String groupUid) { - if (false == skipProperties) { - Either<List<GroupProperty>, TitanOperationStatus> propertiesRes = getGroupProperties(uniqueId); - if (propertiesRes.isRight()) { - TitanOperationStatus status = propertiesRes.right().value(); - if (status != TitanOperationStatus.OK) { - result = Either.right(status); - return result; - } - } else { - List<GroupProperty> properties = propertiesRes.left().value(); - groupDefinition.convertFromGroupProperties(properties); - } - } + List<GroupProperty> groupPropertiesList = new ArrayList<>(); - if (false == skipArtifacts) { - Either<List<ImmutablePair<String, String>>, TitanOperationStatus> artifactsRes = getGroupArtifactsPairs(uniqueId); - if (artifactsRes.isRight()) { - TitanOperationStatus status = artifactsRes.right().value(); - if (status != TitanOperationStatus.OK) { - result = Either.right(status); - return result; - } - } else { - List<String> artifactsUid = new ArrayList<>(); - List<String> artifactsUUID = new ArrayList<>(); - - List<ImmutablePair<String, String>> list = artifactsRes.left().value(); - if (list != null) { - for (ImmutablePair<String, String> pair : list) { - String uid = pair.left; - String UUID = pair.right; - artifactsUid.add(uid); - artifactsUUID.add(UUID); - } - groupDefinition.setArtifacts(artifactsUid); - groupDefinition.setArtifactsUuid(artifactsUUID); - } - } - } - result = Either.left(groupDefinition); + Either<GroupTypeDefinition, StorageOperationStatus> groupTypeOfGroupRes = getGroupTypeOfGroup(groupUid); + + if (groupTypeOfGroupRes.isRight()) { + StorageOperationStatus status = groupTypeOfGroupRes.right().value(); + return Either.right(status); + } - return result; + GroupTypeDefinition groupTypeDefinition = groupTypeOfGroupRes.left().value(); - } + // Get the properties on the group type of this group + List<PropertyDefinition> groupTypeProperties = groupTypeDefinition.getProperties(); - @Override - public boolean isGroupExist(String groupName, boolean inTransaction) { + if (isEmpty(groupTypeProperties)) { + return Either.right(StorageOperationStatus.OK); + } + + Map<String, PropertyDefinition> uidToPropDefMap = groupTypeProperties.stream().collect(Collectors.toMap(PropertyDefinition::getUniqueId, Function.identity())); + + // Find all properties values on the group + Either<List<ImmutablePair<PropertyValueData, GraphEdge>>, StorageOperationStatus> propertyImplNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupUid, GraphEdgeLabels.PROPERTY_VALUE, + NodeTypeEnum.PropertyValue, PropertyValueData.class) + .right() + .map(DaoStatusConverter::convertTitanStatusToStorageStatus); + + if (propertyImplNodes.isRight()) { + StorageOperationStatus status = propertyImplNodes.right().value(); + if (status == StorageOperationStatus.NOT_FOUND) { + groupPropertiesList = groupTypeProperties.stream().map(p -> new GroupProperty(p, p.getDefaultValue(), null)).collect(Collectors.toList()); + return Either.left(groupPropertiesList); + } else { + return Either.right(status); + } + } + + List<ImmutablePair<PropertyValueData, GraphEdge>> list = propertyImplNodes.left().value(); + if (isEmpty(list)) { + return Either.right(StorageOperationStatus.OK); + } - Either<List<GroupData>, TitanOperationStatus> eitherGroup = null; - try { - Map<String, Object> properties = new HashMap<>(); - properties.put(GraphPropertiesDictionary.NAME.getProperty(), groupName); + List<String> processedProps = new ArrayList<>(); + + for (ImmutablePair<PropertyValueData, GraphEdge> propertyValue : list) { + + PropertyValueData propertyValueData = propertyValue.getLeft(); + String propertyValueUid = propertyValueData.getUniqueId(); + String value = propertyValueData.getValue(); + + Either<ImmutablePair<PropertyData, GraphEdge>, StorageOperationStatus> propertyDefRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.PropertyValue), propertyValueUid, GraphEdgeLabels.PROPERTY_IMPL, + NodeTypeEnum.Property, PropertyData.class) + .right() + .map(DaoStatusConverter::convertTitanStatusToStorageStatus); + if (propertyDefRes.isRight()) { + StorageOperationStatus status = propertyDefRes.right().value(); + if (status == StorageOperationStatus.NOT_FOUND) { + status = StorageOperationStatus.INVALID_ID; + } + return Either.right(status); + } - eitherGroup = titanGenericDao.getByCriteria(NodeTypeEnum.Group, properties, GroupData.class); - return eitherGroup.isLeft() && !eitherGroup.left().value().isEmpty(); + ImmutablePair<PropertyData, GraphEdge> propertyDefPair = propertyDefRes.left().value(); - } finally { - handleTransactionCommitRollback(inTransaction, eitherGroup); - } - } + PropertyData propertyData = propertyDefPair.left; + String propertyUniqueId = propertyData.getPropertyDataDefinition().getUniqueId(); - protected Either<List<GroupDefinition>, TitanOperationStatus> getAllGroupsFromGraph(String componentId, NodeTypeEnum componentTypeEnum, boolean skipProperties, boolean skipMembers, boolean skipArtifacts) { + PropertyDefinition propertyDefinition = uidToPropDefMap.get(propertyUniqueId); + GroupProperty groupProperty = new GroupProperty(propertyDefinition, value, propertyValueUid); - List<GroupDefinition> groups = new ArrayList<GroupDefinition>(); + processedProps.add(propertyUniqueId); - Either<List<ImmutablePair<GroupData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(componentTypeEnum), componentId, GraphEdgeLabels.GROUP, NodeTypeEnum.Group, - GroupData.class); + groupPropertiesList.add(groupProperty); - if (childrenNodes.isRight()) { - TitanOperationStatus status = childrenNodes.right().value(); - return Either.right(status); - } + } - List<ImmutablePair<GroupData, GraphEdge>> graphGroups = childrenNodes.left().value(); + // Find all properties which does not have property value on the group. + List<GroupProperty> leftProps = groupTypeProperties.stream() + // filter out the group type properties which already processed + .filter(p -> !processedProps.contains(p.getUniqueId())) + .map(p -> new GroupProperty(p, p.getDefaultValue(), null)) + .collect(Collectors.toList()); + if (leftProps != null) { + groupPropertiesList.addAll(leftProps); + } + + return Either.left(groupPropertiesList); + } + + @Override + public Either<List<GraphRelation>, StorageOperationStatus> dissociateAllGroupsFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String artifactId) { + + List<GraphRelation> relations = new ArrayList<>(); + Either<List<GraphRelation>, StorageOperationStatus> result = Either.left(relations); + + Either<List<GroupDefinition>, StorageOperationStatus> allGroupsFromGraph = getAllGroupsFromGraph(componentId, componentTypeEnum, true, true, false); + if (allGroupsFromGraph.isRight()) { + StorageOperationStatus status = allGroupsFromGraph.right().value(); + return Either.right(status); + } + + List<GroupDefinition> allGroups = allGroupsFromGraph.left().value(); + if (isEmpty(allGroups)) { + return Either.right(StorageOperationStatus.OK); + } + + // Find all groups which contains this artifact id + List<GroupDefinition> associatedGroups = allGroups.stream().filter(p -> p.getArtifacts() != null && p.getArtifacts().contains(artifactId)).collect(Collectors.toList()); + + if (isNotEmpty(associatedGroups)) { + log.debug("The groups {} contains the artifact {}", associatedGroups.stream().map(GroupDataDefinition::getName).collect(Collectors.toList()), artifactId); + + UniqueIdData artifactData = new UniqueIdData(NodeTypeEnum.ArtifactRef, artifactId); + for (GroupDefinition groupDefinition : associatedGroups) { + UniqueIdData groupData = new UniqueIdData(NodeTypeEnum.Group, groupDefinition.getUniqueId()); + Either<GraphRelation, StorageOperationStatus> deleteRelation = titanGenericDao.deleteRelation(groupData, artifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF) + .right() + .map(DaoStatusConverter::convertTitanStatusToStorageStatus); + if (deleteRelation.isRight()) { + StorageOperationStatus status = deleteRelation.right().value(); + if (status == StorageOperationStatus.NOT_FOUND) { + status = StorageOperationStatus.INVALID_ID; + } + return Either.right(status); + } + + relations.add(deleteRelation.left().value()); + } + + return result; + + } else { + log.debug("No group under component id {} is associated to artifact {}", componentId, artifactId); + return Either.right(StorageOperationStatus.OK); + } + + } + + public Either<GroupDefinition, StorageOperationStatus> getGroupFromGraph(String uniqueId, boolean skipProperties, boolean skipMembers, boolean skipArtifacts) { + + Either<GroupDefinition, StorageOperationStatus> result = null; + + Either<GroupData, StorageOperationStatus> groupRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), uniqueId, GroupData.class) + .right() + .map(DaoStatusConverter::convertTitanStatusToStorageStatus); + if (groupRes.isRight()) { + StorageOperationStatus status = groupRes.right().value(); + log.debug("Failed to retrieve group {} from graph. Status is {}", uniqueId, status); + BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("Fetch Group", uniqueId, String.valueOf(status)); + result = Either.right(status); + return result; + } + + GroupData groupData = groupRes.left().value(); + + GroupDefinition groupDefinition = convertGroupDataToGroupDefinition(groupData); + + Either<GroupTypeDefinition, StorageOperationStatus> groupTypeOfGroup = getGroupTypeOfGroup(uniqueId); + + if (groupTypeOfGroup.isRight()) { + StorageOperationStatus status = groupTypeOfGroup.right().value(); + log.debug("Failed to retrieve capability type of capability {}. Status is {}", uniqueId, status); + + result = Either.right(status); + return result; + } + + GroupTypeDefinition groupTypeDefinition = groupTypeOfGroup.left().value(); + + groupDefinition.setTypeUid(groupTypeDefinition.getUniqueId()); + + if (!skipMembers) { + Either<Map<String, String>, StorageOperationStatus> membersRes = getGroupMembers(uniqueId) + .right() + .map(DaoStatusConverter::convertTitanStatusToStorageStatus); + if (membersRes.isRight()) { + StorageOperationStatus status = membersRes.right().value(); + if (status != StorageOperationStatus.OK) { + result = Either.right(status); + return result; + } + } else { + Map<String, String> members = membersRes.left().value(); + groupDefinition.setMembers(members); + } + } + + if (!skipProperties) { + Either<List<GroupProperty>, StorageOperationStatus> propertiesRes = getGroupProperties(uniqueId); + if (propertiesRes.isRight()) { + StorageOperationStatus status = propertiesRes.right().value(); + if (status != StorageOperationStatus.OK) { + result = Either.right(status); + return result; + } + } else { + List<GroupProperty> properties = propertiesRes.left().value(); + groupDefinition.convertFromGroupProperties(properties); + } + } + + if (!skipArtifacts) { + Either<List<ImmutablePair<String, String>>, StorageOperationStatus> artifactsRes = getGroupArtifactsPairs(uniqueId) + .right() + .map(DaoStatusConverter::convertTitanStatusToStorageStatus); + if (artifactsRes.isRight()) { + StorageOperationStatus status = artifactsRes.right().value(); + if (status != StorageOperationStatus.OK) { + result = Either.right(status); + return result; + } + } else { + List<String> artifactsUid = new ArrayList<>(); + List<String> artifactsUUID = new ArrayList<>(); + + List<ImmutablePair<String, String>> list = artifactsRes.left().value(); + if (list != null) { + for (ImmutablePair<String, String> pair : list) { + String uid = pair.left; + String UUID = pair.right; + artifactsUid.add(uid); + artifactsUUID.add(UUID); + } + groupDefinition.setArtifacts(artifactsUid); + groupDefinition.setArtifactsUuid(artifactsUUID); + } + } + } + result = Either.left(groupDefinition); + + return result; + + } + + @Override + public boolean isGroupExist(String groupName, boolean inTransaction) { + + Either<List<GroupData>, TitanOperationStatus> eitherGroup = null; + try { + Map<String, Object> properties = new HashMap<>(); + properties.put(GraphPropertiesDictionary.NAME.getProperty(), groupName); + + eitherGroup = titanGenericDao.getByCriteria(NodeTypeEnum.Group, properties, GroupData.class); + return eitherGroup.isLeft() && !eitherGroup.left().value().isEmpty(); + + } finally { + handleTransactionCommitRollback(inTransaction, eitherGroup); + } + } + + protected Either<List<GroupDefinition>, StorageOperationStatus> getAllGroupsFromGraph(String componentId, NodeTypeEnum componentTypeEnum, boolean skipProperties, boolean skipMembers, boolean skipArtifacts) { + + List<GroupDefinition> groups = new ArrayList<>(); + + Either<List<ImmutablePair<GroupData, GraphEdge>>, StorageOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(componentTypeEnum), componentId, GraphEdgeLabels.GROUP, NodeTypeEnum.Group, + GroupData.class) + .right() + .map(DaoStatusConverter::convertTitanStatusToStorageStatus); + + if (childrenNodes.isRight()) { + StorageOperationStatus status = childrenNodes.right().value(); + return Either.right(status); + } + + List<ImmutablePair<GroupData, GraphEdge>> graphGroups = childrenNodes.left().value(); + + if (isEmpty(graphGroups)) { + return Either.right(StorageOperationStatus.NOT_FOUND); + } - if (graphGroups == null || true == graphGroups.isEmpty()) { - return Either.right(TitanOperationStatus.NOT_FOUND); - } - // Consumer<String> consumer = (x) -> getGroup(x); - // StreamUtils.takeWhile(graphGroups.stream().map(p -> - // p.left.getUniqueId()), consumer); for (ImmutablePair<GroupData, GraphEdge> pair : graphGroups) { - String groupUniqueId = pair.left.getGroupDataDefinition().getUniqueId(); - Either<GroupDefinition, TitanOperationStatus> groupRes = this.getGroupFromGraph(groupUniqueId, skipProperties, skipMembers, skipArtifacts); + String groupUniqueId = pair.left.getGroupDataDefinition().getUniqueId(); + Either<GroupDefinition, StorageOperationStatus> groupRes = this.getGroupFromGraph(groupUniqueId, skipProperties, skipMembers, skipArtifacts); - if (groupRes.isRight()) { - TitanOperationStatus status = groupRes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - return Either.right(status); - } else { - groups.add(groupRes.left().value()); - } + if (groupRes.isRight()) { + StorageOperationStatus status = groupRes.right().value(); + if (status == StorageOperationStatus.NOT_FOUND) { + status = StorageOperationStatus.INVALID_ID; + } + return Either.right(status); + } else { + groups.add(groupRes.left().value()); + } - } + } - return Either.left(groups); - } + return Either.left(groups); + } - private TitanOperationStatus dissociateAndAssociateGroupsFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact) { + private StorageOperationStatus dissociateAndAssociateGroupsFromArtifactOnGraph(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact) { - Either<List<GroupDefinition>, TitanOperationStatus> allGroupsFromGraph = getAllGroupsFromGraph(componentId, componentTypeEnum, true, true, false); + Either<List<GroupDefinition>, StorageOperationStatus> allGroupsFromGraph = getAllGroupsFromGraph(componentId, componentTypeEnum, true, true, false); if (allGroupsFromGraph.isRight()) { - TitanOperationStatus status = allGroupsFromGraph.right().value(); - return status; - } + return allGroupsFromGraph.right().value(); - List<GroupDefinition> allGroups = allGroupsFromGraph.left().value(); - if (allGroups == null || allGroups.isEmpty()) { - return TitanOperationStatus.OK; } - // Find all groups which contains this artifact id - List<GroupDefinition> associatedGroups = allGroups.stream().filter(p -> p.getArtifacts() != null && p.getArtifacts().contains(oldArtifactId)).collect(Collectors.toList()); - - if (associatedGroups != null && false == associatedGroups.isEmpty()) { - - log.debug("The groups {} contains the artifact {}", associatedGroups.stream().map(p -> p.getName()).collect(Collectors.toList()), oldArtifactId); - - UniqueIdData oldArtifactData = new UniqueIdData(NodeTypeEnum.ArtifactRef, oldArtifactId); - UniqueIdData newArtifactData = new UniqueIdData(NodeTypeEnum.ArtifactRef, newArtifact.getArtifactDataDefinition().getUniqueId()); - Map<String, Object> props = new HashMap<String, Object>(); - props.put(GraphPropertiesDictionary.NAME.getProperty(), newArtifactData.getLabel()); - - for (GroupDefinition groupDefinition : associatedGroups) { - UniqueIdData groupData = new UniqueIdData(NodeTypeEnum.Group, groupDefinition.getUniqueId()); - - Either<GraphRelation, TitanOperationStatus> deleteRelation = titanGenericDao.deleteRelation(groupData, oldArtifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF); - log.trace("After dissociate group {} from artifact {}" , groupDefinition.getName(), oldArtifactId); - if (deleteRelation.isRight()) { - TitanOperationStatus status = deleteRelation.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - return status; - } - - Either<GraphRelation, TitanOperationStatus> createRelation = titanGenericDao.createRelation(groupData, newArtifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF, props); - log.trace("After associate group {} to artifact {}" , groupDefinition.getName(), newArtifact.getUniqueIdKey()); - if (createRelation.isRight()) { - TitanOperationStatus status = createRelation.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - return status; - } - } - + List<GroupDefinition> allGroups = allGroupsFromGraph.left().value(); + if (isEmpty(allGroups)) { + return StorageOperationStatus.OK; + } + + // Find all groups which contains this artifact id + List<GroupDefinition> associatedGroups = allGroups.stream().filter(p -> p.getArtifacts() != null && p.getArtifacts().contains(oldArtifactId)).collect(Collectors.toList()); + + if (isNotEmpty(associatedGroups)) { + + log.debug("The groups {} contains the artifact {}", associatedGroups.stream().map(GroupDataDefinition::getName).collect(Collectors.toList()), oldArtifactId); + + UniqueIdData oldArtifactData = new UniqueIdData(NodeTypeEnum.ArtifactRef, oldArtifactId); + UniqueIdData newArtifactData = new UniqueIdData(NodeTypeEnum.ArtifactRef, newArtifact.getArtifactDataDefinition().getUniqueId()); + Map<String, Object> props = new HashMap<>(); + props.put(GraphPropertiesDictionary.NAME.getProperty(), newArtifactData.getLabel()); + + for (GroupDefinition groupDefinition : associatedGroups) { + UniqueIdData groupData = new UniqueIdData(NodeTypeEnum.Group, groupDefinition.getUniqueId()); + + Either<GraphRelation, StorageOperationStatus> deleteRelation = titanGenericDao.deleteRelation(groupData, oldArtifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF) + .right() + .map(DaoStatusConverter::convertTitanStatusToStorageStatus); + log.trace("After dissociate group {} from artifact {}" , groupDefinition.getName(), oldArtifactId); + if (deleteRelation.isRight()) { + StorageOperationStatus status = deleteRelation.right().value(); + if (status == StorageOperationStatus.NOT_FOUND) { + status = StorageOperationStatus.INVALID_ID; + } + return status; + } + + Either<GraphRelation, StorageOperationStatus> createRelation = titanGenericDao.createRelation(groupData, newArtifactData, GraphEdgeLabels.GROUP_ARTIFACT_REF, props) + .right() + .map(DaoStatusConverter::convertTitanStatusToStorageStatus); + log.trace("After associate group {} to artifact {}" , groupDefinition.getName(), newArtifact.getUniqueIdKey()); + if (createRelation.isRight()) { + StorageOperationStatus status = createRelation.right().value(); + if (status == StorageOperationStatus.NOT_FOUND) { + status = StorageOperationStatus.INVALID_ID; + } + return status; + } + } + + } + return StorageOperationStatus.OK; + } + + @Override + public StorageOperationStatus dissociateAndAssociateGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact, boolean inTransaction) { + + StorageOperationStatus result = null; + + try { + StorageOperationStatus status = this.dissociateAndAssociateGroupsFromArtifactOnGraph(componentId, componentTypeEnum, oldArtifactId, newArtifact); + + if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { + return status; + } + + result = StorageOperationStatus.OK; + return result; + + } finally { + if (!inTransaction) { + if (result == null || result != StorageOperationStatus.OK) { + log.debug("Going to execute rollback on graph."); + BeEcompErrorManager.getInstance().logBeExecuteRollbackError("Rollback on graph"); + titanGenericDao.rollback(); + } else { + log.debug("Going to execute commit on graph."); + titanGenericDao.commit(); + } + } + } + } + + private Either<List<ImmutablePair<String, String>>, TitanOperationStatus> getGroupArtifactsPairs(String groupUniqueId) { + + Either<List<ImmutablePair<String, String>>, TitanOperationStatus> result = null; + + Either<List<ImmutablePair<ArtifactData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupUniqueId, GraphEdgeLabels.GROUP_ARTIFACT_REF, + NodeTypeEnum.ArtifactRef, ArtifactData.class); + if (childrenNodes.isRight()) { + TitanOperationStatus status = childrenNodes.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.OK; + } + result = Either.right(status); + + } else { + + List<ImmutablePair<String, String>> artifactsList = new ArrayList<>(); + List<ImmutablePair<ArtifactData, GraphEdge>> list = childrenNodes.left().value(); + if (list != null) { + for (ImmutablePair<ArtifactData, GraphEdge> pair : list) { + ArtifactData artifactData = pair.getKey(); + String uniqueId = artifactData.getArtifactDataDefinition().getUniqueId(); + String UUID = artifactData.getArtifactDataDefinition().getArtifactUUID(); + ImmutablePair<String, String> artifact = new ImmutablePair<>(uniqueId, UUID); + artifactsList.add(artifact); + } + } + + log.debug("The artifacts list related to group {} is {}", groupUniqueId, artifactsList); + result = Either.left(artifactsList); + } + + return result; + + } + + @Override + public StorageOperationStatus validateAndUpdatePropertyValue(GroupProperty property) { + + StorageOperationStatus result = null; + String innerType = property.getSchema() == null ? null : property.getSchema().getProperty() == null ? null : property.getSchema().getProperty().getType(); + Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); + Either<Object, Boolean> isValid = null; + if (allDataTypes.isRight()) { + TitanOperationStatus status = allDataTypes.right().value(); + log.debug("Failed to fetch data types from cache. Status is {}. ", status); + result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); + } + if(result == null){ + isValid = propertyOperation.validateAndUpdatePropertyValue(property.getType(), property.getValue(), innerType, allDataTypes.left().value()); + if(isValid.isRight()){ + log.debug("Failed to validate property value {}. Status is {}. ", property.getValue(), StorageOperationStatus.INVALID_PROPERTY); + result = StorageOperationStatus.INVALID_PROPERTY; + } + } + if(result == null){ + String validValue = String.valueOf(isValid.left().value()); + property.setValue(validValue); + result = StorageOperationStatus.OK; + } + return result; + } + + public StorageOperationStatus updateGroupProperties(org.openecomp.sdc.be.model.Component containerComponent, String groupId, List<PropertyDataDefinition> propertiesToUpdate) { + log.debug("#updateGroupProperties - updating the properties of group {} in component {}", groupId, containerComponent.getUniqueId()); + Optional<GroupDefinition> group = containerComponent.getGroupById(groupId); + if (group.isPresent()){ + return titanDao.getVertexById(containerComponent.getUniqueId(), JsonParseFlagEnum.NoParse) + .either(containerVertex -> updateGroupProperties(containerVertex, group.get(), propertiesToUpdate), + DaoStatusConverter::convertTitanStatusToStorageStatus); + } else { + throw new StorageException(StorageOperationStatus.NOT_FOUND, groupId); } - return TitanOperationStatus.OK; } - @Override - public StorageOperationStatus dissociateAndAssociateGroupsFromArtifact(String componentId, NodeTypeEnum componentTypeEnum, String oldArtifactId, ArtifactData newArtifact, boolean inTransaction) { - - StorageOperationStatus result = null; - - try { - TitanOperationStatus status = this.dissociateAndAssociateGroupsFromArtifactOnGraph(componentId, componentTypeEnum, oldArtifactId, newArtifact); - - if (status != TitanOperationStatus.OK && status != TitanOperationStatus.NOT_FOUND) { - result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - return result; - } - - result = StorageOperationStatus.OK; - return result; - - } finally { - if (false == inTransaction) { - if (result == null || result != StorageOperationStatus.OK) { - log.debug("Going to execute rollback on graph."); - BeEcompErrorManager.getInstance().logBeExecuteRollbackError("Rollback on graph"); - titanGenericDao.rollback(); - } else { - log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } + private StorageOperationStatus updateGroupProperties(GraphVertex container, GroupDefinition group, List<PropertyDataDefinition> propertiesToUpdate) { + List<PropertyDataDefinition> groupProperties = group.getProperties(); + List<PropertyDataDefinition> updatedGroupProperties = updateGroupProperties(groupProperties, propertiesToUpdate); + group.setProperties(updatedGroupProperties); + return topologyTemplateOperation.updateGroupOfToscaElement(container, group); } - private Either<List<ImmutablePair<String, String>>, TitanOperationStatus> getGroupArtifactsPairs(String groupUniqueId) { - - Either<List<ImmutablePair<String, String>>, TitanOperationStatus> result = null; - - Either<List<ImmutablePair<ArtifactData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Group), groupUniqueId, GraphEdgeLabels.GROUP_ARTIFACT_REF, - NodeTypeEnum.ArtifactRef, ArtifactData.class); - if (childrenNodes.isRight()) { - TitanOperationStatus status = childrenNodes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.OK; - } - result = Either.right(status); - - } else { - - List<ImmutablePair<String, String>> artifactsList = new ArrayList<>(); - List<ImmutablePair<ArtifactData, GraphEdge>> list = childrenNodes.left().value(); - if (list != null) { - for (ImmutablePair<ArtifactData, GraphEdge> pair : list) { - ArtifactData artifactData = pair.getKey(); - String uniqueId = artifactData.getArtifactDataDefinition().getUniqueId(); - String UUID = artifactData.getArtifactDataDefinition().getArtifactUUID(); - ImmutablePair<String, String> artifact = new ImmutablePair<String, String>(uniqueId, UUID); - artifactsList.add(artifact); - } - } - - log.debug("The artifacts list related to group {} is {}", groupUniqueId, artifactsList); - result = Either.left(artifactsList); - } - - return result; - + private List<PropertyDataDefinition> updateGroupProperties(List<PropertyDataDefinition> currentGroupProperties, List<PropertyDataDefinition> toBeUpdatedProperties) { + Map<String, PropertyDataDefinition> currPropsByName = MapUtil.toMap(currentGroupProperties, PropertyDataDefinition::getName); + overrideCurrentPropertiesWithUpdatedProperties(currPropsByName, toBeUpdatedProperties); + return new ArrayList<>(currPropsByName.values()); } - @Override - public StorageOperationStatus validateAndUpdatePropertyValue(GroupProperty property) { - - StorageOperationStatus result = null; - String innerType = property.getSchema() == null ? null : property.getSchema().getProperty() == null ? null : property.getSchema().getProperty().getType(); - Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypes = dataTypeCache.getAll(); - Either<Object, Boolean> isValid = null; - if (allDataTypes.isRight()) { - TitanOperationStatus status = allDataTypes.right().value(); - log.debug("Failed to fetch data types from cache. Status is {}. ", status); - result = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } - if(result == null){ - isValid = propertyOperation.validateAndUpdatePropertyValue(property.getType(), property.getValue(), innerType, allDataTypes.left().value()); - if(isValid.isRight()){ - log.debug("Failed to validate property value {}. Status is {}. ", property.getValue(), StorageOperationStatus.INVALID_PROPERTY); - result = StorageOperationStatus.INVALID_PROPERTY; - } - } - if(result == null){ - String validValue = String.valueOf(isValid.left().value()); - property.setValue(validValue); - result = StorageOperationStatus.OK; - } - return result; + private void overrideCurrentPropertiesWithUpdatedProperties(Map<String, PropertyDataDefinition> currPropsByName, List<PropertyDataDefinition> toBeUpdatedProperties) { + toBeUpdatedProperties.forEach(prop -> currPropsByName.put(prop.getName(), prop)); } + } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/GroupTypeOperation.java index b17bab3d04..1817868255 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 @@ -20,83 +20,78 @@ package org.openecomp.sdc.be.model.operations.impl; -import static org.openecomp.sdc.be.dao.titan.TitanUtils.buildNotInPredicate; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - -import javax.annotation.Resource; - +import com.google.common.base.Strings; +import com.thinkaurelius.titan.graphdb.query.TitanPredicate; +import fj.data.Either; import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.tinkerpop.gremlin.structure.Edge; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation; import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; +import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.dao.titan.TitanGenericDao; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.elements.GroupTypeDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.model.CapabilityDefinition; import org.openecomp.sdc.be.model.CapabilityTypeDefinition; import org.openecomp.sdc.be.model.GroupTypeDefinition; import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.operations.StorageException; +import org.openecomp.sdc.be.model.operations.api.DerivedFromOperation; import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.resources.data.CapabilityTypeData; -import org.openecomp.sdc.be.resources.data.GroupTypeData; -import org.openecomp.sdc.be.resources.data.PropertyData; -import org.openecomp.sdc.be.resources.data.UniqueIdData; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Qualifier; +import org.openecomp.sdc.be.model.operations.api.TypeOperations; +import org.openecomp.sdc.be.model.utils.TypeCompareUtils; +import org.openecomp.sdc.be.resources.data.*; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.stereotype.Component; -import com.google.common.base.Strings; -import com.thinkaurelius.titan.graphdb.query.TitanPredicate; +import java.util.*; +import java.util.function.Function; +import java.util.stream.Collectors; -import fj.data.Either; +import static org.openecomp.sdc.be.dao.titan.TitanUtils.buildNotInPredicate; @Component("group-type-operation") -public class GroupTypeOperation extends AbstractOperation implements IGroupTypeOperation { - @Resource - private CapabilityTypeOperation capabilityTypeOperation; - - private static final Logger log = LoggerFactory.getLogger(GroupTypeOperation.class); +public class GroupTypeOperation implements IGroupTypeOperation { + private static final Logger log = Logger.getLogger(GroupTypeOperation.class.getName()); private static final String CREATE_FLOW_CONTEXT = "CreateGroupType"; - private static final String GET_FLOW_CONTEXT = "GetGroupType"; - - private PropertyOperation propertyOperation; - private TitanGenericDao titanGenericDao; + private final PropertyOperation propertyOperation; + private final TitanGenericDao titanGenericDao; + private final CapabilityTypeOperation capabilityTypeOperation; + private final CapabilityOperation capabilityOperation; + private final DerivedFromOperation derivedFromOperation; + private final OperationUtils operationUtils; - public GroupTypeOperation(@Qualifier("titan-generic-dao") TitanGenericDao titanGenericDao, @Qualifier("property-operation") PropertyOperation propertyOperation) { - super(); - this.propertyOperation = propertyOperation; - this.titanGenericDao = titanGenericDao; - } - /** - * FOR TEST ONLY - * - * @param titanGenericDao - */ - public void setTitanGenericDao(TitanGenericDao titanGenericDao) { + public GroupTypeOperation(TitanGenericDao titanGenericDao, + PropertyOperation propertyOperation, + CapabilityTypeOperation capabilityTypeOperation, + CapabilityOperation capabilityOperation, + DerivedFromOperation derivedFromOperation, OperationUtils operationUtils) { this.titanGenericDao = titanGenericDao; + this.propertyOperation = propertyOperation; + this.capabilityTypeOperation = capabilityTypeOperation; + this.capabilityOperation = capabilityOperation; + this.derivedFromOperation = derivedFromOperation; + this.operationUtils = operationUtils; } @Override public Either<GroupTypeDefinition, StorageOperationStatus> addGroupType(GroupTypeDefinition groupTypeDefinition) { - - return addGroupType(groupTypeDefinition, false); + Either<GroupTypeDefinition, StorageOperationStatus> validationRes = validateUpdateProperties(groupTypeDefinition); + if (validationRes.isRight()) { + log.error("#addGroupType - One or all properties of group type {} not valid. status is {}", groupTypeDefinition, validationRes.right().value()); + return validationRes; + } + + return addGroupType(groupTypeDefinition, true); } @Override @@ -111,84 +106,206 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO if (eitherStatus.isRight()) { BeEcompErrorManager.getInstance().logBeFailedCreateNodeError(CREATE_FLOW_CONTEXT, groupTypeDefinition.getType(), eitherStatus.right().value().name()); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(eitherStatus.right().value())); + } + else { + result = getGroupType(eitherStatus.left().value().getUniqueId(), inTransaction); + } - } else { - GroupTypeData groupTypeData = eitherStatus.left().value(); - - String uniqueId = groupTypeData.getUniqueId(); - Either<GroupTypeDefinition, StorageOperationStatus> groupTypeRes = this.getGroupType(uniqueId, true); + return result; - if (groupTypeRes.isRight()) { - BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError(GET_FLOW_CONTEXT, groupTypeDefinition.getType(), eitherStatus.right().value().name()); - } else { - List<CapabilityTypeDefinition> groupCapTypes = groupTypeDefinition.getCapabilityTypes(); - if (!CollectionUtils.isEmpty(groupCapTypes)) { - Optional<TitanOperationStatus> firstFailure = connectToCapabilityType(groupTypeData, groupCapTypes); - if (firstFailure.isPresent()) { - groupTypeRes = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(firstFailure.get())); - } - } - } + } finally { + titanGenericDao.handleTransactionCommitRollback(inTransaction, result); + } - result = groupTypeRes; + } + @Override + public Either<GroupTypeDefinition, StorageOperationStatus> updateGroupType(GroupTypeDefinition updatedGroupType, GroupTypeDefinition currGroupType) { + log.debug("updating group type {}", updatedGroupType.getType()); + return updateGroupTypeOnGraph(updatedGroupType, currGroupType); + } + + + public Either<GroupTypeDefinition, StorageOperationStatus> validateUpdateProperties(GroupTypeDefinition groupTypeDefinition) { + TitanOperationStatus error = null; + if (CollectionUtils.isNotEmpty(groupTypeDefinition.getProperties()) && !Strings.isNullOrEmpty(groupTypeDefinition.getDerivedFrom())) { + Either<Map<String, PropertyDefinition>, TitanOperationStatus> allPropertiesRes = + getAllGroupTypePropertiesFromAllDerivedFrom(groupTypeDefinition.getDerivedFrom()); + if (allPropertiesRes.isRight() && !allPropertiesRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { + error = allPropertiesRes.right().value(); + log.debug("Couldn't fetch derived from property nodes for group type {}, error: {}", groupTypeDefinition.getType(), error); + } + if (error == null && !allPropertiesRes.left().value().isEmpty()) { + Either<List<PropertyDefinition>, TitanOperationStatus> validatePropertiesRes = propertyOperation.validatePropertiesUniqueness(allPropertiesRes.left().value(), + groupTypeDefinition.getProperties()); + if (validatePropertiesRes.isRight()) { + error = validatePropertiesRes.right().value(); + } } + } + if (error == null) { + return Either.left(groupTypeDefinition); + } + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error)); + } + + private Either<Map<String, PropertyDefinition>, TitanOperationStatus> getAllGroupTypePropertiesFromAllDerivedFrom(String firstParentType) { + return titanGenericDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), firstParentType, GroupTypeData.class) + .left() + .bind(parentGroup -> propertyOperation.getAllTypePropertiesFromAllDerivedFrom(parentGroup.getUniqueId(), NodeTypeEnum.GroupType, GroupTypeData.class)); + } - return result; - } finally { - handleTransactionCommitRollback(inTransaction, result); + private StorageOperationStatus mergeCapabilities(GroupTypeDefinition groupTypeDef) { + Map<String, CapabilityDefinition> updatedGroupTypeCapabilities = groupTypeDef.getCapabilities(); + Map<String, CapabilityDefinition> newGroupTypeCapabilities; + Either<List<CapabilityDefinition>, StorageOperationStatus> oldCapabilitiesRes = getCapablities(groupTypeDef.getUniqueId()); + if (oldCapabilitiesRes.isRight()) { + StorageOperationStatus status = oldCapabilitiesRes.right().value(); + if (status == StorageOperationStatus.NOT_FOUND) { + newGroupTypeCapabilities = updatedGroupTypeCapabilities; + } + else { + return status; + } + } + else { + Map<String, CapabilityDefinition> oldCapabilities = asCapabilitiesMap(oldCapabilitiesRes.left().value()); + newGroupTypeCapabilities = collectNewCapabilities(updatedGroupTypeCapabilities, oldCapabilities); + + for(Map.Entry<String, CapabilityDefinition> oldEntry: oldCapabilities.entrySet()) { + String key = oldEntry.getKey(); + CapabilityDefinition newCapDef = updatedGroupTypeCapabilities != null? updatedGroupTypeCapabilities.get(key): null; + CapabilityDefinition oldCapDef = oldEntry.getValue(); + + StorageOperationStatus deleteCapResult = deleteOutdatedCapability(newGroupTypeCapabilities, newCapDef, oldCapDef); + if(deleteCapResult != StorageOperationStatus.OK) { + return deleteCapResult; + } + } } + TitanOperationStatus createCapResult = createCapabilities(new GroupTypeData(groupTypeDef), newGroupTypeCapabilities); + return DaoStatusConverter.convertTitanStatusToStorageStatus(createCapResult); } + /** + * @param newGroupTypeCapabilities + * @param newCapDef + * @param oldCapDef + * @return + */ + private StorageOperationStatus deleteOutdatedCapability(Map<String, CapabilityDefinition> newGroupTypeCapabilities, CapabilityDefinition newCapDef, CapabilityDefinition oldCapDef) { + if(!isUpdateAllowed(newCapDef, oldCapDef)) { + return StorageOperationStatus.MATCH_NOT_FOUND; + } - @Override - public Either<GroupTypeDefinition, StorageOperationStatus> upgradeGroupType(GroupTypeDefinition groupTypeDefinitionNew, GroupTypeDefinition groupTypeDefinitionOld) { - return upgradeGroupType(groupTypeDefinitionOld, groupTypeDefinitionNew, false); + if (!TypeCompareUtils.capabilityEquals(oldCapDef, newCapDef)) { + StorageOperationStatus deleteCapResult = capabilityOperation.deleteCapability(oldCapDef); + + if(deleteCapResult == StorageOperationStatus.OK) { + newGroupTypeCapabilities.put(newCapDef.getName(), newCapDef); + } + else { + return deleteCapResult; + } + } + + return StorageOperationStatus.OK; } - @Override - public Either<GroupTypeDefinition, StorageOperationStatus> upgradeGroupType(GroupTypeDefinition groupTypeDefinitionNew, GroupTypeDefinition groupTypeDefinitionOld, boolean inTransaction) { - Either<GroupTypeDefinition, StorageOperationStatus> result = Either.left(groupTypeDefinitionNew); + private boolean isUpdateAllowed(CapabilityDefinition newCapDef, CapabilityDefinition oldCapDef) { + if (newCapDef == null) { + log.error("#upsertCapabilities - Failed due to attempt to delete the capability with id {}", oldCapDef.getUniqueId()); + return false; + } - try { - // dr2032: - // Right now upgrade Group is used only to ensure that already existing group type is connected by DERRIVED_FROM edge with it's parent - // We don't need to use for a while new node definition since following group type upgrade is not supported. - if (!Strings.isNullOrEmpty(groupTypeDefinitionOld.getDerivedFrom())) { - result = ensureExsitanceDerivedFromEdge(groupTypeDefinitionOld); - } - } finally { - handleTransactionCommitRollback(inTransaction, result); + if (newCapDef.getType() == null || !newCapDef.getType().equals(oldCapDef.getType())) { + log.error("#upsertCapabilities - Failed due to attempt to change type of the capability with id {}", oldCapDef.getUniqueId()); + return false; } + + return true; + } - return result; + /** + * @param updatedGroupTypeCapabilities + * @param oldCapabilities + * @return + */ + private Map<String, CapabilityDefinition> collectNewCapabilities(Map<String, CapabilityDefinition> updatedGroupTypeCapabilities, Map<String, CapabilityDefinition> oldCapabilities) { + return updatedGroupTypeCapabilities != null? updatedGroupTypeCapabilities.entrySet().stream() + .filter(entry -> !oldCapabilities.containsKey(entry.getKey())) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue) ): null; } - private Optional<TitanOperationStatus> connectToCapabilityType(GroupTypeData groupTypeData, List<CapabilityTypeDefinition> groupCapTypes) { - return groupCapTypes.stream() - .map(groupCapTypeDef -> connectTo(groupTypeData, groupCapTypeDef)) + private TitanOperationStatus createCapabilities(GroupTypeData groupTypeData, Map<String, CapabilityDefinition> groupCapabilities) { + if (MapUtils.isEmpty(groupCapabilities)) { + return TitanOperationStatus.OK; + } + + return groupCapabilities.values().stream() + .map(v -> createCapability(groupTypeData, v)) .filter(Either::isRight) .findFirst() - .map(either -> either.right().value()); + .map(either -> either.right().value()) + .orElse(TitanOperationStatus.OK); + } + + private Either<GraphRelation, TitanOperationStatus> createCapability(GroupTypeData groupTypeData, CapabilityDefinition capabilityDef) { + Either<CapabilityTypeDefinition, TitanOperationStatus> eitherCapData = capabilityTypeOperation.getCapabilityTypeByType(capabilityDef.getType()); + return eitherCapData + .left() + .map(CapabilityTypeData::new) + .left() + .bind(capTypeData -> capabilityOperation.addCapabilityToGraph(groupTypeData.getUniqueId(), capTypeData, capabilityDef)) + .left() + .bind(capData -> connectToCapability(groupTypeData, capData, capabilityDef.getName())); } - private Either<GraphRelation, TitanOperationStatus> connectTo(GroupTypeData groupTypeData, CapabilityTypeDefinition groupCapTypeDef) { - Either<CapabilityTypeData, TitanOperationStatus> eitherCapData = capabilityTypeOperation.getCapabilityTypeByType(groupCapTypeDef.getType()); - if (eitherCapData.isLeft()) { - return titanGenericDao.createRelation(groupTypeData, eitherCapData.left().value(), GraphEdgeLabels.GROUP_TYPE_CAPABILITY_TYPE, null); + + /** + * Get capability with all relevant properties + * @param groupTypeId + * @return + */ + private Either<List<CapabilityDefinition>, StorageOperationStatus> getCapablities(String groupTypeId) { + Either<List<ImmutablePair<CapabilityData, GraphEdge>>, TitanOperationStatus> groupCapabilitiesOnGraph = + titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupType), groupTypeId, GraphEdgeLabels.GROUP_TYPE_CAPABILITY, NodeTypeEnum.Capability, CapabilityData.class, true); + + if (groupCapabilitiesOnGraph.isRight()) { + TitanOperationStatus capabilityStatus = groupCapabilitiesOnGraph.right().value(); + if (capabilityStatus == TitanOperationStatus.NOT_FOUND) { + return Either.left(Collections.emptyList()); + } + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(capabilityStatus)); } - return Either.right(eitherCapData.right().value()); + List<ImmutablePair<CapabilityData, GraphEdge>> groupCapabilites = groupCapabilitiesOnGraph.left().value(); + groupCapabilites.forEach(this::fillCapabilityName); + + return capabilityOperation.getCapabilitiesWithProps(groupCapabilites) + .right() + .map(DaoStatusConverter::convertTitanStatusToStorageStatus); + } + + private void fillCapabilityName(ImmutablePair<CapabilityData, GraphEdge> pair) { + pair.getLeft().getCapabilityDataDefinition().setName((String)pair.getRight().getProperties().get(GraphEdgePropertiesDictionary.NAME.getProperty())); } + private Either<GraphRelation, TitanOperationStatus> connectToCapability(GroupTypeData groupTypeData, CapabilityData capabilityData, String capabilityName) { + Map<String, Object> properties = new HashMap<>(); + properties.put(GraphEdgePropertiesDictionary.NAME.getProperty(), capabilityName); + + return titanGenericDao.createRelation(groupTypeData, capabilityData, GraphEdgeLabels.GROUP_TYPE_CAPABILITY, properties); + } + + public List<GroupTypeDefinition> getAllGroupTypes(Set<String> excludedGroupTypes) { Map<String, Map.Entry<TitanPredicate, Object>> predicateCriteria = buildNotInPredicate(GraphPropertiesDictionary.TYPE.getProperty(), excludedGroupTypes); List<GroupTypeData> groupTypes = titanGenericDao.getByCriteriaWithPredicate(NodeTypeEnum.GroupType, predicateCriteria, GroupTypeData.class) .left() - .on(this::onTitanAccessError); - + .on(operationUtils::onTitanOperationFailure); return convertGroupTypesToDefinition(groupTypes); } @@ -199,54 +316,44 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO .collect(Collectors.toList()); } - private List<GroupTypeData> onTitanAccessError(TitanOperationStatus toe) { - throw new StorageException( - DaoStatusConverter.convertTitanStatusToStorageStatus(toe)); - } - - - public Either<GroupTypeDefinition, TitanOperationStatus> getGroupTypeByUid(String uniqueId) { - Either<GroupTypeDefinition, TitanOperationStatus> result = null; + public Either<GroupTypeDefinition, StorageOperationStatus> getGroupTypeByUid(String uniqueId) { + log.debug("#getGroupTypeByUid - fetching group type with id {}", uniqueId); + return titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupType), uniqueId, GroupTypeData.class) + .right() + .map(DaoStatusConverter::convertTitanStatusToStorageStatus) + .left() + .bind(groupType -> buildGroupTypeDefinition(uniqueId, groupType)); + } - Either<GroupTypeData, TitanOperationStatus> groupTypesRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.GroupType), uniqueId, GroupTypeData.class); + @Override + public Either<GroupTypeDefinition, StorageOperationStatus> getGroupType(String uniqueId, boolean inTransaction) { + Either<GroupTypeDefinition, StorageOperationStatus> result = null; + try { - if (groupTypesRes.isRight()) { - TitanOperationStatus status = groupTypesRes.right().value(); - log.debug("Group type {} cannot be found in graph. status is {}", uniqueId, status); - return Either.right(status); - } + Either<GroupTypeDefinition, StorageOperationStatus> ctResult = getGroupTypeByUid(uniqueId); - GroupTypeData gtData = groupTypesRes.left().value(); - GroupTypeDefinition groupTypeDefinition = new GroupTypeDefinition(gtData.getGroupTypeDataDefinition()); + if (ctResult.isRight()) { + StorageOperationStatus status = ctResult.right().value(); + if (status != StorageOperationStatus.NOT_FOUND) { + log.error("Failed to retrieve information on element uniqueId: {}. status is {}", uniqueId, status); + } + result = Either.right(ctResult.right().value()); + return result; + } - TitanOperationStatus propertiesStatus = propertyOperation.fillProperties(uniqueId, NodeTypeEnum.GroupType, properList -> groupTypeDefinition.setProperties(properList)); + result = Either.left(ctResult.left().value()); - if (propertiesStatus != TitanOperationStatus.OK) { - log.error("Failed to fetch properties of capability type {}", uniqueId); - return Either.right(propertiesStatus); + return result; + } finally { + titanGenericDao.handleTransactionCommitRollback(inTransaction, result); } - result = Either.left(groupTypeDefinition); - - return result; - } - - @Override - public Either<GroupTypeDefinition, StorageOperationStatus> getGroupType(String uniqueId) { - - return getGroupType(uniqueId, false); - - } - - @Override - public Either<GroupTypeDefinition, StorageOperationStatus> getGroupType(String uniqueId, boolean inTransaction) { - return getElementType(this::getGroupTypeByUid, uniqueId, inTransaction); } @Override public Either<GroupTypeDefinition, StorageOperationStatus> getLatestGroupTypeByType(String type) { - return getLatestGroupTypeByType(type, false); + return getLatestGroupTypeByType(type, true); } @Override @@ -268,21 +375,98 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO return result; } - Either<List<GroupTypeData>, TitanOperationStatus> groupTypeEither = titanGenericDao.getByCriteria(NodeTypeEnum.GroupType, properties, GroupTypeData.class); + Either<List<GroupTypeData>, StorageOperationStatus> groupTypeEither = titanGenericDao.getByCriteria(NodeTypeEnum.GroupType, properties, GroupTypeData.class) + .right() + .map(DaoStatusConverter::convertTitanStatusToStorageStatus); if (groupTypeEither.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(groupTypeEither.right().value())); + result = Either.right(groupTypeEither.right().value()); } else { - GroupTypeDataDefinition dataDefinition = groupTypeEither.left().value().stream().map(e -> e.getGroupTypeDataDefinition()).findFirst().get(); - result = getGroupType(dataDefinition.getUniqueId(), inTransaction); - } + GroupTypeDataDefinition dataDefinition = groupTypeEither.left().value().stream() + .map(GroupTypeData::getGroupTypeDataDefinition) + .findFirst() + .get(); + result = getGroupTypeByUid(dataDefinition.getUniqueId()); + } return result; } finally { - handleTransactionCommitRollback(inTransaction, result); + titanGenericDao.handleTransactionCommitRollback(inTransaction, result); } } + private Either<GroupTypeDefinition, StorageOperationStatus> buildGroupTypeDefinition(String uniqueId, GroupTypeData groupTypeNode) { + GroupTypeDefinition groupType = new GroupTypeDefinition(groupTypeNode.getGroupTypeDataDefinition()); + return fillDerivedFrom(uniqueId, groupType) + .left() + .map(derivedFrom -> fillProperties(uniqueId, groupType, derivedFrom)) + .left() + .bind(props -> fillCapabilities(uniqueId, groupType)); + } + + private Either<GroupTypeDefinition, StorageOperationStatus> fillCapabilities(String uniqueId, GroupTypeDefinition groupType) { + return getCapablities(uniqueId) + .left() + .map(capabilities -> { + groupType.setCapabilities(asCapabilitiesMap(capabilities)); + return groupType; + }); + } + + private Either<GroupTypeData, StorageOperationStatus> fillDerivedFrom(String uniqueId, GroupTypeDefinition groupType) { + log.debug("#fillDerivedFrom - fetching group type {} derived node", groupType.getType()); + return derivedFromOperation.getDerivedFromChild(uniqueId, NodeTypeEnum.GroupType, GroupTypeData.class) + .right() + .bind(this::handleDerivedFromNotExist) + .left() + .map(derivedFrom -> setDerivedFrom(groupType, derivedFrom)); + + } + + private Either<List<PropertyDefinition>, StorageOperationStatus> fillProperties(String uniqueId, GroupTypeDefinition groupType, GroupTypeData derivedFromNode) { + log.debug("#fillProperties - fetching all properties for group type {}", groupType.getType()); + return propertyOperation.findPropertiesOfNode(NodeTypeEnum.GroupType, uniqueId) + .right() + .bind(this::handleGroupTypeHasNoProperties) + .left() + .bind(propsMap -> fillDerivedFromProperties(groupType, derivedFromNode, new ArrayList<>(propsMap.values()))); + } + + Either<Map<String, PropertyDefinition>, StorageOperationStatus> handleGroupTypeHasNoProperties(TitanOperationStatus err) { + if (err == TitanOperationStatus.NOT_FOUND) { + return Either.left(new HashMap<>()); + } + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(err)); + } + + private Either<List<PropertyDefinition>, StorageOperationStatus> fillDerivedFromProperties(GroupTypeDefinition groupType, GroupTypeData derivedFromNode, List<PropertyDefinition> groupTypeDirectProperties) { + if (derivedFromNode == null) { + groupType.setProperties(groupTypeDirectProperties); + return Either.left(groupTypeDirectProperties); + } + log.debug("#fillDerivedFromProperties - fetching all properties of derived from chain for group type {}", groupType.getType()); + return propertyOperation.getAllPropertiesRec(derivedFromNode.getUniqueId(), NodeTypeEnum.GroupType, GroupTypeData.class) + .left() + .map(derivedFromProps -> {groupTypeDirectProperties.addAll(derivedFromProps); return groupTypeDirectProperties;}) + .left() + .map(allProps -> {groupType.setProperties(allProps);return allProps;}); + } + + private Either<GroupTypeData, StorageOperationStatus> handleDerivedFromNotExist(StorageOperationStatus err) { + if (err == StorageOperationStatus.NOT_FOUND) { + return Either.left(null); + } + return Either.right(err); + } + + private GroupTypeData setDerivedFrom(GroupTypeDefinition groupTypeDefinition, GroupTypeData derivedFrom) { + if (derivedFrom != null) { + groupTypeDefinition.setDerivedFrom(derivedFrom.getGroupTypeDataDefinition().getType()); + } + return derivedFrom; + } + + @Override public Either<GroupTypeDefinition, StorageOperationStatus> getGroupTypeByTypeAndVersion(String type, String version) { return getGroupTypeByTypeAndVersion(type, version, false); @@ -313,7 +497,7 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO log.debug("Got group type {}", groupTypeDefinition); - String ctUniqueId = UniqueIdBuilder.buildGroupTypeUid(groupTypeDefinition.getType(), groupTypeDefinition.getVersion()); + String ctUniqueId = UniqueIdBuilder.buildGroupTypeUid(groupTypeDefinition.getType(), groupTypeDefinition.getVersion(), "grouptype"); GroupTypeData groupTypeData = buildGroupTypeData(groupTypeDefinition, ctUniqueId); @@ -343,6 +527,14 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO return Either.right(createRelation.right().value()); } } + + Map<String, CapabilityDefinition> groupCapTypes = groupTypeDefinition.getCapabilities(); + if (!MapUtils.isEmpty(groupCapTypes)) { + TitanOperationStatus status = createCapabilities(groupTypeData, groupCapTypes); + if (status != TitanOperationStatus.OK) { + return Either.right(status); + } + } return Either.left(createGTResult.left().value()); @@ -369,55 +561,6 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO } } - - private Either<GroupTypeDefinition, StorageOperationStatus> ensureExsitanceDerivedFromEdge(GroupTypeDefinition groupTypeDefinition) { - Either<GroupTypeDefinition, StorageOperationStatus> result = Either.left(groupTypeDefinition); - - GroupTypeData childGroupType = null; - GroupTypeData parentGroupType = null; - - Either<GroupTypeData, TitanOperationStatus> childGroupTypeResult = - titanGenericDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), groupTypeDefinition.getType(), GroupTypeData.class); - if (childGroupTypeResult.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(childGroupTypeResult.right().value())); - log.debug("Filed to find GroupType with type {}, status is {}.", groupTypeDefinition.getType(), childGroupTypeResult); - } else { - childGroupType = childGroupTypeResult.left().value(); - } - - - if (result.isLeft()) { - Either<GroupTypeData, TitanOperationStatus> parentGroupTypeResult = - titanGenericDao.getNode(GraphPropertiesDictionary.TYPE.getProperty(), groupTypeDefinition.getDerivedFrom(), GroupTypeData.class); - if (parentGroupTypeResult.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentGroupTypeResult.right().value())); - log.debug("Filed to find GroupType with type {}, status is {}.", groupTypeDefinition.getDerivedFrom(), parentGroupTypeResult); - } else { - parentGroupType = parentGroupTypeResult.left().value(); - } - } - - - if (childGroupType != null && parentGroupType != null) { - Either<Edge, TitanOperationStatus> edgeDerivedFromResult = titanGenericDao.getEdgeByNodes(childGroupType, parentGroupType, GraphEdgeLabels.DERIVED_FROM); - if (edgeDerivedFromResult.isLeft()) { - log.debug("It was found relation {}. Don't need to create the edge.", edgeDerivedFromResult.left().value()); - } else { - Either<GraphRelation, TitanOperationStatus> createRelationResult = titanGenericDao.createRelation(childGroupType, parentGroupType, GraphEdgeLabels.DERIVED_FROM, null); - log.debug("After create relation between Group Type with id {} to its parent with id {}, status is {}.", - childGroupType.getKeyValueId().getValue(), parentGroupType.getKeyValueId().getValue(), createRelationResult); - if (createRelationResult.isRight()) { - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createRelationResult.right().value())); - } - } - - } - - - return result; - } - - private GroupTypeData buildGroupTypeData(GroupTypeDefinition groupTypeDefinition, String ctUniqueId) { GroupTypeData groupTypeData = new GroupTypeData(groupTypeDefinition); @@ -434,7 +577,7 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO } public Either<Boolean, StorageOperationStatus> isCapabilityTypeDerivedFrom(String childCandidateType, String parentCandidateType) { - Map<String, Object> propertiesToMatch = new HashMap<String, Object>(); + Map<String, Object> propertiesToMatch = new HashMap<>(); propertiesToMatch.put(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.CapabilityType), childCandidateType); Either<List<CapabilityTypeData>, TitanOperationStatus> getResponse = titanGenericDao.getByCriteria(NodeTypeEnum.CapabilityType, propertiesToMatch, CapabilityTypeData.class); if (getResponse.isRight()) { @@ -454,7 +597,7 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO log.debug("Couldn't fetch derived from node for capability type {}, error: {}", childCandidateType, titanOperationStatus); return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(titanOperationStatus)); } else { - log.debug("Derived from node is not found for type {} - this is OK for root capability."); + log.debug("Derived from node is not found for type {} - this is OK for root capability.", childCandidateType); return Either.left(false); } } @@ -471,20 +614,99 @@ public class GroupTypeOperation extends AbstractOperation implements IGroupTypeO log.error("Detected a cycle of \"derived from\" edges starting at capability type node {}", childUniqueId); return Either.right(StorageOperationStatus.GENERAL_ERROR); } - + /** - * FOR TEST ONLY - * - * @param propertyOperation + * @param list + * @return */ - public void setPropertyOperation(PropertyOperation propertyOperation) { - this.propertyOperation = propertyOperation; + private Map<String, CapabilityDefinition> asCapabilitiesMap(List<CapabilityDefinition> list) { + return list.stream() + .collect(Collectors.toMap(CapabilityDefinition::getName, Function.identity())); } - @Override - public Either<GroupTypeData, TitanOperationStatus> getLatestGroupTypeByNameFromGraph(String name) { - return null; + private Either<GroupTypeDefinition, StorageOperationStatus> updateGroupTypeOnGraph(GroupTypeDefinition updatedGroupType, GroupTypeDefinition currGroupType) { + updateGroupTypeData(updatedGroupType, currGroupType); + return titanGenericDao.updateNode(new GroupTypeData(updatedGroupType), GroupTypeData.class) + .right() + .map(DaoStatusConverter::convertTitanStatusToStorageStatus) + .left() + .bind(updatedNode -> updateGroupProperties(updatedGroupType.getUniqueId(), updatedGroupType.getProperties())) + .left() + .bind(updatedProperties -> updateGroupDerivedFrom(updatedGroupType, currGroupType.getDerivedFrom())) + .right() + .bind(result -> TypeOperations.mapOkStatus(result, null)) + .left() + .bind(updatedDerivedFrom -> TypeOperations.mapOkStatus(mergeCapabilities(updatedGroupType), updatedGroupType)) + .left() + .bind(def -> getGroupTypeByUid(def.getUniqueId())); + } + + + private Either<Map<String, PropertyData>, StorageOperationStatus> updateGroupProperties(String groupId, List<PropertyDefinition> properties) { + log.debug("#updateGroupProperties - updating group type properties for group type with id {}", groupId); + Map<String, PropertyDefinition> mapProperties = properties != null? properties.stream() + .collect(Collectors.toMap(PropertyDefinition::getName, Function.identity())): null; + return propertyOperation.mergePropertiesAssociatedToNode(NodeTypeEnum.GroupType, groupId, mapProperties) + .right() + .map(DaoStatusConverter::convertTitanStatusToStorageStatus); + } + + + + private Either<GraphRelation, StorageOperationStatus> updateGroupDerivedFrom(GroupTypeDefinition updatedGroupType, String currDerivedFromGroupType) { + + String groupTypeId = updatedGroupType.getUniqueId(); + if (StringUtils.equals(updatedGroupType.getDerivedFrom(), currDerivedFromGroupType)) { + return Strings.isNullOrEmpty(currDerivedFromGroupType)? + Either.right(StorageOperationStatus.OK): + getLatestGroupTypeByType(currDerivedFromGroupType, true) + .left() + .map(def -> null); + } + + StorageOperationStatus status = isLegalToReplaceParent(currDerivedFromGroupType, updatedGroupType.getDerivedFrom(), updatedGroupType.getType()); + if ( status != StorageOperationStatus.OK) { + return Either.right(status); + } + + log.debug("#updateGroupDerivedFrom - updating group derived from relation for group type with id {}. old derived type {}. new derived type {}", groupTypeId, currDerivedFromGroupType, updatedGroupType.getDerivedFrom()); + StorageOperationStatus deleteDerivedRelationStatus = deleteDerivedFromGroupType(groupTypeId, currDerivedFromGroupType); + if (deleteDerivedRelationStatus != StorageOperationStatus.OK) { + return Either.right(deleteDerivedRelationStatus); + } + return addDerivedFromRelation(updatedGroupType, groupTypeId); + } + + private StorageOperationStatus isLegalToReplaceParent(String oldTypeParent, String newTypeParent, String childType) { + return derivedFromOperation.isUpdateParentAllowed(oldTypeParent, newTypeParent, childType, NodeTypeEnum.GroupType, GroupTypeData.class, t -> t.getGroupTypeDataDefinition().getType()); + } + + private Either<GraphRelation, StorageOperationStatus> addDerivedFromRelation(GroupTypeDataDefinition groupTypeDef, String gtUniqueId) { + String derivedFrom = groupTypeDef.getDerivedFrom(); + if (derivedFrom == null) { + return Either.left(null); + } + log.debug("#addDerivedFromRelationBefore - adding derived from relation between group type {} to its parent {}", groupTypeDef.getType(), derivedFrom); + return this.getLatestGroupTypeByType(derivedFrom, true) + .left() + .bind(derivedFromGroup -> derivedFromOperation.addDerivedFromRelation(gtUniqueId, derivedFromGroup.getUniqueId(), NodeTypeEnum.GroupType)); + } + + private StorageOperationStatus deleteDerivedFromGroupType(String groupTypeId, String derivedFromType) { + if (derivedFromType == null) { + return StorageOperationStatus.OK; + } + log.debug("#deleteDerivedFromGroupType - deleting derivedFrom relation for group type with id {} and its derived type {}", groupTypeId, derivedFromType); + return getLatestGroupTypeByType(derivedFromType, true) + .either(derivedFromNode -> derivedFromOperation.removeDerivedFromRelation(groupTypeId, derivedFromNode.getUniqueId(), NodeTypeEnum.GroupType), + err -> err); + } + + private void updateGroupTypeData(GroupTypeDefinition updatedTypeDefinition, GroupTypeDefinition currTypeDefinition) { + updatedTypeDefinition.setUniqueId(currTypeDefinition.getUniqueId()); + updatedTypeDefinition.setCreationTime(currTypeDefinition.getCreationTime()); + updatedTypeDefinition.setModificationTime(System.currentTimeMillis()); } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/HeatParametersOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/HeatParametersOperation.java index 7b7ead5a19..6d050afb2c 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/HeatParametersOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/HeatParametersOperation.java @@ -20,11 +20,7 @@ package org.openecomp.sdc.be.model.operations.impl; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.tinkerpop.gremlin.structure.Edge; import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge; @@ -43,432 +39,432 @@ import org.openecomp.sdc.be.model.tosca.validators.PropertyTypeValidator; 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.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.stereotype.Component; -import fj.data.Either; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; @Component("heat-parameter-operation") public class HeatParametersOperation implements IHeatParametersOperation { - public static final String EMPTY_VALUE = null; + public static final String EMPTY_VALUE = null; + + private static final Logger log = Logger.getLogger(HeatParametersOperation.class.getName()); + + @javax.annotation.Resource + private TitanGenericDao titanGenericDao; + + public TitanGenericDao getTitanGenericDao() { + return titanGenericDao; + } + + public void setTitanGenericDao(TitanGenericDao titanGenericDao) { + this.titanGenericDao = titanGenericDao; + } + + public StorageOperationStatus getHeatParametersOfNode(NodeTypeEnum nodeType, String uniqueId, List<HeatParameterDefinition> properties) { + + Either<List<ImmutablePair<HeatParameterData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, GraphEdgeLabels.HEAT_PARAMETER, NodeTypeEnum.HeatParameter, + HeatParameterData.class); + + if (childrenNodes.isRight()) { + TitanOperationStatus status = childrenNodes.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.OK; + } + return DaoStatusConverter.convertTitanStatusToStorageStatus(status); + } + + List<ImmutablePair<HeatParameterData, GraphEdge>> values = childrenNodes.left().value(); + if (values != null) { + + for (ImmutablePair<HeatParameterData, GraphEdge> immutablePair : values) { + GraphEdge edge = immutablePair.getValue(); + String propertyName = (String) edge.getProperties().get(GraphPropertiesDictionary.NAME.getProperty()); + if (log.isDebugEnabled()) + log.debug("Property {} is associated to node {}", propertyName, uniqueId); + HeatParameterData propertyData = immutablePair.getKey(); + HeatParameterDefinition propertyDefinition = convertParameterDataToParameterDefinition(propertyData, propertyName, uniqueId); - private static Logger log = LoggerFactory.getLogger(HeatParametersOperation.class.getName()); + properties.add(propertyDefinition); - @javax.annotation.Resource - private TitanGenericDao titanGenericDao; + if (log.isTraceEnabled()) { + log.trace("getHeatParametersOfNode - property {} associated to node {}", propertyDefinition, uniqueId); + } + } - public TitanGenericDao getTitanGenericDao() { - return titanGenericDao; - } + } - public void setTitanGenericDao(TitanGenericDao titanGenericDao) { - this.titanGenericDao = titanGenericDao; - } + return StorageOperationStatus.OK; + } - public StorageOperationStatus getHeatParametersOfNode(NodeTypeEnum nodeType, String uniqueId, List<HeatParameterDefinition> properties) { + public StorageOperationStatus getParametersValueNodes(NodeTypeEnum parentNodeType, String parentUniqueId, List<HeatParameterValueData> heatValues) { - Either<List<ImmutablePair<HeatParameterData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, GraphEdgeLabels.HEAT_PARAMETER, NodeTypeEnum.HeatParameter, - HeatParameterData.class); + Either<List<ImmutablePair<HeatParameterValueData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(parentNodeType), parentUniqueId, GraphEdgeLabels.PARAMETER_VALUE, + NodeTypeEnum.HeatParameterValue, HeatParameterValueData.class); - if (childrenNodes.isRight()) { - TitanOperationStatus status = childrenNodes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.OK; - } - return DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } + if (childrenNodes.isRight()) { + TitanOperationStatus status = childrenNodes.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.OK; + } + return DaoStatusConverter.convertTitanStatusToStorageStatus(status); + } - List<ImmutablePair<HeatParameterData, GraphEdge>> values = childrenNodes.left().value(); - if (values != null) { + List<ImmutablePair<HeatParameterValueData, GraphEdge>> values = childrenNodes.left().value(); + if (values != null) { - for (ImmutablePair<HeatParameterData, GraphEdge> immutablePair : values) { - GraphEdge edge = immutablePair.getValue(); - String propertyName = (String) edge.getProperties().get(GraphPropertiesDictionary.NAME.getProperty()); - if (log.isDebugEnabled()) - log.debug("Property {} is associated to node {}", propertyName, uniqueId); - HeatParameterData propertyData = immutablePair.getKey(); - HeatParameterDefinition propertyDefinition = convertParameterDataToParameterDefinition(propertyData, propertyName, uniqueId); + for (ImmutablePair<HeatParameterValueData, GraphEdge> immutablePair : values) { + GraphEdge edge = immutablePair.getValue(); + String propertyName = (String) edge.getProperties().get(GraphPropertiesDictionary.NAME.getProperty()); + log.trace("Heat value {} is associated to node {}", propertyName,parentUniqueId); + HeatParameterValueData propertyData = immutablePair.getKey(); - properties.add(propertyDefinition); + heatValues.add(propertyData); + } - if (log.isTraceEnabled()) { - log.trace("getHeatParametersOfNode - property {} associated to node {}", propertyDefinition, uniqueId); - } - } + } - } + return StorageOperationStatus.OK; + } - return StorageOperationStatus.OK; - } + @Override + public Either<List<HeatParameterDefinition>, StorageOperationStatus> deleteAllHeatParametersAssociatedToNode(NodeTypeEnum nodeType, String uniqueId) { - public StorageOperationStatus getParametersValueNodes(NodeTypeEnum parentNodeType, String parentUniqueId, List<HeatParameterValueData> heatValues) { + List<HeatParameterDefinition> heatParams = new ArrayList<>(); + StorageOperationStatus propertiesOfNodeRes = getHeatParametersOfNode(nodeType, uniqueId, heatParams); - Either<List<ImmutablePair<HeatParameterValueData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(parentNodeType), parentUniqueId, GraphEdgeLabels.PARAMETER_VALUE, - NodeTypeEnum.HeatParameterValue, HeatParameterValueData.class); + if (!propertiesOfNodeRes.equals(StorageOperationStatus.OK) && !propertiesOfNodeRes.equals(StorageOperationStatus.NOT_FOUND)) { + return Either.right(propertiesOfNodeRes); + } - if (childrenNodes.isRight()) { - TitanOperationStatus status = childrenNodes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.OK; - } - return DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } + for (HeatParameterDefinition propertyDefinition : heatParams) { - List<ImmutablePair<HeatParameterValueData, GraphEdge>> values = childrenNodes.left().value(); - if (values != null) { + String propertyUid = propertyDefinition.getUniqueId(); + Either<HeatParameterData, TitanOperationStatus> deletePropertyRes = deleteHeatParameterFromGraph(propertyUid); + if (deletePropertyRes.isRight()) { + log.error("Failed to delete heat parameter with id {}", propertyUid); + TitanOperationStatus status = deletePropertyRes.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } - for (ImmutablePair<HeatParameterValueData, GraphEdge> immutablePair : values) { - GraphEdge edge = immutablePair.getValue(); - String propertyName = (String) edge.getProperties().get(GraphPropertiesDictionary.NAME.getProperty()); - log.trace("Heat value {} is associated to node {}", propertyName,parentUniqueId); - HeatParameterValueData propertyData = immutablePair.getKey(); + } - heatValues.add(propertyData); - } + log.debug("The heat parameters deleted from node {} are {}", uniqueId, heatParams); + return Either.left(heatParams); + } - } + @Override + public StorageOperationStatus deleteAllHeatValuesAssociatedToNode(NodeTypeEnum parentNodeType, String parentUniqueId) { - return StorageOperationStatus.OK; - } + List<HeatParameterValueData> heatValues = new ArrayList<>(); + StorageOperationStatus propertiesOfNodeRes = getParametersValueNodes(parentNodeType, parentUniqueId, heatValues); - @Override - public Either<List<HeatParameterDefinition>, StorageOperationStatus> deleteAllHeatParametersAssociatedToNode(NodeTypeEnum nodeType, String uniqueId) { + if (!propertiesOfNodeRes.equals(StorageOperationStatus.OK) && !propertiesOfNodeRes.equals(StorageOperationStatus.NOT_FOUND)) { + return propertiesOfNodeRes; + } - List<HeatParameterDefinition> heatParams = new ArrayList<HeatParameterDefinition>(); - StorageOperationStatus propertiesOfNodeRes = getHeatParametersOfNode(nodeType, uniqueId, heatParams); + for (HeatParameterValueData propertyDefinition : heatValues) { - if (!propertiesOfNodeRes.equals(StorageOperationStatus.OK) && !propertiesOfNodeRes.equals(StorageOperationStatus.NOT_FOUND)) { - return Either.right(propertiesOfNodeRes); - } + String propertyUid = (String) propertyDefinition.getUniqueId(); + Either<HeatParameterValueData, TitanOperationStatus> deletePropertyRes = deleteHeatParameterValueFromGraph(propertyUid); + if (deletePropertyRes.isRight()) { + log.error("Failed to delete heat parameter value with id {}", propertyUid); + TitanOperationStatus status = deletePropertyRes.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + return DaoStatusConverter.convertTitanStatusToStorageStatus(status); + } - for (HeatParameterDefinition propertyDefinition : heatParams) { + } - String propertyUid = propertyDefinition.getUniqueId(); - Either<HeatParameterData, TitanOperationStatus> deletePropertyRes = deleteHeatParameterFromGraph(propertyUid); - if (deletePropertyRes.isRight()) { - log.error("Failed to delete heat parameter with id {}", propertyUid); - TitanOperationStatus status = deletePropertyRes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } + log.debug("The heat values deleted from node {} are {}" , parentUniqueId, heatValues); + return StorageOperationStatus.OK; + } - } + private Either<HeatParameterData, TitanOperationStatus> deleteHeatParameterFromGraph(String propertyId) { + log.debug("Before deleting heat parameter from graph {}" , propertyId); + return titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.HeatParameter), propertyId, HeatParameterData.class); + } - log.debug("The heat parameters deleted from node {} are {}", uniqueId, heatParams); - return Either.left(heatParams); - } + private Either<HeatParameterValueData, TitanOperationStatus> deleteHeatParameterValueFromGraph(String propertyId) { + log.debug("Before deleting heat parameter from graph {}" , propertyId); + return titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.HeatParameterValue), propertyId, HeatParameterValueData.class); + } - @Override - public StorageOperationStatus deleteAllHeatValuesAssociatedToNode(NodeTypeEnum parentNodeType, String parentUniqueId) { + @Override + public StorageOperationStatus addPropertiesToGraph(List<HeatParameterDefinition> properties, String parentId, NodeTypeEnum nodeType) { - List<HeatParameterValueData> heatValues = new ArrayList<HeatParameterValueData>(); - StorageOperationStatus propertiesOfNodeRes = getParametersValueNodes(parentNodeType, parentUniqueId, heatValues); + if (properties != null) { + for (HeatParameterDefinition propertyDefinition : properties) { - if (!propertiesOfNodeRes.equals(StorageOperationStatus.OK) && !propertiesOfNodeRes.equals(StorageOperationStatus.NOT_FOUND)) { - return propertiesOfNodeRes; - } + String propertyName = propertyDefinition.getName(); - for (HeatParameterValueData propertyDefinition : heatValues) { + Either<HeatParameterData, TitanOperationStatus> addPropertyToGraph = addPropertyToGraph(propertyName, propertyDefinition, parentId, nodeType); - String propertyUid = (String) propertyDefinition.getUniqueId(); - Either<HeatParameterValueData, TitanOperationStatus> deletePropertyRes = deleteHeatParameterValueFromGraph(propertyUid); - if (deletePropertyRes.isRight()) { - log.error("Failed to delete heat parameter value with id {}", propertyUid); - TitanOperationStatus status = deletePropertyRes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - return DaoStatusConverter.convertTitanStatusToStorageStatus(status); - } + if (addPropertyToGraph.isRight()) { + return DaoStatusConverter.convertTitanStatusToStorageStatus(addPropertyToGraph.right().value()); + } + } + } - } + return StorageOperationStatus.OK; - log.debug("The heat values deleted from node {} are {}" , parentUniqueId, heatValues); - return StorageOperationStatus.OK; - } + } - private Either<HeatParameterData, TitanOperationStatus> deleteHeatParameterFromGraph(String propertyId) { - log.debug("Before deleting heat parameter from graph {}" , propertyId); - return titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.HeatParameter), propertyId, HeatParameterData.class); - } + @Override + public StorageOperationStatus updateHeatParameters(List<HeatParameterDefinition> properties) { - private Either<HeatParameterValueData, TitanOperationStatus> deleteHeatParameterValueFromGraph(String propertyId) { - log.debug("Before deleting heat parameter from graph {}" , propertyId); - return titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.HeatParameterValue), propertyId, HeatParameterValueData.class); - } + if (properties == null) { + return StorageOperationStatus.OK; + } + for (HeatParameterDefinition property : properties) { - @Override - public StorageOperationStatus addPropertiesToGraph(List<HeatParameterDefinition> properties, String parentId, NodeTypeEnum nodeType) { + HeatParameterData heatParameterData = new HeatParameterData(property); + Either<HeatParameterData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(heatParameterData, HeatParameterData.class); + if (updateNode.isRight()) { + log.debug("failed to update heat parameter in graph. id = {}", property.getUniqueId()); + return DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value()); + } + } - if (properties != null) { - for (HeatParameterDefinition propertyDefinition : properties) { + return StorageOperationStatus.OK; + } - String propertyName = propertyDefinition.getName(); - - Either<HeatParameterData, TitanOperationStatus> addPropertyToGraph = addPropertyToGraph(propertyName, propertyDefinition, parentId, nodeType); - - if (addPropertyToGraph.isRight()) { - return DaoStatusConverter.convertTitanStatusToStorageStatus(addPropertyToGraph.right().value()); - } - } - } - - return StorageOperationStatus.OK; - - } - - @Override - public StorageOperationStatus updateHeatParameters(List<HeatParameterDefinition> properties) { + public Either<HeatParameterData, TitanOperationStatus> addPropertyToGraph(String propertyName, HeatParameterDefinition propertyDefinition, String parentId, NodeTypeEnum nodeType) { - if (properties == null) { - return StorageOperationStatus.OK; - } - for (HeatParameterDefinition property : properties) { + UniqueIdData parentNode = new UniqueIdData(nodeType, parentId); - HeatParameterData heatParameterData = new HeatParameterData(property); - Either<HeatParameterData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(heatParameterData, HeatParameterData.class); - if (updateNode.isRight()) { - log.debug("failed to update heat parameter in graph. id = {}", property.getUniqueId()); - return DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value()); - } - } + propertyDefinition.setUniqueId(UniqueIdBuilder.buildHeatParameterUniqueId(parentId, propertyName)); + HeatParameterData propertyData = new HeatParameterData(propertyDefinition); - return StorageOperationStatus.OK; - } + log.debug("Before adding property to graph {}" , propertyData); + Either<HeatParameterData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(propertyData, HeatParameterData.class); + log.debug("After adding property to graph {}" , propertyData); + if (createNodeResult.isRight()) { + TitanOperationStatus operationStatus = createNodeResult.right().value(); + log.error("Failed to add property {} to graph. status is {}", propertyName, operationStatus); + return Either.right(operationStatus); + } - public Either<HeatParameterData, TitanOperationStatus> addPropertyToGraph(String propertyName, HeatParameterDefinition propertyDefinition, String parentId, NodeTypeEnum nodeType) { + Map<String, Object> props = new HashMap<>(); + props.put(GraphPropertiesDictionary.NAME.getProperty(), propertyName); + Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(parentNode, propertyData, GraphEdgeLabels.HEAT_PARAMETER, props); + if (createRelResult.isRight()) { + TitanOperationStatus operationStatus = createRelResult.right().value(); + log.error("Failed to associate {} {} to heat parameter {} in graph. status is {}", nodeType.getName(), parentId, propertyName, operationStatus); + return Either.right(operationStatus); + } - UniqueIdData parentNode = new UniqueIdData(nodeType, parentId); + return Either.left(createNodeResult.left().value()); - propertyDefinition.setUniqueId(UniqueIdBuilder.buildHeatParameterUniqueId(parentId, propertyName)); - HeatParameterData propertyData = new HeatParameterData(propertyDefinition); + } - log.debug("Before adding property to graph {}" , propertyData); - Either<HeatParameterData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(propertyData, HeatParameterData.class); - log.debug("After adding property to graph {}" , propertyData); - if (createNodeResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); - log.error("Failed to add property {} to graph. status is {}", propertyName, operationStatus); - return Either.right(operationStatus); - } + public StorageOperationStatus validateAndUpdateProperty(HeatParameterDefinition propertyDefinition) { - Map<String, Object> props = new HashMap<String, Object>(); - props.put(GraphPropertiesDictionary.NAME.getProperty(), propertyName); - Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(parentNode, propertyData, GraphEdgeLabels.HEAT_PARAMETER, props); - if (createRelResult.isRight()) { - TitanOperationStatus operationStatus = createRelResult.right().value(); - log.error("Failed to associate {} {} to heat parameter {} in graph. status is {}", nodeType.getName(), parentId, propertyName, operationStatus); - return Either.right(operationStatus); - } + log.trace("Going to validate property type and value. {}" , propertyDefinition); - return Either.left(createNodeResult.left().value()); + String propertyType = propertyDefinition.getType(); + HeatParameterType type = getType(propertyType); - } + if (type == null) { + log.info("The type {} of heat parameter is invalid", type); - public StorageOperationStatus validateAndUpdateProperty(HeatParameterDefinition propertyDefinition) { + return StorageOperationStatus.INVALID_TYPE; + } + propertyDefinition.setType(type.getType()); - log.trace("Going to validate property type and value. {}" , propertyDefinition); + log.trace("After validating property type {}", propertyType); - String propertyType = propertyDefinition.getType(); - HeatParameterType type = getType(propertyType); - - if (type == null) { - log.info("The type {} of heat parameter is invalid", type); - - return StorageOperationStatus.INVALID_TYPE; - } - propertyDefinition.setType(type.getType()); - - log.trace("After validating property type {}", propertyType); - - // validate default value - String defaultValue = propertyDefinition.getDefaultValue(); - boolean isValidProperty = isValidValue(type, defaultValue); - if (false == isValidProperty) { - log.info("The value {} of property from type {} is invalid", defaultValue, type); - return StorageOperationStatus.INVALID_VALUE; - } - - PropertyValueConverter converter = type.getConverter(); - - if (isEmptyValue(defaultValue)) { - log.debug("Default value was not sent for property {}. Set default value to {}", propertyDefinition.getName() , EMPTY_VALUE); - - propertyDefinition.setDefaultValue(EMPTY_VALUE); - } else if (false == isEmptyValue(defaultValue)) { - String convertedValue = converter.convert(defaultValue, null, null); - propertyDefinition.setDefaultValue(convertedValue); - } - - // validate current value - String value = propertyDefinition.getCurrentValue(); - isValidProperty = isValidValue(type, value); - if (false == isValidProperty) { - log.info("The value {} of property from type {} is invalid", value, type); - return StorageOperationStatus.INVALID_VALUE; - } - - if (isEmptyValue(value)) { - log.debug("Value was not sent for property {}. Set value to {}", propertyDefinition.getName(), EMPTY_VALUE); - - propertyDefinition.setCurrentValue(EMPTY_VALUE); - } else if (!value.equals("")) { - String convertedValue = converter.convert(value, null, null); - propertyDefinition.setCurrentValue(convertedValue); - } - - return StorageOperationStatus.OK; - } - - public HeatParameterDefinition convertParameterDataToParameterDefinition(HeatParameterData propertyDataResult, String propertyName, String resourceId) { - log.debug("convert to HeatParamereDefinition {}", propertyDataResult); - - HeatParameterDefinition propertyDefResult = new HeatParameterDefinition(propertyDataResult.getHeatDataDefinition()); - - propertyDefResult.setName(propertyName); - - return propertyDefResult; - } - - private HeatParameterType getType(String propertyType) { - - HeatParameterType type = HeatParameterType.isValidType(propertyType); - - return type; - - } - - protected boolean isValidValue(HeatParameterType type, String value) { - if (isEmptyValue(value)) { - return true; - } - - PropertyTypeValidator validator = type.getValidator(); - - boolean isValid = validator.isValid(value, null, null); - if (true == isValid) { - return true; - } else { - return false; - } - - } - - public boolean isEmptyValue(String value) { - if (value == null) { - return true; - } - return false; - } - - public boolean isNullParam(String value) { - if (value == null) { - return true; - } - return false; - } - - @Override - public Either<HeatParameterValueData, StorageOperationStatus> updateHeatParameterValue(HeatParameterDefinition heatParam, String artifactId, String resourceInstanceId, String artifactLabel) { - String heatEnvId = UniqueIdBuilder.buildHeatParameterValueUniqueId(resourceInstanceId, artifactLabel, heatParam.getName()); - Either<HeatParameterValueData, TitanOperationStatus> getNode = titanGenericDao.getNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), heatEnvId, HeatParameterValueData.class); - if (getNode.isRight() || getNode.left().value() == null) { - if (heatParam.getCurrentValue() == null || (heatParam.getDefaultValue() != null && heatParam.getCurrentValue().equals(heatParam.getDefaultValue()))) { - log.debug("Updated heat parameter value equals default value. No need to create heat parameter value for heat parameter {}", heatParam.getUniqueId()); - return Either.left(null); - } - return createHeatParameterValue(heatParam, artifactId, resourceInstanceId, artifactLabel); - } else { - heatParam.setUniqueId(heatEnvId); - return updateHeatParameterValue(heatParam); - } - } - - public Either<HeatParameterValueData, StorageOperationStatus> updateHeatParameterValue(HeatParameterDefinition heatParam) { - HeatParameterValueData heatParameterValue = new HeatParameterValueData(); - heatParameterValue.setUniqueId(heatParam.getUniqueId()); - if (heatParam.getCurrentValue() == null || (heatParam.getDefaultValue() != null && heatParam.getCurrentValue().equals(heatParam.getDefaultValue()))) { - Either<GraphRelation, TitanOperationStatus> deleteParameterValueIncomingRelation = titanGenericDao.deleteIncomingRelationByCriteria(heatParameterValue, GraphEdgeLabels.PARAMETER_VALUE, null); - if (deleteParameterValueIncomingRelation.isRight()) { - log.debug("Failed to delete heat parameter value incoming relation on graph. id = {}", heatParameterValue.getUniqueId()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(deleteParameterValueIncomingRelation.right().value())); - } - Either<Edge, TitanOperationStatus> getOutgoingRelation = titanGenericDao.getOutgoingEdgeByCriteria(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) heatParameterValue.getUniqueId(), GraphEdgeLabels.PARAMETER_IMPL, null); - if (getOutgoingRelation.isRight()) { - log.debug("Failed to get heat parameter value outgoing relation from graph. id = {}", heatParameterValue.getUniqueId()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getOutgoingRelation.right().value())); - } - Edge edge = getOutgoingRelation.left().value(); - if (edge == null) { - log.debug("Failed to get heat parameter value outgoing relation from graph. id = {}", heatParameterValue.getUniqueId()); - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - edge.remove(); - - Either<HeatParameterValueData, TitanOperationStatus> deleteNode = titanGenericDao.deleteNode(heatParameterValue, HeatParameterValueData.class); - if (deleteNode.isRight()) { - log.debug("Failed to delete heat parameter value on graph. id = {}", heatParameterValue.getUniqueId()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(deleteNode.right().value())); - } - return Either.left(deleteNode.left().value()); - } - heatParameterValue.setValue(heatParam.getCurrentValue()); - Either<HeatParameterValueData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(heatParameterValue, HeatParameterValueData.class); - if (updateNode.isRight()) { - log.debug("Failed to update heat parameter value in graph. id = {}", heatParameterValue.getUniqueId()); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value())); - } - return Either.left(updateNode.left().value()); - } - - public Either<HeatParameterValueData, StorageOperationStatus> createHeatParameterValue(HeatParameterDefinition heatParam, String artifactId, String resourceInstanceId, String artifactLabel) { - - Either<HeatParameterValueData, TitanOperationStatus> addHeatValueToGraph = addHeatValueToGraph(heatParam, artifactLabel, artifactId, resourceInstanceId); - if (addHeatValueToGraph.isRight()) { - log.debug("Failed to create heat parameters value on graph for artifact {}", artifactId); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(addHeatValueToGraph.right().value())); - } - return Either.left(addHeatValueToGraph.left().value()); - } - - public Either<HeatParameterValueData, TitanOperationStatus> addHeatValueToGraph(HeatParameterDefinition heatParameter, String artifactLabel, String artifactId, String resourceInstanceId) { - - UniqueIdData heatEnvNode = new UniqueIdData(NodeTypeEnum.ArtifactRef, artifactId); - HeatParameterValueData heatValueData = new HeatParameterValueData(); - heatValueData.setUniqueId(UniqueIdBuilder.buildHeatParameterValueUniqueId(resourceInstanceId, artifactLabel, heatParameter.getName())); - heatValueData.setValue(heatParameter.getCurrentValue()); - - log.debug("Before adding property to graph {}", heatValueData); - Either<HeatParameterValueData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(heatValueData, HeatParameterValueData.class); - log.debug("After adding property to graph {}", heatValueData); - if (createNodeResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); - log.error("Failed to add heat value {} to graph. status is {}", heatValueData.getUniqueId(), operationStatus); - return Either.right(operationStatus); - } - - Map<String, Object> props = new HashMap<String, Object>(); - props.put(GraphPropertiesDictionary.NAME.getProperty(), heatParameter.getName()); - Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(heatEnvNode, heatValueData, GraphEdgeLabels.PARAMETER_VALUE, props); - if (createRelResult.isRight()) { - TitanOperationStatus operationStatus = createRelResult.right().value(); - log.error("Failed to associate heat value {} to heat env artifact {} in graph. status is {}", heatValueData.getUniqueId(), artifactId, operationStatus); - return Either.right(operationStatus); - } - UniqueIdData heatParameterNode = new UniqueIdData(NodeTypeEnum.HeatParameter, heatParameter.getUniqueId()); - Either<GraphRelation, TitanOperationStatus> createRel2Result = titanGenericDao.createRelation(heatValueData, heatParameterNode, GraphEdgeLabels.PARAMETER_IMPL, null); - if (createRel2Result.isRight()) { - TitanOperationStatus operationStatus = createRel2Result.right().value(); - log.error("Failed to associate heat value {} to heat parameter {} in graph. status is {}", heatValueData.getUniqueId(), heatParameter.getName(), operationStatus); - return Either.right(operationStatus); - } - - return Either.left(createNodeResult.left().value()); - - } + // validate default value + String defaultValue = propertyDefinition.getDefaultValue(); + boolean isValidProperty = isValidValue(type, defaultValue); + if (!isValidProperty) { + log.info("The value {} of property from type {} is invalid", defaultValue, type); + return StorageOperationStatus.INVALID_VALUE; + } + + PropertyValueConverter converter = type.getConverter(); + + if (isEmptyValue(defaultValue)) { + log.debug("Default value was not sent for property {}. Set default value to {}", propertyDefinition.getName() , EMPTY_VALUE); + + propertyDefinition.setDefaultValue(EMPTY_VALUE); + } else if (!isEmptyValue(defaultValue)) { + String convertedValue = converter.convert(defaultValue, null, null); + propertyDefinition.setDefaultValue(convertedValue); + } + + // validate current value + String value = propertyDefinition.getCurrentValue(); + isValidProperty = isValidValue(type, value); + if (!isValidProperty) { + log.info("The value {} of property from type {} is invalid", value, type); + return StorageOperationStatus.INVALID_VALUE; + } + + if (isEmptyValue(value)) { + log.debug("Value was not sent for property {}. Set value to {}", propertyDefinition.getName(), EMPTY_VALUE); + + propertyDefinition.setCurrentValue(EMPTY_VALUE); + } else if (!value.equals("")) { + String convertedValue = converter.convert(value, null, null); + propertyDefinition.setCurrentValue(convertedValue); + } + + return StorageOperationStatus.OK; + } + + public HeatParameterDefinition convertParameterDataToParameterDefinition(HeatParameterData propertyDataResult, String propertyName, String resourceId) { + log.debug("convert to HeatParamereDefinition {}", propertyDataResult); + + HeatParameterDefinition propertyDefResult = new HeatParameterDefinition(propertyDataResult.getHeatDataDefinition()); + + propertyDefResult.setName(propertyName); + + return propertyDefResult; + } + + private HeatParameterType getType(String propertyType) { + + return HeatParameterType.isValidType(propertyType); + + } + + protected boolean isValidValue(HeatParameterType type, String value) { + if (isEmptyValue(value)) { + return true; + } + + PropertyTypeValidator validator = type.getValidator(); + + boolean isValid = validator.isValid(value, null, null); + if (isValid) { + return true; + } else { + return false; + } + + } + + public boolean isEmptyValue(String value) { + if (value == null) { + return true; + } + return false; + } + + public boolean isNullParam(String value) { + if (value == null) { + return true; + } + return false; + } + + @Override + public Either<HeatParameterValueData, StorageOperationStatus> updateHeatParameterValue(HeatParameterDefinition heatParam, String artifactId, String resourceInstanceId, String artifactLabel) { + String heatEnvId = UniqueIdBuilder.buildHeatParameterValueUniqueId(resourceInstanceId, artifactLabel, heatParam.getName()); + Either<HeatParameterValueData, TitanOperationStatus> getNode = titanGenericDao.getNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), heatEnvId, HeatParameterValueData.class); + if (getNode.isRight() || getNode.left().value() == null) { + if (heatParam.getCurrentValue() == null || (heatParam.getDefaultValue() != null && heatParam.getCurrentValue().equals(heatParam.getDefaultValue()))) { + log.debug("Updated heat parameter value equals default value. No need to create heat parameter value for heat parameter {}", heatParam.getUniqueId()); + return Either.left(null); + } + return createHeatParameterValue(heatParam, artifactId, resourceInstanceId, artifactLabel); + } else { + heatParam.setUniqueId(heatEnvId); + return updateHeatParameterValue(heatParam); + } + } + + public Either<HeatParameterValueData, StorageOperationStatus> updateHeatParameterValue(HeatParameterDefinition heatParam) { + HeatParameterValueData heatParameterValue = new HeatParameterValueData(); + heatParameterValue.setUniqueId(heatParam.getUniqueId()); + if (heatParam.getCurrentValue() == null || (heatParam.getDefaultValue() != null && heatParam.getCurrentValue().equals(heatParam.getDefaultValue()))) { + Either<GraphRelation, TitanOperationStatus> deleteParameterValueIncomingRelation = titanGenericDao.deleteIncomingRelationByCriteria(heatParameterValue, GraphEdgeLabels.PARAMETER_VALUE, null); + if (deleteParameterValueIncomingRelation.isRight()) { + log.debug("Failed to delete heat parameter value incoming relation on graph. id = {}", heatParameterValue.getUniqueId()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(deleteParameterValueIncomingRelation.right().value())); + } + Either<Edge, TitanOperationStatus> getOutgoingRelation = titanGenericDao.getOutgoingEdgeByCriteria(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) heatParameterValue.getUniqueId(), GraphEdgeLabels.PARAMETER_IMPL, null); + if (getOutgoingRelation.isRight()) { + log.debug("Failed to get heat parameter value outgoing relation from graph. id = {}", heatParameterValue.getUniqueId()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getOutgoingRelation.right().value())); + } + Edge edge = getOutgoingRelation.left().value(); + if (edge == null) { + log.debug("Failed to get heat parameter value outgoing relation from graph. id = {}", heatParameterValue.getUniqueId()); + return Either.right(StorageOperationStatus.GENERAL_ERROR); + } + edge.remove(); + + Either<HeatParameterValueData, TitanOperationStatus> deleteNode = titanGenericDao.deleteNode(heatParameterValue, HeatParameterValueData.class); + if (deleteNode.isRight()) { + log.debug("Failed to delete heat parameter value on graph. id = {}", heatParameterValue.getUniqueId()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(deleteNode.right().value())); + } + return Either.left(deleteNode.left().value()); + } + heatParameterValue.setValue(heatParam.getCurrentValue()); + Either<HeatParameterValueData, TitanOperationStatus> updateNode = titanGenericDao.updateNode(heatParameterValue, HeatParameterValueData.class); + if (updateNode.isRight()) { + log.debug("Failed to update heat parameter value in graph. id = {}", heatParameterValue.getUniqueId()); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateNode.right().value())); + } + return Either.left(updateNode.left().value()); + } + + public Either<HeatParameterValueData, StorageOperationStatus> createHeatParameterValue(HeatParameterDefinition heatParam, String artifactId, String resourceInstanceId, String artifactLabel) { + + Either<HeatParameterValueData, TitanOperationStatus> addHeatValueToGraph = addHeatValueToGraph(heatParam, artifactLabel, artifactId, resourceInstanceId); + if (addHeatValueToGraph.isRight()) { + log.debug("Failed to create heat parameters value on graph for artifact {}", artifactId); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(addHeatValueToGraph.right().value())); + } + return Either.left(addHeatValueToGraph.left().value()); + } + + public Either<HeatParameterValueData, TitanOperationStatus> addHeatValueToGraph(HeatParameterDefinition heatParameter, String artifactLabel, String artifactId, String resourceInstanceId) { + + UniqueIdData heatEnvNode = new UniqueIdData(NodeTypeEnum.ArtifactRef, artifactId); + HeatParameterValueData heatValueData = new HeatParameterValueData(); + heatValueData.setUniqueId(UniqueIdBuilder.buildHeatParameterValueUniqueId(resourceInstanceId, artifactLabel, heatParameter.getName())); + heatValueData.setValue(heatParameter.getCurrentValue()); + + log.debug("Before adding property to graph {}", heatValueData); + Either<HeatParameterValueData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(heatValueData, HeatParameterValueData.class); + log.debug("After adding property to graph {}", heatValueData); + if (createNodeResult.isRight()) { + TitanOperationStatus operationStatus = createNodeResult.right().value(); + log.error("Failed to add heat value {} to graph. status is {}", heatValueData.getUniqueId(), operationStatus); + return Either.right(operationStatus); + } + + Map<String, Object> props = new HashMap<>(); + props.put(GraphPropertiesDictionary.NAME.getProperty(), heatParameter.getName()); + Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(heatEnvNode, heatValueData, GraphEdgeLabels.PARAMETER_VALUE, props); + if (createRelResult.isRight()) { + TitanOperationStatus operationStatus = createRelResult.right().value(); + log.error("Failed to associate heat value {} to heat env artifact {} in graph. status is {}", heatValueData.getUniqueId(), artifactId, operationStatus); + return Either.right(operationStatus); + } + UniqueIdData heatParameterNode = new UniqueIdData(NodeTypeEnum.HeatParameter, heatParameter.getUniqueId()); + Either<GraphRelation, TitanOperationStatus> createRel2Result = titanGenericDao.createRelation(heatValueData, heatParameterNode, GraphEdgeLabels.PARAMETER_IMPL, null); + if (createRel2Result.isRight()) { + TitanOperationStatus operationStatus = createRel2Result.right().value(); + log.error("Failed to associate heat value {} to heat parameter {} in graph. status is {}", heatValueData.getUniqueId(), heatParameter.getName(), operationStatus); + return Either.right(operationStatus); + } + + return Either.left(createNodeResult.left().value()); + + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InputsOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InputsOperation.java index 287a63ea3a..9c5445a8c2 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InputsOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/InputsOperation.java @@ -20,9 +20,7 @@ package org.openecomp.sdc.be.model.operations.impl; -import java.util.ArrayList; -import java.util.List; - +import fj.data.Either; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.tinkerpop.gremlin.structure.Edge; import org.openecomp.sdc.be.config.BeEcompErrorManager; @@ -35,205 +33,185 @@ import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.ComponentInstanceInput; import org.openecomp.sdc.be.model.operations.api.IInputsOperation; -import org.openecomp.sdc.be.resources.data.ComponentInstanceData; -import org.openecomp.sdc.be.resources.data.InputValueData; -import org.openecomp.sdc.be.resources.data.InputsData; -import org.openecomp.sdc.be.resources.data.PropertyData; -import org.openecomp.sdc.be.resources.data.ResourceMetadataData; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.be.resources.data.*; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import com.google.gson.Gson; - -import fj.data.Either; +import java.util.ArrayList; +import java.util.List; @Component("input-operation") public class InputsOperation extends AbstractOperation implements IInputsOperation { - private static Logger log = LoggerFactory.getLogger(InputsOperation.class.getName()); - @Autowired - PropertyOperation propertyOperation; + private static final Logger log = Logger.getLogger(InputsOperation.class.getName()); + @Autowired + PropertyOperation propertyOperation; + + public <ElementDefinition> TitanOperationStatus findAllResourceElementsDefinitionRecursively(String resourceId, List<ElementDefinition> elements, NodeElementFetcher<ElementDefinition> singleNodeFetcher) { + + log.trace("Going to fetch elements under resource {}" , resourceId); + TitanOperationStatus resourceAttributesStatus = singleNodeFetcher.findAllNodeElements(resourceId, elements); + + if (resourceAttributesStatus != TitanOperationStatus.OK) { + return resourceAttributesStatus; + } + + Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> parentNodes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource, ResourceMetadataData.class); + + if (parentNodes.isRight()) { + TitanOperationStatus parentNodesStatus = parentNodes.right().value(); + if (parentNodesStatus != TitanOperationStatus.NOT_FOUND) { + BeEcompErrorManager.getInstance().logInternalFlowError("findAllResourceElementsDefinitionRecursively", "Failed to find parent elements of resource " + resourceId + ". status is " + parentNodesStatus, ErrorSeverity.ERROR); + return parentNodesStatus; + } + } + + if (parentNodes.isLeft()) { + ImmutablePair<ResourceMetadataData, GraphEdge> parnetNodePair = parentNodes.left().value(); + String parentUniqueId = parnetNodePair.getKey().getMetadataDataDefinition().getUniqueId(); + TitanOperationStatus addParentIntStatus = findAllResourceElementsDefinitionRecursively(parentUniqueId, elements, singleNodeFetcher); + + if (addParentIntStatus != TitanOperationStatus.OK) { + BeEcompErrorManager.getInstance().logInternalFlowError("findAllResourceElementsDefinitionRecursively", "Failed to find all resource elements of resource " + parentUniqueId, ErrorSeverity.ERROR); + + return addParentIntStatus; + } + } + return TitanOperationStatus.OK; + } + + + @Override + public ImmutablePair<TitanOperationStatus, String> findInputValue(String resourceInstanceId, String propertyId) { + + log.debug("Going to check whether the property {} already added to resource instance {}", propertyId, resourceInstanceId); + + Either<List<ComponentInstanceInput>, TitanOperationStatus> getAllRes = getAllInputsOfResourceInstanceOnlyInputDefId(resourceInstanceId); + if (getAllRes.isRight()) { + TitanOperationStatus status = getAllRes.right().value(); + log.trace("After fetching all properties of resource instance {}. Status is {}" ,resourceInstanceId, status); + return new ImmutablePair<>(status, null); + } + + List<ComponentInstanceInput> list = getAllRes.left().value(); + if (list != null) { + for (ComponentInstanceInput instanceProperty : list) { + String propertyUniqueId = instanceProperty.getUniqueId(); + String valueUniqueUid = instanceProperty.getValueUniqueUid(); + log.trace("Go over property {} under resource instance {}. valueUniqueId = {}" ,propertyUniqueId, resourceInstanceId, valueUniqueUid); + if (propertyId.equals(propertyUniqueId) && valueUniqueUid != null) { + log.debug("The property {} already created under resource instance {}", propertyId, resourceInstanceId); + return new ImmutablePair<>(TitanOperationStatus.ALREADY_EXIST, valueUniqueUid); + } + } + } + + return new ImmutablePair<>(TitanOperationStatus.NOT_FOUND, null); + } + + /** + * return all properties associated to resource instance. The result does contains the property unique id but not its type, default value... + * + * @param resourceInstanceUid + * @return + */ + public Either<List<ComponentInstanceInput>, TitanOperationStatus> getAllInputsOfResourceInstanceOnlyInputDefId(String resourceInstanceUid) { + + return getAllInputsOfResourceInstanceOnlyInputDefId(resourceInstanceUid, NodeTypeEnum.ResourceInstance); + + } + + public Either<List<ComponentInstanceInput>, TitanOperationStatus> getAllInputsOfResourceInstanceOnlyInputDefId(String resourceInstanceUid, NodeTypeEnum instanceNodeType) { + + Either<ComponentInstanceData, TitanOperationStatus> findResInstanceRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(instanceNodeType), resourceInstanceUid, ComponentInstanceData.class); + + if (findResInstanceRes.isRight()) { + TitanOperationStatus status = findResInstanceRes.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + return Either.right(status); + } + + Either<List<ImmutablePair<InputValueData, GraphEdge>>, TitanOperationStatus> propertyImplNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(instanceNodeType), resourceInstanceUid, GraphEdgeLabels.INPUT_VALUE, NodeTypeEnum.InputValue, InputValueData.class); + + if (propertyImplNodes.isRight()) { + TitanOperationStatus status = propertyImplNodes.right().value(); + return Either.right(status); + } + + List<ImmutablePair<InputValueData, GraphEdge>> list = propertyImplNodes.left().value(); + if (list == null || list.isEmpty()) { + return Either.right(TitanOperationStatus.NOT_FOUND); + } + + List<ComponentInstanceInput> result = new ArrayList<>(); + + + for (ImmutablePair<InputValueData, GraphEdge> propertyValueDataPair : list) { + + InputValueData propertyValueData = propertyValueDataPair.getLeft(); + String propertyValueUid = propertyValueData.getUniqueId(); + String value = propertyValueData.getValue(); + + Either<ImmutablePair<InputsData, GraphEdge>, TitanOperationStatus> inputNodes = titanGenericDao.getParentNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), propertyValueData.getUniqueId(), GraphEdgeLabels.GET_INPUT, NodeTypeEnum.Input, InputsData.class); + + if (inputNodes.isRight()) { + + return Either.right(inputNodes.right().value()); + } + + InputsData input = inputNodes.left().value().left; + String inputId = input.getPropertyDataDefinition().getUniqueId(); + + Either<ImmutablePair<PropertyData, GraphEdge>, TitanOperationStatus> propertyDefRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.InputValue), propertyValueUid, GraphEdgeLabels.INPUT_IMPL, NodeTypeEnum.Property, PropertyData.class); + if (propertyDefRes.isRight()) { + TitanOperationStatus status = propertyDefRes.right().value(); + if (status == TitanOperationStatus.NOT_FOUND) { + status = TitanOperationStatus.INVALID_ID; + } + return Either.right(status); + } + + ImmutablePair<PropertyData, GraphEdge> propertyDefPair = propertyDefRes.left().value(); + PropertyData propertyData = propertyDefPair.left; + Either<Edge, TitanOperationStatus> inputsEges = titanGenericDao.getIncomingEdgeByCriteria(propertyData, GraphEdgeLabels.INPUT, null); + if (inputsEges.isRight()) { + TitanOperationStatus status = inputsEges.right().value(); + + return Either.right(status); + } + Edge edge = inputsEges.left().value(); + String inputName = (String) titanGenericDao.getProperty(edge, GraphEdgePropertiesDictionary.NAME.getProperty()); - Gson gson = new Gson(); + ComponentInstanceInput resourceInstanceProperty = new ComponentInstanceInput(propertyData.getPropertyDataDefinition(), inputId, value, propertyValueUid); + resourceInstanceProperty.setName(inputName); + resourceInstanceProperty.setParentUniqueId(inputId); + resourceInstanceProperty.setValue(value); + resourceInstanceProperty.setValueUniqueUid(propertyValueData.getUniqueId()); + resourceInstanceProperty.setType(propertyData.getPropertyDataDefinition().getType()); + resourceInstanceProperty.setSchema(propertyData.getPropertyDataDefinition().getSchema()); + resourceInstanceProperty.setComponentInstanceId(resourceInstanceUid); - public <ElementDefinition> TitanOperationStatus findAllResourceElementsDefinitionRecursively(String resourceId, List<ElementDefinition> elements, NodeElementFetcher<ElementDefinition> singleNodeFetcher) { + result.add(resourceInstanceProperty); + } - log.trace("Going to fetch elements under resource {}" , resourceId); - TitanOperationStatus resourceAttributesStatus = singleNodeFetcher.findAllNodeElements(resourceId, elements); - - if (resourceAttributesStatus != TitanOperationStatus.OK) { - return resourceAttributesStatus; - } - Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> parentNodes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource, ResourceMetadataData.class); + return Either.left(result); + } - if (parentNodes.isRight()) { - TitanOperationStatus parentNodesStatus = parentNodes.right().value(); - if (parentNodesStatus != TitanOperationStatus.NOT_FOUND) { - BeEcompErrorManager.getInstance().logInternalFlowError("findAllResourceElementsDefinitionRecursively", "Failed to find parent elements of resource " + resourceId + ". status is " + parentNodesStatus, ErrorSeverity.ERROR); - return parentNodesStatus; - } - } + @Override + public ComponentInstanceInput buildResourceInstanceInput(InputValueData propertyValueData, ComponentInstanceInput resourceInstanceInput) { - if (parentNodes.isLeft()) { - ImmutablePair<ResourceMetadataData, GraphEdge> parnetNodePair = parentNodes.left().value(); - String parentUniqueId = parnetNodePair.getKey().getMetadataDataDefinition().getUniqueId(); - TitanOperationStatus addParentIntStatus = findAllResourceElementsDefinitionRecursively(parentUniqueId, elements, singleNodeFetcher); - - if (addParentIntStatus != TitanOperationStatus.OK) { - BeEcompErrorManager.getInstance().logInternalFlowError("findAllResourceElementsDefinitionRecursively", "Failed to find all resource elements of resource " + parentUniqueId, ErrorSeverity.ERROR); + String value = propertyValueData.getValue(); + String uid = propertyValueData.getUniqueId(); + ComponentInstanceInput instanceProperty = new ComponentInstanceInput(resourceInstanceInput, value, uid); + instanceProperty.setPath(resourceInstanceInput.getPath()); - return addParentIntStatus; - } - } - return TitanOperationStatus.OK; - } - - - @Override - public ImmutablePair<TitanOperationStatus, String> findInputValue(String resourceInstanceId, String propertyId) { - - log.debug("Going to check whether the property {} already added to resource instance {}", propertyId, resourceInstanceId); - - Either<List<ComponentInstanceInput>, TitanOperationStatus> getAllRes = getAllInputsOfResourceInstanceOnlyInputDefId(resourceInstanceId); - if (getAllRes.isRight()) { - TitanOperationStatus status = getAllRes.right().value(); - log.trace("After fetching all properties of resource instance {}. Status is {}" ,resourceInstanceId, status); - return new ImmutablePair<TitanOperationStatus, String>(status, null); - } - - List<ComponentInstanceInput> list = getAllRes.left().value(); - if (list != null) { - for (ComponentInstanceInput instanceProperty : list) { - String propertyUniqueId = instanceProperty.getUniqueId(); - String valueUniqueUid = instanceProperty.getValueUniqueUid(); - log.trace("Go over property {} under resource instance {}. valueUniqueId = {}" ,propertyUniqueId, resourceInstanceId, valueUniqueUid); - if (propertyId.equals(propertyUniqueId) && valueUniqueUid != null) { - log.debug("The property {} already created under resource instance {}", propertyId, resourceInstanceId); - return new ImmutablePair<TitanOperationStatus, String>(TitanOperationStatus.ALREADY_EXIST, valueUniqueUid); - } - } - } - - return new ImmutablePair<TitanOperationStatus, String>(TitanOperationStatus.NOT_FOUND, null); - } - - /** - * return all properties associated to resource instance. The result does contains the property unique id but not its type, default value... - * - * @param resourceInstanceUid - * @return - */ - public Either<List<ComponentInstanceInput>, TitanOperationStatus> getAllInputsOfResourceInstanceOnlyInputDefId(String resourceInstanceUid) { - - return getAllInputsOfResourceInstanceOnlyInputDefId(resourceInstanceUid, NodeTypeEnum.ResourceInstance); - - } - - public Either<List<ComponentInstanceInput>, TitanOperationStatus> getAllInputsOfResourceInstanceOnlyInputDefId(String resourceInstanceUid, NodeTypeEnum instanceNodeType) { - - Either<ComponentInstanceData, TitanOperationStatus> findResInstanceRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(instanceNodeType), resourceInstanceUid, ComponentInstanceData.class); - - if (findResInstanceRes.isRight()) { - TitanOperationStatus status = findResInstanceRes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - return Either.right(status); - } - - Either<List<ImmutablePair<InputValueData, GraphEdge>>, TitanOperationStatus> propertyImplNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(instanceNodeType), resourceInstanceUid, GraphEdgeLabels.INPUT_VALUE, NodeTypeEnum.InputValue, InputValueData.class); - - if (propertyImplNodes.isRight()) { - TitanOperationStatus status = propertyImplNodes.right().value(); - return Either.right(status); - } - - List<ImmutablePair<InputValueData, GraphEdge>> list = propertyImplNodes.left().value(); - if (list == null || true == list.isEmpty()) { - return Either.right(TitanOperationStatus.NOT_FOUND); - } - - List<ComponentInstanceInput> result = new ArrayList<>(); - - - for (ImmutablePair<InputValueData, GraphEdge> propertyValueDataPair : list) { - - InputValueData propertyValueData = propertyValueDataPair.getLeft(); - String propertyValueUid = propertyValueData.getUniqueId(); - String value = propertyValueData.getValue(); - - Either<ImmutablePair<InputsData, GraphEdge>, TitanOperationStatus> inputNodes = titanGenericDao.getParentNode(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), propertyValueData.getUniqueId(), GraphEdgeLabels.GET_INPUT, NodeTypeEnum.Input, InputsData.class); - - if (inputNodes.isRight()) { - - return Either.right(inputNodes.right().value()); - } - - InputsData input = inputNodes.left().value().left; - String inputId = input.getPropertyDataDefinition().getUniqueId(); - - Either<ImmutablePair<PropertyData, GraphEdge>, TitanOperationStatus> propertyDefRes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.InputValue), propertyValueUid, GraphEdgeLabels.INPUT_IMPL, NodeTypeEnum.Property, PropertyData.class); - if (propertyDefRes.isRight()) { - TitanOperationStatus status = propertyDefRes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.INVALID_ID; - } - return Either.right(status); - } - - ImmutablePair<PropertyData, GraphEdge> propertyDefPair = propertyDefRes.left().value(); - PropertyData propertyData = propertyDefPair.left; - Either<Edge, TitanOperationStatus> inputsEges = titanGenericDao.getIncomingEdgeByCriteria(propertyData, GraphEdgeLabels.INPUT, null); - if (inputsEges.isRight()) { - TitanOperationStatus status = inputsEges.right().value(); - - return Either.right(status); - } - Edge edge = inputsEges.left().value(); - String inputName = (String) titanGenericDao.getProperty(edge, GraphEdgePropertiesDictionary.NAME.getProperty()); - - String propertyUniqueId = (String) propertyData.getPropertyDataDefinition().getUniqueId(); - - - ComponentInstanceInput resourceInstanceProperty = new ComponentInstanceInput(propertyData.getPropertyDataDefinition(), inputId, value, propertyValueUid); - - //resourceInstanceProperty.setName(inputName); - // set resource id - // TODO: esofer add resource id - resourceInstanceProperty.setName(inputName); - resourceInstanceProperty.setParentUniqueId(inputId); - // set value - resourceInstanceProperty.setValue(value); - // set property value unique id - resourceInstanceProperty.setValueUniqueUid(propertyValueData.getUniqueId()); - // set rules - // resourceInstanceProperty.setRules(propertyValueData.getRules()); - resourceInstanceProperty.setType(propertyData.getPropertyDataDefinition().getType()); - resourceInstanceProperty.setSchema(propertyData.getPropertyDataDefinition().getSchema()); - //resourceInstanceProperty.setComponentInstanceName(componentInsName); - resourceInstanceProperty.setComponentInstanceId(resourceInstanceUid); - - result.add(resourceInstanceProperty); - } - - - return Either.left(result); - } - - @Override - public ComponentInstanceInput buildResourceInstanceInput(InputValueData propertyValueData, ComponentInstanceInput resourceInstanceInput) { - - String value = propertyValueData.getValue(); - String uid = propertyValueData.getUniqueId(); - ComponentInstanceInput instanceProperty = new ComponentInstanceInput(resourceInstanceInput, value, uid); - instanceProperty.setPath(resourceInstanceInput.getPath()); - - return instanceProperty; - } + return instanceProperty; + } } 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 c86559bb59..3482a25bc4 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 @@ -40,12 +40,11 @@ import org.openecomp.sdc.be.resources.data.ArtifactData; import org.openecomp.sdc.be.resources.data.InterfaceData; import org.openecomp.sdc.be.resources.data.OperationData; import org.openecomp.sdc.be.resources.data.ResourceMetadataData; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.stereotype.Component; -import java.util.HashMap; -import java.util.Iterator; +import java.util.*; +import java.util.Map.Entry; import java.util.List; import java.util.Map; import java.util.Map.Entry; @@ -54,847 +53,842 @@ import java.util.Set; @Component("interface-operation") public class InterfaceLifecycleOperation implements IInterfaceLifecycleOperation { - private static Logger log = LoggerFactory.getLogger(InterfaceLifecycleOperation.class.getName()); - - public InterfaceLifecycleOperation() { - super(); - } - - @javax.annotation.Resource - private ArtifactOperation artifactOperation; + private static final Logger log = Logger.getLogger(InterfaceLifecycleOperation.class.getName()); - @javax.annotation.Resource - private TitanGenericDao titanGenericDao; + public InterfaceLifecycleOperation() { + super(); + } - @Override - public Either<InterfaceDefinition, StorageOperationStatus> addInterfaceToResource(InterfaceDefinition interf, String resourceId, String interfaceName, boolean inTransaction) { + @javax.annotation.Resource + private ArtifactOperation artifactOperation; - return createInterfaceOnResource(interf, resourceId, interfaceName, true, inTransaction); + @javax.annotation.Resource + private TitanGenericDao titanGenericDao; - } + @Override + public Either<InterfaceDefinition, StorageOperationStatus> addInterfaceToResource(InterfaceDefinition interf, String resourceId, String interfaceName, boolean inTransaction) { - private Either<OperationData, TitanOperationStatus> addOperationToGraph(InterfaceDefinition interf, String opName, Operation op, InterfaceData interfaceData) { + return createInterfaceOnResource(interf, resourceId, interfaceName, true, inTransaction); - op.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId((String) interfaceData.getUniqueId(), opName)); - OperationData operationData = new OperationData(op); + } - log.debug("Before adding operation to graph {}", operationData); - Either<OperationData, TitanOperationStatus> createOpNodeResult = titanGenericDao.createNode(operationData, OperationData.class); - log.debug("After adding operation to graph {}", operationData); + private Either<OperationData, TitanOperationStatus> addOperationToGraph(InterfaceDefinition interf, String opName, Operation op, InterfaceData interfaceData) { - if (createOpNodeResult.isRight()) { - TitanOperationStatus opStatus = createOpNodeResult.right().value(); - log.error("Failed to add operation {} to graph. status is {}", opName, opStatus); - return Either.right(opStatus); - } + op.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId((String) interfaceData.getUniqueId(), opName)); + OperationData operationData = new OperationData(op); - Map<String, Object> props = new HashMap<String, Object>(); - props.put(GraphPropertiesDictionary.NAME.getProperty(), opName); - Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(interfaceData, operationData, GraphEdgeLabels.INTERFACE_OPERATION, props); + log.debug("Before adding operation to graph {}", operationData); + Either<OperationData, TitanOperationStatus> createOpNodeResult = titanGenericDao.createNode(operationData, OperationData.class); + log.debug("After adding operation to graph {}", operationData); - if (createRelResult.isRight()) { - TitanOperationStatus operationStatus = createOpNodeResult.right().value(); - log.error("Failed to associate operation {} to property {} in graph. status is {}", interfaceData.getUniqueId(), opName, operationStatus); + if (createOpNodeResult.isRight()) { + TitanOperationStatus opStatus = createOpNodeResult.right().value(); + log.error("Failed to add operation {} to graph. status is {}", opName, opStatus); + return Either.right(opStatus); + } - return Either.right(operationStatus); - } + Map<String, Object> props = new HashMap<>(); + props.put(GraphPropertiesDictionary.NAME.getProperty(), opName); + Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(interfaceData, operationData, GraphEdgeLabels.INTERFACE_OPERATION, props); - return Either.left(createOpNodeResult.left().value()); + if (createRelResult.isRight()) { + TitanOperationStatus operationStatus = createOpNodeResult.right().value(); + log.error("Failed to associate operation {} to property {} in graph. status is {}", interfaceData.getUniqueId(), opName, operationStatus); - } + return Either.right(operationStatus); + } - private InterfaceDefinition convertInterfaceDataToInterfaceDefinition(InterfaceData interfaceData) { + return Either.left(createOpNodeResult.left().value()); - log.debug("The object returned after create interface is {}", interfaceData); + } - InterfaceDefinition interfaceDefResult = new InterfaceDefinition(interfaceData.getInterfaceDataDefinition()); + private InterfaceDefinition convertInterfaceDataToInterfaceDefinition(InterfaceData interfaceData) { - return interfaceDefResult; + log.debug("The object returned after create interface is {}", interfaceData); - } + return new InterfaceDefinition(interfaceData.getInterfaceDataDefinition()); - private Operation convertOperationDataToOperation(OperationData operationData) { + } - log.debug("The object returned after create operation is {}", operationData); + private Operation convertOperationDataToOperation(OperationData operationData) { - Operation operationDefResult = new Operation(operationData.getOperationDataDefinition()); + log.debug("The object returned after create operation is {}", operationData); - return operationDefResult; + return new Operation(operationData.getOperationDataDefinition()); - } + } - private Either<InterfaceData, TitanOperationStatus> addInterfaceToGraph(InterfaceDefinition interfaceInfo, String interfaceName, String resourceId) { + private Either<InterfaceData, TitanOperationStatus> addInterfaceToGraph(InterfaceDefinition interfaceInfo, String interfaceName, String resourceId) { - InterfaceData interfaceData = new InterfaceData(interfaceInfo); + InterfaceData interfaceData = new InterfaceData(interfaceInfo); - ResourceMetadataData resourceData = new ResourceMetadataData(); - resourceData.getMetadataDataDefinition().setUniqueId(resourceId); + ResourceMetadataData resourceData = new ResourceMetadataData(); + resourceData.getMetadataDataDefinition().setUniqueId(resourceId); - String interfaceNameSplitted = getShortInterfaceName(interfaceInfo); + String interfaceNameSplitted = getShortInterfaceName(interfaceInfo); - interfaceInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, interfaceNameSplitted)); + interfaceInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, interfaceNameSplitted)); - Either<InterfaceData, TitanOperationStatus> existInterface = titanGenericDao.getNode(interfaceData.getUniqueIdKey(), interfaceData.getUniqueId(), InterfaceData.class); + Either<InterfaceData, TitanOperationStatus> existInterface = titanGenericDao.getNode(interfaceData.getUniqueIdKey(), interfaceData.getUniqueId(), InterfaceData.class); - if (existInterface.isRight()) { + if (existInterface.isRight()) { - return createInterfaceNodeAndRelation(interfaceNameSplitted, resourceId, interfaceData, resourceData); - } else { - log.debug("Interface {} already exist", interfaceData.getUniqueId()); - return Either.right(TitanOperationStatus.ALREADY_EXIST); - } - } + return createInterfaceNodeAndRelation(interfaceNameSplitted, resourceId, interfaceData, resourceData); + } else { + log.debug("Interface {} already exist", interfaceData.getUniqueId()); + return Either.right(TitanOperationStatus.ALREADY_EXIST); + } + } - private Either<InterfaceData, TitanOperationStatus> createInterfaceNodeAndRelation(String interfaceName, String resourceId, InterfaceData interfaceData, ResourceMetadataData resourceData) { - log.debug("Before adding interface to graph {}", interfaceData); - Either<InterfaceData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(interfaceData, InterfaceData.class); - log.debug("After adding property to graph {}", interfaceData); + private Either<InterfaceData, TitanOperationStatus> createInterfaceNodeAndRelation(String interfaceName, String resourceId, InterfaceData interfaceData, ResourceMetadataData resourceData) { + log.debug("Before adding interface to graph {}", interfaceData); + Either<InterfaceData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(interfaceData, InterfaceData.class); + log.debug("After adding property to graph {}", interfaceData); - if (createNodeResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); - log.error("Failed to add interface {} to graph. status is {}", interfaceName, operationStatus); - return Either.right(operationStatus); - } + if (createNodeResult.isRight()) { + TitanOperationStatus operationStatus = createNodeResult.right().value(); + log.error("Failed to add interface {} to graph. status is {}", interfaceName, operationStatus); + return Either.right(operationStatus); + } - Map<String, Object> props = new HashMap<String, Object>(); - props.put(GraphPropertiesDictionary.NAME.getProperty(), interfaceName); - Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(resourceData, interfaceData, GraphEdgeLabels.INTERFACE, props); - if (createRelResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); - log.error("Failed to associate resource {} to property {} in graph. status is {}", resourceId, interfaceName, operationStatus); - - return Either.right(operationStatus); - } - - return Either.left(createNodeResult.left().value()); - } - - private Either<OperationData, TitanOperationStatus> createOperationNodeAndRelation(String operationName, OperationData operationData, InterfaceData interfaceData) { - log.debug("Before adding operation to graph {}", operationData); - Either<OperationData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(operationData, OperationData.class); - log.debug("After adding operation to graph {}", interfaceData); - - if (createNodeResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); - log.error("Failed to add interfoperationce {} to graph. status is {}", operationName, operationStatus); - return Either.right(operationStatus); - } - - Map<String, Object> props = new HashMap<String, Object>(); - props.put(GraphPropertiesDictionary.NAME.getProperty(), operationName); - Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(interfaceData, operationData, GraphEdgeLabels.INTERFACE_OPERATION, props); - if (createRelResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); - log.error("Failed to associate operation {} to interface {} in graph. status is {}", operationName, interfaceData.getUniqueId(), operationStatus); - - return Either.right(operationStatus); - } - - return Either.left(createNodeResult.left().value()); - } - - @Override - public Either<Map<String, InterfaceDefinition>, StorageOperationStatus> getAllInterfacesOfResource(String resourceIdn, boolean recursively) { - return getAllInterfacesOfResource(resourceIdn, recursively, false); - } - - @Override - public Either<Map<String, InterfaceDefinition>, StorageOperationStatus> getAllInterfacesOfResource(String resourceId, boolean recursively, boolean inTransaction) { - - Either<Map<String, InterfaceDefinition>, StorageOperationStatus> result = null; - Map<String, InterfaceDefinition> interfaces = new HashMap<String, InterfaceDefinition>(); - try { - if ((resourceId == null) || resourceId.isEmpty()) { - log.error("resourceId is empty"); - result = Either.right(StorageOperationStatus.INVALID_ID); - return result; - } - - TitanOperationStatus findInterfacesRes = TitanOperationStatus.GENERAL_ERROR; - if (recursively) { - findInterfacesRes = findAllInterfacesRecursively(resourceId, interfaces); - } else { - findInterfacesRes = findAllInterfacesNotRecursively(resourceId, interfaces); - } - if (!findInterfacesRes.equals(TitanOperationStatus.OK)) { - log.error("Failed to get all interfaces of resource {}. status is {}", resourceId, findInterfacesRes); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(findInterfacesRes)); - return result; - } - result = Either.left(interfaces); - return result; - } finally { - if (false == inTransaction) { - if (result == null || result.isRight()) { - log.error("Going to execute rollback on graph."); - titanGenericDao.rollback(); - } else { - log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } - } - - private TitanOperationStatus findAllInterfacesNotRecursively(String resourceId, Map<String, InterfaceDefinition> interfaces) { - - Either<List<ImmutablePair<InterfaceData, GraphEdge>>, TitanOperationStatus> interfaceNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.INTERFACE, - NodeTypeEnum.Interface, InterfaceData.class); - - if (interfaceNodes.isRight()) { - TitanOperationStatus status = interfaceNodes.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { - return status; - } - } else { - List<ImmutablePair<InterfaceData, GraphEdge>> interfaceList = interfaceNodes.left().value(); - if (interfaceList != null) { - for (ImmutablePair<InterfaceData, GraphEdge> interfacePair : interfaceList) { - String interfaceUniqueId = (String) interfacePair.getKey().getUniqueId(); - Either<String, TitanOperationStatus> interfaceNameRes = getPropertyValueFromEdge(interfacePair.getValue(), GraphPropertiesDictionary.NAME); - if (interfaceNameRes.isRight()) { - log.error("The requirement name is missing on the edge of requirement {}", interfaceUniqueId); - return interfaceNameRes.right().value(); - } - String interfaceName = interfaceNameRes.left().value(); - Either<InterfaceDefinition, TitanOperationStatus> interfaceDefRes = getNonRecursiveInterface(interfacePair.getKey()); - if (interfaceDefRes.isRight()) { - TitanOperationStatus status = interfaceDefRes.right().value(); - log.error("Failed to get interface actions of interface {}", interfaceUniqueId); - return status; - } - - InterfaceDefinition interfaceDefinition = interfaceDefRes.left().value(); - if (true == interfaces.containsKey(interfaceName)) { - log.debug("The interface {} was already defined in dervied resource. add not overriden operations", interfaceName); - InterfaceDefinition existInterface = interfaces.get(interfaceName); - addMissingOperationsToInterface(interfaceDefinition, existInterface); - } else { - interfaces.put(interfaceName, interfaceDefinition); - } - - } - } - } - return TitanOperationStatus.OK; - } - - public TitanOperationStatus findAllInterfacesRecursively(String resourceId, Map<String, InterfaceDefinition> interfaces) { - - TitanOperationStatus findAllInterfacesNotRecursively = findAllInterfacesNotRecursively(resourceId, interfaces); - if (!findAllInterfacesNotRecursively.equals(TitanOperationStatus.OK)) { - log.error("failed to get interfaces for resource {}. status is {}", resourceId, findAllInterfacesNotRecursively); - } - - Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> parentNodes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource, - ResourceMetadataData.class); - - if (parentNodes.isRight()) { - TitanOperationStatus parentNodesStatus = parentNodes.right().value(); - if (parentNodesStatus == TitanOperationStatus.NOT_FOUND) { - log.debug("Finish to lookup for parnet interfaces"); - return TitanOperationStatus.OK; - } else { - log.error("Failed to find parent interfaces of resource {}. status is {}", resourceId, parentNodesStatus); - return parentNodesStatus; - } - } - ImmutablePair<ResourceMetadataData, GraphEdge> parnetNodePair = parentNodes.left().value(); - String parentUniqueId = parnetNodePair.getKey().getMetadataDataDefinition().getUniqueId(); - TitanOperationStatus addParentIntStatus = findAllInterfacesRecursively(parentUniqueId, interfaces); - - if (addParentIntStatus != TitanOperationStatus.OK) { - log.error("Failed to fetch all interfaces of resource {}", parentUniqueId); - return addParentIntStatus; - } - - return TitanOperationStatus.OK; - } - - private Either<String, TitanOperationStatus> getPropertyValueFromEdge(GraphEdge edge, GraphPropertiesDictionary property) { - Map<String, Object> edgeProps = edge.getProperties(); - String interfaceName = null; - if (edgeProps != null) { - interfaceName = (String) edgeProps.get(property.getProperty()); - if (interfaceName == null) { - return Either.right(TitanOperationStatus.INVALID_ELEMENT); - } - } else { - return Either.right(TitanOperationStatus.INVALID_ELEMENT); - } - return Either.left(interfaceName); - } - - private Either<InterfaceDefinition, TitanOperationStatus> getNonRecursiveInterface(InterfaceData interfaceData) { - - log.debug("Going to fetch the operations associate to interface {}", interfaceData.getUniqueId()); - InterfaceDefinition interfaceDefinition = new InterfaceDefinition(interfaceData.getInterfaceDataDefinition()); - - String interfaceId = interfaceData.getUniqueId(); - Either<List<ImmutablePair<OperationData, GraphEdge>>, TitanOperationStatus> operationsRes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), interfaceId, GraphEdgeLabels.INTERFACE_OPERATION, - NodeTypeEnum.InterfaceOperation, OperationData.class); - - if (operationsRes.isRight()) { - TitanOperationStatus status = operationsRes.right().value(); - if (status != TitanOperationStatus.NOT_FOUND) { - return Either.right(status); - } else { - return Either.left(interfaceDefinition); - } - } - - List<ImmutablePair<OperationData, GraphEdge>> operationList = operationsRes.left().value(); - if (operationList != null && !operationList.isEmpty()) { - for (ImmutablePair<OperationData, GraphEdge> operationPair : operationList) { - Operation operation = new Operation(operationPair.getKey().getOperationDataDefinition()); - Either<String, TitanOperationStatus> operationNameRes = getPropertyValueFromEdge(operationPair.getValue(), GraphPropertiesDictionary.NAME); - if (operationNameRes.isRight()) { - log.error("The operation name is missing on the edge of operation {}", operationPair.getKey().getUniqueId()); - return Either.right(operationNameRes.right().value()); - } - String operationName = operationNameRes.left().value(); - findOperationImplementation(operation); - interfaceDefinition.getOperations().put(operationName, operation); - } - } - - return Either.left(interfaceDefinition); - } - - private StorageOperationStatus findOperationImplementation(Operation operation) { - - String operationId = operation.getUniqueId(); - Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsRes = artifactOperation.getArtifacts(operationId, NodeTypeEnum.InterfaceOperation, true); - if (artifactsRes.isRight() || artifactsRes.left().value() == null) { - log.error("failed to get artifact from graph for operation id {}. status is {}", operationId, artifactsRes.right().value()); - return artifactsRes.right().value(); - } else { - Map<String, ArtifactDefinition> artifacts = artifactsRes.left().value(); - Iterator<String> iter = artifacts.keySet().iterator(); - - if (iter.hasNext()) { - operation.setImplementation(artifacts.get(iter.next())); - } - } - return StorageOperationStatus.OK; - } - - private StorageOperationStatus addMissingOperationsToInterface(InterfaceDefinition interfaceDefinition, InterfaceDefinition existInterface) { - Map<String, Operation> existOperations = existInterface.getOperationsMap(); - Map<String, Operation> operations = interfaceDefinition.getOperationsMap(); - if (operations != null && !operations.isEmpty()) { - Set<Entry<String, Operation>> operationsSet = operations.entrySet(); - for (Entry<String, Operation> operation : operationsSet) { - if (!existOperations.containsKey(operation.getKey())) { - existOperations.put(operation.getKey(), operation.getValue()); - } - } - } - return StorageOperationStatus.OK; - } - - @Override - public Either<Operation, StorageOperationStatus> updateInterfaceOperation(String resourceId, String interfaceName, String operationName, Operation interf) { - - return updateInterfaceOperation(resourceId, interfaceName, operationName, interf, false); - } - - @Override - public Either<Operation, StorageOperationStatus> updateInterfaceOperation(String resourceId, String interfaceName, String operationName, Operation operation, boolean inTransaction) { - Either<Operation, StorageOperationStatus> status = updateOperationOnGraph(operation, resourceId, interfaceName, operationName); - return status; - } - - private Either<Operation, StorageOperationStatus> updateOperationOnGraph(Operation operation, String resourceId, String interfaceName, String operationName) { - - Either<List<ImmutablePair<InterfaceData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), resourceId, GraphEdgeLabels.INTERFACE, NodeTypeEnum.Interface, - InterfaceData.class); - - if (childrenNodes.isRight()) { - return updateOperationFromParentNode(operation, resourceId, interfaceName, operationName); - - } else { - return updateExistingOperation(resourceId, operation, interfaceName, operationName, childrenNodes); - - } - - } - - private Either<Operation, StorageOperationStatus> updateExistingOperation(String resourceId, Operation operation, String interfaceName, String operationName, - Either<List<ImmutablePair<InterfaceData, GraphEdge>>, TitanOperationStatus> childrenNodes) { - Operation newOperation = null; - StorageOperationStatus storageOperationStatus = StorageOperationStatus.GENERAL_ERROR; - - for (ImmutablePair<InterfaceData, GraphEdge> interfaceDataNode : childrenNodes.left().value()) { - - GraphEdge interfaceEdge = interfaceDataNode.getRight(); - Map<String, Object> interfaceEdgeProp = interfaceEdge.getProperties(); - InterfaceData interfaceData = interfaceDataNode.getKey(); - - if (interfaceEdgeProp.get(GraphPropertiesDictionary.NAME.getProperty()).equals(interfaceName)) { - Either<List<ImmutablePair<OperationData, GraphEdge>>, TitanOperationStatus> operationRes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) interfaceDataNode.getLeft().getUniqueId(), - GraphEdgeLabels.INTERFACE_OPERATION, NodeTypeEnum.InterfaceOperation, OperationData.class); - if (operationRes.isRight()) { - log.error("Failed to find operation {} on interface {}", operationName, interfaceName); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationRes.right().value())); - } else { - List<ImmutablePair<OperationData, GraphEdge>> operations = operationRes.left().value(); - for (ImmutablePair<OperationData, GraphEdge> operationPairEdge : operations) { - GraphEdge opEdge = operationPairEdge.getRight(); - OperationData opData = operationPairEdge.getLeft(); - Map<String, Object> opEdgeProp = opEdge.getProperties(); - if (opEdgeProp.get(GraphPropertiesDictionary.NAME.getProperty()).equals(operationName)) { - ArtifactDefinition artifact = operation.getImplementationArtifact(); - Either<ImmutablePair<ArtifactData, GraphEdge>, TitanOperationStatus> artifactRes = titanGenericDao.getChild(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) opData.getUniqueId(), GraphEdgeLabels.ARTIFACT_REF, - NodeTypeEnum.ArtifactRef, ArtifactData.class); - Either<ArtifactDefinition, StorageOperationStatus> artStatus; - if (artifactRes.isRight()) { - artStatus = artifactOperation.addArifactToComponent(artifact, (String) operationPairEdge.getLeft().getUniqueId(), NodeTypeEnum.InterfaceOperation, true, true); - } else { - artStatus = artifactOperation.updateArifactOnResource(artifact, (String) operationPairEdge.getLeft().getUniqueId(), (String) artifactRes.left().value().getLeft().getUniqueId(), NodeTypeEnum.InterfaceOperation, true); - } - if (artStatus.isRight()) { - titanGenericDao.rollback(); - log.error("Failed to add artifact {} to interface {}", operationName, interfaceName); - return Either.right(artStatus.right().value()); - } else { - newOperation = this.convertOperationDataToOperation(opData); - newOperation.setImplementation(artStatus.left().value()); - - } - - } - - } - if (newOperation == null) { - Either<InterfaceData, TitanOperationStatus> parentInterfaceStatus = findInterfaceOnParentNode(resourceId, interfaceName); - if (parentInterfaceStatus.isRight()) { - log.debug("Interface {} not exist", interfaceName); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentInterfaceStatus.right().value())); - } - - InterfaceData parentInterfaceData = parentInterfaceStatus.left().value(); - Either<List<ImmutablePair<OperationData, GraphEdge>>, TitanOperationStatus> opRes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) parentInterfaceData.getUniqueId(), - GraphEdgeLabels.INTERFACE_OPERATION, NodeTypeEnum.InterfaceOperation, OperationData.class); - if (opRes.isRight()) { - log.error("Failed to find operation {} on interface {}", operationName, interfaceName); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationRes.right().value())); - - } else { - List<ImmutablePair<OperationData, GraphEdge>> parentOperations = opRes.left().value(); - for (ImmutablePair<OperationData, GraphEdge> operationPairEdge : parentOperations) { - GraphEdge opEdge = operationPairEdge.getRight(); - OperationData opData = operationPairEdge.getLeft(); - Map<String, Object> opEdgeProp = opEdge.getProperties(); - if (opEdgeProp.get(GraphPropertiesDictionary.NAME.getProperty()).equals(operationName)) { - return copyAndCreateNewOperation(operation, interfaceName, operationName, null, interfaceData, operationRes, opData); - } - } - } - - } - - } - - } else { - // not found - storageOperationStatus = StorageOperationStatus.ARTIFACT_NOT_FOUND; - } - - } - if (newOperation == null) - return Either.right(storageOperationStatus); - else - return Either.left(newOperation); - } - - private Either<Operation, StorageOperationStatus> copyAndCreateNewOperation(Operation operation, String interfaceName, String operationName, Operation newOperation, InterfaceData interfaceData, - Either<List<ImmutablePair<OperationData, GraphEdge>>, TitanOperationStatus> operationRes, OperationData opData) { - OperationDataDefinition opDataInfo = opData.getOperationDataDefinition(); - OperationDataDefinition newOperationInfo = new OperationDataDefinition(opDataInfo); - newOperationInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(interfaceData.getUniqueId(), operationName.toLowerCase())); - OperationData newopData = new OperationData(newOperationInfo); - Either<OperationData, TitanOperationStatus> operationStatus = createOperationNodeAndRelation(operationName, newopData, interfaceData); - if (operationStatus.isRight()) { - log.error("Failed to create operation {} on interface {}", operationName, interfaceName); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationRes.right().value())); - } - ArtifactDefinition artifact = operation.getImplementationArtifact(); - if (artifact != null) { - Either<ArtifactDefinition, StorageOperationStatus> artStatus = artifactOperation.addArifactToComponent(artifact, (String) operationStatus.left().value().getUniqueId(), NodeTypeEnum.InterfaceOperation, true, true); - if (artStatus.isRight()) { - titanGenericDao.rollback(); - log.error("Failed to add artifact {} to interface {}", operationName, interfaceName); - } else { - newOperation = this.convertOperationDataToOperation(opData); - newOperation.setImplementation(artStatus.left().value()); - - } - } - return Either.left(newOperation); - } - - private Either<Operation, StorageOperationStatus> updateOperationFromParentNode(Operation operation, String resourceId, String interfaceName, String operationName) { - // Operation newOperation = null; - ResourceMetadataData resourceData = new ResourceMetadataData(); - resourceData.getMetadataDataDefinition().setUniqueId(resourceId); - Either<InterfaceData, TitanOperationStatus> parentInterfaceStatus = findInterfaceOnParentNode(resourceId, interfaceName); - if (parentInterfaceStatus.isRight()) { - log.debug("Interface {} not exist", interfaceName); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentInterfaceStatus.right().value())); - } - - InterfaceData interfaceData = parentInterfaceStatus.left().value(); - InterfaceDataDefinition intDataDefinition = interfaceData.getInterfaceDataDefinition(); - InterfaceDataDefinition newInterfaceInfo = new InterfaceDataDefinition(intDataDefinition); - - String interfaceNameSplitted = getShortInterfaceName(intDataDefinition); - - newInterfaceInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, interfaceNameSplitted)); - InterfaceData updatedInterfaceData = new InterfaceData(newInterfaceInfo); - Either<InterfaceData, TitanOperationStatus> createStatus = createInterfaceNodeAndRelation(interfaceName, resourceId, updatedInterfaceData, resourceData); - if (createStatus.isRight()) { - log.debug("failed to create interface node {} on resource {}", interfaceName, resourceId); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createStatus.right().value())); - } - - InterfaceData newInterfaceNode = createStatus.left().value(); - Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(newInterfaceNode, interfaceData, GraphEdgeLabels.DERIVED_FROM, null); - if (createRelResult.isRight()) { - TitanOperationStatus operationStatus = createRelResult.right().value(); - log.error("Failed to associate interface {} to interface {} in graph. status is {}", interfaceData.getUniqueId(), newInterfaceNode.getUniqueId(), operationStatus); - - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationStatus)); - } - Either<List<ImmutablePair<OperationData, GraphEdge>>, TitanOperationStatus> operationRes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) interfaceData.getUniqueId(), - GraphEdgeLabels.INTERFACE_OPERATION, NodeTypeEnum.InterfaceOperation, OperationData.class); - if (operationRes.isRight()) { - log.error("Failed to find operation {} on interface {}", operationName, interfaceName); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationRes.right().value())); - - } else { - List<ImmutablePair<OperationData, GraphEdge>> operations = operationRes.left().value(); - for (ImmutablePair<OperationData, GraphEdge> operationPairEdge : operations) { - GraphEdge opEdge = operationPairEdge.getRight(); - OperationData opData = operationPairEdge.getLeft(); - Map<String, Object> opEdgeProp = opEdge.getProperties(); - if (opEdgeProp.get(GraphPropertiesDictionary.NAME.getProperty()).equals(operationName)) { - - return copyAndCreateNewOperation(operation, interfaceName, operationName, null, // changed - // from - // newOperation - newInterfaceNode, operationRes, opData); - - } - } - } - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - - private Either<InterfaceData, TitanOperationStatus> findInterfaceOnParentNode(String resourceId, String interfaceName) { - - Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> parentRes = titanGenericDao.getChild(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), resourceId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource, - ResourceMetadataData.class); - if (parentRes.isRight()) { - log.debug("interface {} not found ", interfaceName); - return Either.right(parentRes.right().value()); - } - ImmutablePair<ResourceMetadataData, GraphEdge> parenNode = parentRes.left().value(); - - Either<List<ImmutablePair<InterfaceData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), parenNode.getKey().getMetadataDataDefinition().getUniqueId(), - GraphEdgeLabels.INTERFACE, NodeTypeEnum.Interface, InterfaceData.class); - if (childrenNodes.isRight()) { - return findInterfaceOnParentNode(parenNode.getKey().getMetadataDataDefinition().getUniqueId(), interfaceName); - - } else { - for (ImmutablePair<InterfaceData, GraphEdge> interfaceDataNode : childrenNodes.left().value()) { - - GraphEdge interfaceEdge = interfaceDataNode.getRight(); - Map<String, Object> interfaceEdgeProp = interfaceEdge.getProperties(); - - if (interfaceEdgeProp.get(GraphPropertiesDictionary.NAME.getProperty()).equals(interfaceName)) { - return Either.left(interfaceDataNode.getKey()); - } - - } - return findInterfaceOnParentNode(parenNode.getKey().getMetadataDataDefinition().getUniqueId(), interfaceName); - } - - } - - @Override - public Either<InterfaceDefinition, StorageOperationStatus> createInterfaceOnResource(InterfaceDefinition interf, String resourceId, String interfaceName, boolean failIfExist, boolean inTransaction) { - - Either<InterfaceData, TitanOperationStatus> status = addInterfaceToGraph(interf, interfaceName, resourceId); - - if (status.isRight()) { - titanGenericDao.rollback(); - log.error("Failed to add interface {} to resource {}", interfaceName, resourceId); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status.right().value())); - } else { - - if (false == inTransaction) { - titanGenericDao.commit(); - } - InterfaceData interfaceData = status.left().value(); - - InterfaceDefinition interfaceDefResult = convertInterfaceDataToInterfaceDefinition(interfaceData); - Map<String, Operation> operations = interf.getOperationsMap(); - if (operations != null && !operations.isEmpty()) { - Set<String> opNames = operations.keySet(); - Map<String, Operation> newOperations = new HashMap<String, Operation>(); - for (String operationName : opNames) { - - Operation op = operations.get(operationName); - Either<OperationData, TitanOperationStatus> opStatus = addOperationToGraph(interf, operationName, op, interfaceData); - if (status.isRight()) { - titanGenericDao.rollback(); - log.error("Failed to add operation {} to interface {}", operationName, interfaceName); - } else if (status.isLeft()) { - if (false == inTransaction) { - titanGenericDao.commit(); - } - OperationData opData = opStatus.left().value(); - Operation newOperation = this.convertOperationDataToOperation(opData); - - ArtifactDefinition art = op.getImplementationArtifact(); - if (art != null) { - Either<ArtifactDefinition, StorageOperationStatus> artRes = artifactOperation.addArifactToComponent(art, (String) opData.getUniqueId(), NodeTypeEnum.InterfaceOperation, failIfExist, true); - if (artRes.isRight()) { - titanGenericDao.rollback(); - log.error("Failed to add artifact {} to interface {}", operationName, interfaceName); - } else { - newOperation.setImplementation(artRes.left().value()); - } - newOperations.put(operationName, newOperation); - } - } - } - interfaceDefResult.setOperationsMap(newOperations); - } - log.debug("The returned InterfaceDefintion is {}", interfaceDefResult); - return Either.left(interfaceDefResult); - } - - } - - @Override - public Either<Operation, StorageOperationStatus> deleteInterfaceOperation(String resourceId, String interfaceName, String operationId, boolean inTransaction) { - - Either<Operation, TitanOperationStatus> status = removeOperationOnGraph(resourceId, interfaceName, operationId); - if (status.isRight()) { - if (false == inTransaction) { - titanGenericDao.rollback(); - } - log.error("Failed to delete operation {} of interface {} resource {}", operationId, interfaceName, resourceId); - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status.right().value())); - } else { - if (false == inTransaction) { - titanGenericDao.commit(); - } - - Operation opDefResult = status.left().value();// convertOperationDataToOperation(operationData); - log.debug("The returned Operation is {}", opDefResult); - return Either.left(opDefResult); - } - - } - - private Either<Operation, TitanOperationStatus> removeOperationOnGraph(String resourceId, String interfaceName, String operationId) { - log.debug("Before deleting operation from graph {}", operationId); - - Either<List<ImmutablePair<InterfaceData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), resourceId, GraphEdgeLabels.INTERFACE, NodeTypeEnum.Interface, - InterfaceData.class); - - if (childrenNodes.isRight()) { - log.debug("Not found interface {}", interfaceName); - return Either.right(childrenNodes.right().value()); - } - OperationData opData = null; - for (ImmutablePair<InterfaceData, GraphEdge> interfaceDataNode : childrenNodes.left().value()) { - - GraphEdge interfaceEdge = interfaceDataNode.getRight(); - Map<String, Object> interfaceEdgeProp = interfaceEdge.getProperties(); - - String interfaceSplitedName = splitType(interfaceName); - - if (interfaceEdgeProp.get(GraphPropertiesDictionary.NAME.getProperty()).equals(interfaceSplitedName)) { - Either<List<ImmutablePair<OperationData, GraphEdge>>, TitanOperationStatus> operationRes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) interfaceDataNode.getLeft().getUniqueId(), - GraphEdgeLabels.INTERFACE_OPERATION, NodeTypeEnum.InterfaceOperation, OperationData.class); - if (operationRes.isRight()) { - log.error("Failed to find operation {} on interface {}", operationId, interfaceName); - return Either.right(operationRes.right().value()); - } - List<ImmutablePair<OperationData, GraphEdge>> operations = operationRes.left().value(); - - for (ImmutablePair<OperationData, GraphEdge> operationPairEdge : operations) { - - opData = operationPairEdge.getLeft(); - if (opData.getUniqueId().equals(operationId)) { - - Either<ImmutablePair<ArtifactData, GraphEdge>, TitanOperationStatus> artifactRes = titanGenericDao.getChild(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) operationPairEdge.getLeft().getUniqueId(), - GraphEdgeLabels.ARTIFACT_REF, NodeTypeEnum.ArtifactRef, ArtifactData.class); - Either<ArtifactDefinition, StorageOperationStatus> arStatus = null; - if (artifactRes.isLeft()) { - ArtifactData arData = artifactRes.left().value().getKey(); - arStatus = artifactOperation.removeArifactFromResource((String) operationPairEdge.getLeft().getUniqueId(), (String) arData.getUniqueId(), NodeTypeEnum.InterfaceOperation, true, true); - if (arStatus.isRight()) { - log.debug("failed to delete artifact {}", arData.getUniqueId()); - return Either.right(TitanOperationStatus.INVALID_ID); - } - } - Either<OperationData, TitanOperationStatus> deleteOpStatus = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.InterfaceOperation), opData.getUniqueId(), OperationData.class); - if (deleteOpStatus.isRight()) { - log.debug("failed to delete operation {}", opData.getUniqueId()); - return Either.right(TitanOperationStatus.INVALID_ID); - } - opData = deleteOpStatus.left().value(); - Operation operation = new Operation(opData.getOperationDataDefinition()); - if (arStatus != null) { - operation.setImplementation(arStatus.left().value()); - } - if (operations.size() <= 1) { - Either<InterfaceData, TitanOperationStatus> deleteInterfaceStatus = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Interface), interfaceDataNode.left.getUniqueId(), InterfaceData.class); - if (deleteInterfaceStatus.isRight()) { - log.debug("failed to delete interface {}", interfaceDataNode.left.getUniqueId()); - return Either.right(TitanOperationStatus.INVALID_ID); - } - - } - - return Either.left(operation); - - } - } - } - } - - log.debug("Not found operation {}", interfaceName); - return Either.right(TitanOperationStatus.INVALID_ID); - } - - private String splitType(String interfaceName) { - String interfaceSplittedName; - String[] packageName = interfaceName.split("\\."); - - if (packageName.length == 0) { - interfaceSplittedName = interfaceName; - } else { - interfaceSplittedName = packageName[packageName.length - 1]; - } - - return interfaceSplittedName.toLowerCase(); - } - - /** - * FOR TEST ONLY - * - * @param titanGenericDao - */ - public void setTitanGenericDao(TitanGenericDao titanGenericDao) { - this.titanGenericDao = titanGenericDao; - } - - public void setArtifactOperation(ArtifactOperation artifactOperation) { - this.artifactOperation = artifactOperation; - } - - @Override - public Either<InterfaceDefinition, StorageOperationStatus> createInterfaceType(InterfaceDefinition interf, boolean inTransaction) { - Either<InterfaceDefinition, StorageOperationStatus> result = null; - try { - - InterfaceData interfaceData = new InterfaceData(interf); - interf.setUniqueId(interf.getType().toLowerCase()); - - Either<InterfaceData, TitanOperationStatus> existInterface = titanGenericDao.getNode(interfaceData.getUniqueIdKey(), interfaceData.getUniqueId(), InterfaceData.class); - - if (existInterface.isLeft()) { - // already exist - log.debug("Interface type already exist {}", interfaceData); - result = Either.right(StorageOperationStatus.ENTITY_ALREADY_EXISTS); - return result; - } - - log.debug("Before adding interface type to graph {}", interfaceData); - Either<InterfaceData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(interfaceData, InterfaceData.class); - log.debug("After adding property type to graph {}", interfaceData); - - if (createNodeResult.isRight()) { - TitanOperationStatus operationStatus = createNodeResult.right().value(); - log.error("Failed to add interface {} to graph. status is {}", interf.getType(), operationStatus); - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationStatus)); - return result; - } - - InterfaceDefinition interfaceDefResult = convertInterfaceDataToInterfaceDefinition(interfaceData); - Map<String, Operation> operations = interf.getOperationsMap(); - - if (operations != null && !operations.isEmpty()) { - Map<String, Operation> newOperations = new HashMap<String, Operation>(); - - for (Map.Entry<String, Operation> operation : operations.entrySet()) { - Either<OperationData, TitanOperationStatus> opStatus = addOperationToGraph(interf, operation.getKey(), operation.getValue(), interfaceData); - if (opStatus.isRight()) { - titanGenericDao.rollback(); - log.error("Failed to add operation {} to interface {}", operation.getKey(), interf.getType()); - - result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(opStatus.right().value())); - return result; - } else { - OperationData opData = opStatus.left().value(); - Operation newOperation = this.convertOperationDataToOperation(opData); - newOperations.put(operation.getKey(), newOperation); - } - } - interfaceDefResult.setOperationsMap(newOperations); - } - result = Either.left(interfaceDefResult); - return result; - } finally { - if (false == inTransaction) { - if (result == null || result.isRight()) { - log.error("Going to execute rollback on graph."); - titanGenericDao.rollback(); - } else { - log.debug("Going to execute commit on graph."); - titanGenericDao.commit(); - } - } - } - - } - - @Override - public Either<InterfaceDefinition, StorageOperationStatus> getInterface(String interfaceId) { - Either<InterfaceData, TitanOperationStatus> getResult = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Interface), interfaceId, InterfaceData.class); - if (getResult.isLeft()) { - InterfaceData interfaceData = getResult.left().value(); - return Either.left(convertInterfaceDataToInterfaceDefinition(interfaceData)); - } else { - TitanOperationStatus titanStatus = getResult.right().value(); - log.debug("Node with id {} was not found in the graph. status: {}", interfaceId, titanStatus); - StorageOperationStatus storageOperationStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus); - return Either.right(storageOperationStatus); - } - } - - public String getShortInterfaceName(InterfaceDataDefinition interfaceDefinition) { - String[] packageName = interfaceDefinition.getType().split("\\."); - String interfaceName; - if (packageName.length == 0) { - interfaceName = interfaceDefinition.getType(); - } else { - interfaceName = packageName[packageName.length - 1]; - } - return interfaceName.toLowerCase(); - } - - /** - * - */ - public Either<InterfaceDefinition, StorageOperationStatus> createInterfaceType(InterfaceDefinition interf) { - return createInterfaceType(interf, false); - } + Map<String, Object> props = new HashMap<>(); + props.put(GraphPropertiesDictionary.NAME.getProperty(), interfaceName); + Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(resourceData, interfaceData, GraphEdgeLabels.INTERFACE, props); + if (createRelResult.isRight()) { + TitanOperationStatus operationStatus = createNodeResult.right().value(); + log.error("Failed to associate resource {} to property {} in graph. status is {}", resourceId, interfaceName, operationStatus); + + return Either.right(operationStatus); + } + + return Either.left(createNodeResult.left().value()); + } + + private Either<OperationData, TitanOperationStatus> createOperationNodeAndRelation(String operationName, OperationData operationData, InterfaceData interfaceData) { + log.debug("Before adding operation to graph {}", operationData); + Either<OperationData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(operationData, OperationData.class); + log.debug("After adding operation to graph {}", interfaceData); + + if (createNodeResult.isRight()) { + TitanOperationStatus operationStatus = createNodeResult.right().value(); + log.error("Failed to add interfoperationce {} to graph. status is {}", operationName, operationStatus); + return Either.right(operationStatus); + } + + Map<String, Object> props = new HashMap<>(); + props.put(GraphPropertiesDictionary.NAME.getProperty(), operationName); + Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(interfaceData, operationData, GraphEdgeLabels.INTERFACE_OPERATION, props); + if (createRelResult.isRight()) { + TitanOperationStatus operationStatus = createNodeResult.right().value(); + log.error("Failed to associate operation {} to interface {} in graph. status is {}", operationName, interfaceData.getUniqueId(), operationStatus); + + return Either.right(operationStatus); + } + + return Either.left(createNodeResult.left().value()); + } + + @Override + public Either<Map<String, InterfaceDefinition>, StorageOperationStatus> getAllInterfacesOfResource(String resourceIdn, boolean recursively) { + return getAllInterfacesOfResource(resourceIdn, recursively, false); + } + + @Override + public Either<Map<String, InterfaceDefinition>, StorageOperationStatus> getAllInterfacesOfResource(String resourceId, boolean recursively, boolean inTransaction) { + + Either<Map<String, InterfaceDefinition>, StorageOperationStatus> result = null; + Map<String, InterfaceDefinition> interfaces = new HashMap<>(); + try { + if ((resourceId == null) || resourceId.isEmpty()) { + log.error("resourceId is empty"); + result = Either.right(StorageOperationStatus.INVALID_ID); + return result; + } + + TitanOperationStatus findInterfacesRes = TitanOperationStatus.GENERAL_ERROR; + if (recursively) { + findInterfacesRes = findAllInterfacesRecursively(resourceId, interfaces); + } else { + findInterfacesRes = findAllInterfacesNotRecursively(resourceId, interfaces); + } + if (!findInterfacesRes.equals(TitanOperationStatus.OK)) { + log.error("Failed to get all interfaces of resource {}. status is {}", resourceId, findInterfacesRes); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(findInterfacesRes)); + return result; + } + result = Either.left(interfaces); + return result; + } finally { + if (!inTransaction) { + if (result == null || result.isRight()) { + log.error("Going to execute rollback on graph."); + titanGenericDao.rollback(); + } else { + log.debug("Going to execute commit on graph."); + titanGenericDao.commit(); + } + } + } + } + + private TitanOperationStatus findAllInterfacesNotRecursively(String resourceId, Map<String, InterfaceDefinition> interfaces) { + + Either<List<ImmutablePair<InterfaceData, GraphEdge>>, TitanOperationStatus> interfaceNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.INTERFACE, + NodeTypeEnum.Interface, InterfaceData.class); + + if (interfaceNodes.isRight()) { + TitanOperationStatus status = interfaceNodes.right().value(); + if (status != TitanOperationStatus.NOT_FOUND) { + return status; + } + } else { + List<ImmutablePair<InterfaceData, GraphEdge>> interfaceList = interfaceNodes.left().value(); + if (interfaceList != null) { + for (ImmutablePair<InterfaceData, GraphEdge> interfacePair : interfaceList) { + String interfaceUniqueId = (String) interfacePair.getKey().getUniqueId(); + Either<String, TitanOperationStatus> interfaceNameRes = getPropertyValueFromEdge(interfacePair.getValue(), GraphPropertiesDictionary.NAME); + if (interfaceNameRes.isRight()) { + log.error("The requirement name is missing on the edge of requirement {}", interfaceUniqueId); + return interfaceNameRes.right().value(); + } + String interfaceName = interfaceNameRes.left().value(); + Either<InterfaceDefinition, TitanOperationStatus> interfaceDefRes = getNonRecursiveInterface(interfacePair.getKey()); + if (interfaceDefRes.isRight()) { + TitanOperationStatus status = interfaceDefRes.right().value(); + log.error("Failed to get interface actions of interface {}", interfaceUniqueId); + return status; + } + + InterfaceDefinition interfaceDefinition = interfaceDefRes.left().value(); + if (interfaces.containsKey(interfaceName)) { + log.debug("The interface {} was already defined in dervied resource. add not overriden operations", interfaceName); + InterfaceDefinition existInterface = interfaces.get(interfaceName); + addMissingOperationsToInterface(interfaceDefinition, existInterface); + } else { + interfaces.put(interfaceName, interfaceDefinition); + } + + } + } + } + return TitanOperationStatus.OK; + } + + public TitanOperationStatus findAllInterfacesRecursively(String resourceId, Map<String, InterfaceDefinition> interfaces) { + + TitanOperationStatus findAllInterfacesNotRecursively = findAllInterfacesNotRecursively(resourceId, interfaces); + if (!findAllInterfacesNotRecursively.equals(TitanOperationStatus.OK)) { + log.error("failed to get interfaces for resource {}. status is {}", resourceId, findAllInterfacesNotRecursively); + } + + Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> parentNodes = titanGenericDao.getChild(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Resource), resourceId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource, + ResourceMetadataData.class); + + if (parentNodes.isRight()) { + TitanOperationStatus parentNodesStatus = parentNodes.right().value(); + if (parentNodesStatus == TitanOperationStatus.NOT_FOUND) { + log.debug("Finish to lookup for parnet interfaces"); + return TitanOperationStatus.OK; + } else { + log.error("Failed to find parent interfaces of resource {}. status is {}", resourceId, parentNodesStatus); + return parentNodesStatus; + } + } + ImmutablePair<ResourceMetadataData, GraphEdge> parnetNodePair = parentNodes.left().value(); + String parentUniqueId = parnetNodePair.getKey().getMetadataDataDefinition().getUniqueId(); + TitanOperationStatus addParentIntStatus = findAllInterfacesRecursively(parentUniqueId, interfaces); + + if (addParentIntStatus != TitanOperationStatus.OK) { + log.error("Failed to fetch all interfaces of resource {}", parentUniqueId); + return addParentIntStatus; + } + + return TitanOperationStatus.OK; + } + + private Either<String, TitanOperationStatus> getPropertyValueFromEdge(GraphEdge edge, GraphPropertiesDictionary property) { + Map<String, Object> edgeProps = edge.getProperties(); + String interfaceName = null; + if (edgeProps != null) { + interfaceName = (String) edgeProps.get(property.getProperty()); + if (interfaceName == null) { + return Either.right(TitanOperationStatus.INVALID_ELEMENT); + } + } else { + return Either.right(TitanOperationStatus.INVALID_ELEMENT); + } + return Either.left(interfaceName); + } + + private Either<InterfaceDefinition, TitanOperationStatus> getNonRecursiveInterface(InterfaceData interfaceData) { + + log.debug("Going to fetch the operations associate to interface {}", interfaceData.getUniqueId()); + InterfaceDefinition interfaceDefinition = new InterfaceDefinition(interfaceData.getInterfaceDataDefinition()); + + String interfaceId = interfaceData.getUniqueId(); + Either<List<ImmutablePair<OperationData, GraphEdge>>, TitanOperationStatus> operationsRes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), interfaceId, GraphEdgeLabels.INTERFACE_OPERATION, + NodeTypeEnum.InterfaceOperation, OperationData.class); + + if (operationsRes.isRight()) { + TitanOperationStatus status = operationsRes.right().value(); + if (status != TitanOperationStatus.NOT_FOUND) { + return Either.right(status); + } else { + return Either.left(interfaceDefinition); + } + } + + List<ImmutablePair<OperationData, GraphEdge>> operationList = operationsRes.left().value(); + if (operationList != null && !operationList.isEmpty()) { + for (ImmutablePair<OperationData, GraphEdge> operationPair : operationList) { + Operation operation = new Operation(operationPair.getKey().getOperationDataDefinition()); + Either<String, TitanOperationStatus> operationNameRes = getPropertyValueFromEdge(operationPair.getValue(), GraphPropertiesDictionary.NAME); + if (operationNameRes.isRight()) { + log.error("The operation name is missing on the edge of operation {}", operationPair.getKey().getUniqueId()); + return Either.right(operationNameRes.right().value()); + } + String operationName = operationNameRes.left().value(); + findOperationImplementation(operation); + interfaceDefinition.getOperations().put(operationName, operation); + } + } + + return Either.left(interfaceDefinition); + } + + private StorageOperationStatus findOperationImplementation(Operation operation) { + + String operationId = operation.getUniqueId(); + Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsRes = artifactOperation.getArtifacts(operationId, NodeTypeEnum.InterfaceOperation, true); + if (artifactsRes.isRight() || artifactsRes.left().value() == null) { + log.error("failed to get artifact from graph for operation id {}. status is {}", operationId, artifactsRes.right().value()); + return artifactsRes.right().value(); + } else { + Map<String, ArtifactDefinition> artifacts = artifactsRes.left().value(); + Iterator<String> iter = artifacts.keySet().iterator(); + + if (iter.hasNext()) { + operation.setImplementation(artifacts.get(iter.next())); + } + } + return StorageOperationStatus.OK; + } + + private StorageOperationStatus addMissingOperationsToInterface(InterfaceDefinition interfaceDefinition, InterfaceDefinition existInterface) { + Map<String, Operation> existOperations = existInterface.getOperationsMap(); + Map<String, Operation> operations = interfaceDefinition.getOperationsMap(); + if (operations != null && !operations.isEmpty()) { + Set<Entry<String, Operation>> operationsSet = operations.entrySet(); + for (Entry<String, Operation> operation : operationsSet) { + if (!existOperations.containsKey(operation.getKey())) { + existOperations.put(operation.getKey(), operation.getValue()); + } + } + } + return StorageOperationStatus.OK; + } + + @Override + public Either<Operation, StorageOperationStatus> updateInterfaceOperation(String resourceId, String interfaceName, String operationName, Operation interf) { + + return updateInterfaceOperation(resourceId, interfaceName, operationName, interf, false); + } + + @Override + public Either<Operation, StorageOperationStatus> updateInterfaceOperation(String resourceId, String interfaceName, String operationName, Operation operation, boolean inTransaction) { + return updateOperationOnGraph(operation, resourceId, interfaceName, operationName); + } + + private Either<Operation, StorageOperationStatus> updateOperationOnGraph(Operation operation, String resourceId, String interfaceName, String operationName) { + + Either<List<ImmutablePair<InterfaceData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), resourceId, GraphEdgeLabels.INTERFACE, NodeTypeEnum.Interface, + InterfaceData.class); + + if (childrenNodes.isRight()) { + return updateOperationFromParentNode(operation, resourceId, interfaceName, operationName); + + } else { + return updateExistingOperation(resourceId, operation, interfaceName, operationName, childrenNodes); + + } + + } + + private Either<Operation, StorageOperationStatus> updateExistingOperation(String resourceId, Operation operation, String interfaceName, String operationName, + Either<List<ImmutablePair<InterfaceData, GraphEdge>>, TitanOperationStatus> childrenNodes) { + Operation newOperation = null; + StorageOperationStatus storageOperationStatus = StorageOperationStatus.GENERAL_ERROR; + + for (ImmutablePair<InterfaceData, GraphEdge> interfaceDataNode : childrenNodes.left().value()) { + + GraphEdge interfaceEdge = interfaceDataNode.getRight(); + Map<String, Object> interfaceEdgeProp = interfaceEdge.getProperties(); + InterfaceData interfaceData = interfaceDataNode.getKey(); + + if (interfaceEdgeProp.get(GraphPropertiesDictionary.NAME.getProperty()).equals(interfaceName)) { + Either<List<ImmutablePair<OperationData, GraphEdge>>, TitanOperationStatus> operationRes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) interfaceDataNode.getLeft().getUniqueId(), + GraphEdgeLabels.INTERFACE_OPERATION, NodeTypeEnum.InterfaceOperation, OperationData.class); + if (operationRes.isRight()) { + log.error("Failed to find operation {} on interface {}", operationName, interfaceName); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationRes.right().value())); + } else { + List<ImmutablePair<OperationData, GraphEdge>> operations = operationRes.left().value(); + for (ImmutablePair<OperationData, GraphEdge> operationPairEdge : operations) { + GraphEdge opEdge = operationPairEdge.getRight(); + OperationData opData = operationPairEdge.getLeft(); + Map<String, Object> opEdgeProp = opEdge.getProperties(); + if (opEdgeProp.get(GraphPropertiesDictionary.NAME.getProperty()).equals(operationName)) { + ArtifactDefinition artifact = operation.getImplementationArtifact(); + Either<ImmutablePair<ArtifactData, GraphEdge>, TitanOperationStatus> artifactRes = titanGenericDao.getChild(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) opData.getUniqueId(), GraphEdgeLabels.ARTIFACT_REF, + NodeTypeEnum.ArtifactRef, ArtifactData.class); + Either<ArtifactDefinition, StorageOperationStatus> artStatus; + if (artifactRes.isRight()) { + artStatus = artifactOperation.addArifactToComponent(artifact, (String) operationPairEdge.getLeft().getUniqueId(), NodeTypeEnum.InterfaceOperation, true, true); + } else { + artStatus = artifactOperation.updateArifactOnResource(artifact, (String) operationPairEdge.getLeft().getUniqueId(), (String) artifactRes.left().value().getLeft().getUniqueId(), NodeTypeEnum.InterfaceOperation, true); + } + if (artStatus.isRight()) { + titanGenericDao.rollback(); + log.error("Failed to add artifact {} to interface {}", operationName, interfaceName); + return Either.right(artStatus.right().value()); + } else { + newOperation = this.convertOperationDataToOperation(opData); + newOperation.setImplementation(artStatus.left().value()); + + } + + } + + } + if (newOperation == null) { + Either<InterfaceData, TitanOperationStatus> parentInterfaceStatus = findInterfaceOnParentNode(resourceId, interfaceName); + if (parentInterfaceStatus.isRight()) { + log.debug("Interface {} not exist", interfaceName); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentInterfaceStatus.right().value())); + } + + InterfaceData parentInterfaceData = parentInterfaceStatus.left().value(); + Either<List<ImmutablePair<OperationData, GraphEdge>>, TitanOperationStatus> opRes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) parentInterfaceData.getUniqueId(), + GraphEdgeLabels.INTERFACE_OPERATION, NodeTypeEnum.InterfaceOperation, OperationData.class); + if (opRes.isRight()) { + log.error("Failed to find operation {} on interface {}", operationName, interfaceName); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationRes.right().value())); + + } else { + List<ImmutablePair<OperationData, GraphEdge>> parentOperations = opRes.left().value(); + for (ImmutablePair<OperationData, GraphEdge> operationPairEdge : parentOperations) { + GraphEdge opEdge = operationPairEdge.getRight(); + OperationData opData = operationPairEdge.getLeft(); + Map<String, Object> opEdgeProp = opEdge.getProperties(); + if (opEdgeProp.get(GraphPropertiesDictionary.NAME.getProperty()).equals(operationName)) { + return copyAndCreateNewOperation(operation, interfaceName, operationName, null, interfaceData, operationRes, opData); + } + } + } + + } + + } + + } else { + // not found + storageOperationStatus = StorageOperationStatus.ARTIFACT_NOT_FOUND; + } + + } + if (newOperation == null) + return Either.right(storageOperationStatus); + else + return Either.left(newOperation); + } + + private Either<Operation, StorageOperationStatus> copyAndCreateNewOperation(Operation operation, String interfaceName, String operationName, Operation newOperation, InterfaceData interfaceData, + Either<List<ImmutablePair<OperationData, GraphEdge>>, TitanOperationStatus> operationRes, OperationData opData) { + OperationDataDefinition opDataInfo = opData.getOperationDataDefinition(); + OperationDataDefinition newOperationInfo = new OperationDataDefinition(opDataInfo); + newOperationInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(interfaceData.getUniqueId(), operationName.toLowerCase())); + OperationData newopData = new OperationData(newOperationInfo); + Either<OperationData, TitanOperationStatus> operationStatus = createOperationNodeAndRelation(operationName, newopData, interfaceData); + if (operationStatus.isRight()) { + log.error("Failed to create operation {} on interface {}", operationName, interfaceName); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationRes.right().value())); + } + ArtifactDefinition artifact = operation.getImplementationArtifact(); + if (artifact != null) { + Either<ArtifactDefinition, StorageOperationStatus> artStatus = artifactOperation.addArifactToComponent(artifact, (String) operationStatus.left().value().getUniqueId(), NodeTypeEnum.InterfaceOperation, true, true); + if (artStatus.isRight()) { + titanGenericDao.rollback(); + log.error("Failed to add artifact {} to interface {}", operationName, interfaceName); + } else { + newOperation = this.convertOperationDataToOperation(opData); + newOperation.setImplementation(artStatus.left().value()); + + } + } + return Either.left(newOperation); + } + + private Either<Operation, StorageOperationStatus> updateOperationFromParentNode(Operation operation, String resourceId, String interfaceName, String operationName) { + // Operation newOperation = null; + ResourceMetadataData resourceData = new ResourceMetadataData(); + resourceData.getMetadataDataDefinition().setUniqueId(resourceId); + Either<InterfaceData, TitanOperationStatus> parentInterfaceStatus = findInterfaceOnParentNode(resourceId, interfaceName); + if (parentInterfaceStatus.isRight()) { + log.debug("Interface {} not exist", interfaceName); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(parentInterfaceStatus.right().value())); + } + + InterfaceData interfaceData = parentInterfaceStatus.left().value(); + InterfaceDataDefinition intDataDefinition = interfaceData.getInterfaceDataDefinition(); + InterfaceDataDefinition newInterfaceInfo = new InterfaceDataDefinition(intDataDefinition); + + String interfaceNameSplitted = getShortInterfaceName(intDataDefinition); + + newInterfaceInfo.setUniqueId(UniqueIdBuilder.buildPropertyUniqueId(resourceId, interfaceNameSplitted)); + InterfaceData updatedInterfaceData = new InterfaceData(newInterfaceInfo); + Either<InterfaceData, TitanOperationStatus> createStatus = createInterfaceNodeAndRelation(interfaceName, resourceId, updatedInterfaceData, resourceData); + if (createStatus.isRight()) { + log.debug("failed to create interface node {} on resource {}", interfaceName, resourceId); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(createStatus.right().value())); + } + + InterfaceData newInterfaceNode = createStatus.left().value(); + Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(newInterfaceNode, interfaceData, GraphEdgeLabels.DERIVED_FROM, null); + if (createRelResult.isRight()) { + TitanOperationStatus operationStatus = createRelResult.right().value(); + log.error("Failed to associate interface {} to interface {} in graph. status is {}", interfaceData.getUniqueId(), newInterfaceNode.getUniqueId(), operationStatus); + + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationStatus)); + } + Either<List<ImmutablePair<OperationData, GraphEdge>>, TitanOperationStatus> operationRes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) interfaceData.getUniqueId(), + GraphEdgeLabels.INTERFACE_OPERATION, NodeTypeEnum.InterfaceOperation, OperationData.class); + if (operationRes.isRight()) { + log.error("Failed to find operation {} on interface {}", operationName, interfaceName); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationRes.right().value())); + + } else { + List<ImmutablePair<OperationData, GraphEdge>> operations = operationRes.left().value(); + for (ImmutablePair<OperationData, GraphEdge> operationPairEdge : operations) { + GraphEdge opEdge = operationPairEdge.getRight(); + OperationData opData = operationPairEdge.getLeft(); + Map<String, Object> opEdgeProp = opEdge.getProperties(); + if (opEdgeProp.get(GraphPropertiesDictionary.NAME.getProperty()).equals(operationName)) { + + return copyAndCreateNewOperation(operation, interfaceName, operationName, null, // changed + // from + // newOperation + newInterfaceNode, operationRes, opData); + + } + } + } + return Either.right(StorageOperationStatus.GENERAL_ERROR); + } + + private Either<InterfaceData, TitanOperationStatus> findInterfaceOnParentNode(String resourceId, String interfaceName) { + + Either<ImmutablePair<ResourceMetadataData, GraphEdge>, TitanOperationStatus> parentRes = titanGenericDao.getChild(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), resourceId, GraphEdgeLabels.DERIVED_FROM, NodeTypeEnum.Resource, + ResourceMetadataData.class); + if (parentRes.isRight()) { + log.debug("interface {} not found ", interfaceName); + return Either.right(parentRes.right().value()); + } + ImmutablePair<ResourceMetadataData, GraphEdge> parenNode = parentRes.left().value(); + + Either<List<ImmutablePair<InterfaceData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), parenNode.getKey().getMetadataDataDefinition().getUniqueId(), + GraphEdgeLabels.INTERFACE, NodeTypeEnum.Interface, InterfaceData.class); + if (childrenNodes.isRight()) { + return findInterfaceOnParentNode(parenNode.getKey().getMetadataDataDefinition().getUniqueId(), interfaceName); + + } else { + for (ImmutablePair<InterfaceData, GraphEdge> interfaceDataNode : childrenNodes.left().value()) { + + GraphEdge interfaceEdge = interfaceDataNode.getRight(); + Map<String, Object> interfaceEdgeProp = interfaceEdge.getProperties(); + + if (interfaceEdgeProp.get(GraphPropertiesDictionary.NAME.getProperty()).equals(interfaceName)) { + return Either.left(interfaceDataNode.getKey()); + } + + } + return findInterfaceOnParentNode(parenNode.getKey().getMetadataDataDefinition().getUniqueId(), interfaceName); + } + + } + + @Override + public Either<InterfaceDefinition, StorageOperationStatus> createInterfaceOnResource(InterfaceDefinition interf, String resourceId, String interfaceName, boolean failIfExist, boolean inTransaction) { + + Either<InterfaceData, TitanOperationStatus> status = addInterfaceToGraph(interf, interfaceName, resourceId); + + if (status.isRight()) { + titanGenericDao.rollback(); + log.error("Failed to add interface {} to resource {}", interfaceName, resourceId); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status.right().value())); + } else { + + if (!inTransaction) { + titanGenericDao.commit(); + } + InterfaceData interfaceData = status.left().value(); + + InterfaceDefinition interfaceDefResult = convertInterfaceDataToInterfaceDefinition(interfaceData); + Map<String, Operation> operations = interf.getOperationsMap(); + if (operations != null && !operations.isEmpty()) { + Set<String> opNames = operations.keySet(); + Map<String, Operation> newOperations = new HashMap<>(); + for (String operationName : opNames) { + + Operation op = operations.get(operationName); + Either<OperationData, TitanOperationStatus> opStatus = addOperationToGraph(interf, operationName, op, interfaceData); + if (status.isRight()) { + titanGenericDao.rollback(); + log.error("Failed to add operation {} to interface {}", operationName, interfaceName); + } else if (status.isLeft()) { + if (!inTransaction) { + titanGenericDao.commit(); + } + OperationData opData = opStatus.left().value(); + Operation newOperation = this.convertOperationDataToOperation(opData); + + ArtifactDefinition art = op.getImplementationArtifact(); + if (art != null) { + Either<ArtifactDefinition, StorageOperationStatus> artRes = artifactOperation.addArifactToComponent(art, (String) opData.getUniqueId(), NodeTypeEnum.InterfaceOperation, failIfExist, true); + if (artRes.isRight()) { + titanGenericDao.rollback(); + log.error("Failed to add artifact {} to interface {}", operationName, interfaceName); + } else { + newOperation.setImplementation(artRes.left().value()); + } + newOperations.put(operationName, newOperation); + } + } + } + interfaceDefResult.setOperationsMap(newOperations); + } + log.debug("The returned InterfaceDefintion is {}", interfaceDefResult); + return Either.left(interfaceDefResult); + } + + } + + @Override + public Either<Operation, StorageOperationStatus> deleteInterfaceOperation(String resourceId, String interfaceName, String operationId, boolean inTransaction) { + + Either<Operation, TitanOperationStatus> status = removeOperationOnGraph(resourceId, interfaceName, operationId); + if (status.isRight()) { + if (!inTransaction) { + titanGenericDao.rollback(); + } + log.error("Failed to delete operation {} of interface {} resource {}", operationId, interfaceName, resourceId); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status.right().value())); + } else { + if (!inTransaction) { + titanGenericDao.commit(); + } + + Operation opDefResult = status.left().value();// convertOperationDataToOperation(operationData); + log.debug("The returned Operation is {}", opDefResult); + return Either.left(opDefResult); + } + + } + + private Either<Operation, TitanOperationStatus> removeOperationOnGraph(String resourceId, String interfaceName, String operationId) { + log.debug("Before deleting operation from graph {}", operationId); + + Either<List<ImmutablePair<InterfaceData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), resourceId, GraphEdgeLabels.INTERFACE, NodeTypeEnum.Interface, + InterfaceData.class); + + if (childrenNodes.isRight()) { + log.debug("Not found interface {}", interfaceName); + return Either.right(childrenNodes.right().value()); + } + OperationData opData = null; + for (ImmutablePair<InterfaceData, GraphEdge> interfaceDataNode : childrenNodes.left().value()) { + + GraphEdge interfaceEdge = interfaceDataNode.getRight(); + Map<String, Object> interfaceEdgeProp = interfaceEdge.getProperties(); + + String interfaceSplitedName = splitType(interfaceName); + + if (interfaceEdgeProp.get(GraphPropertiesDictionary.NAME.getProperty()).equals(interfaceSplitedName)) { + Either<List<ImmutablePair<OperationData, GraphEdge>>, TitanOperationStatus> operationRes = titanGenericDao.getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) interfaceDataNode.getLeft().getUniqueId(), + GraphEdgeLabels.INTERFACE_OPERATION, NodeTypeEnum.InterfaceOperation, OperationData.class); + if (operationRes.isRight()) { + log.error("Failed to find operation {} on interface {}", operationId, interfaceName); + return Either.right(operationRes.right().value()); + } + List<ImmutablePair<OperationData, GraphEdge>> operations = operationRes.left().value(); + + for (ImmutablePair<OperationData, GraphEdge> operationPairEdge : operations) { + + opData = operationPairEdge.getLeft(); + if (opData.getUniqueId().equals(operationId)) { + + Either<ImmutablePair<ArtifactData, GraphEdge>, TitanOperationStatus> artifactRes = titanGenericDao.getChild(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), (String) operationPairEdge.getLeft().getUniqueId(), + GraphEdgeLabels.ARTIFACT_REF, NodeTypeEnum.ArtifactRef, ArtifactData.class); + Either<ArtifactDefinition, StorageOperationStatus> arStatus = null; + if (artifactRes.isLeft()) { + ArtifactData arData = artifactRes.left().value().getKey(); + arStatus = artifactOperation.removeArifactFromResource((String) operationPairEdge.getLeft().getUniqueId(), (String) arData.getUniqueId(), NodeTypeEnum.InterfaceOperation, true, true); + if (arStatus.isRight()) { + log.debug("failed to delete artifact {}", arData.getUniqueId()); + return Either.right(TitanOperationStatus.INVALID_ID); + } + } + Either<OperationData, TitanOperationStatus> deleteOpStatus = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.InterfaceOperation), opData.getUniqueId(), OperationData.class); + if (deleteOpStatus.isRight()) { + log.debug("failed to delete operation {}", opData.getUniqueId()); + return Either.right(TitanOperationStatus.INVALID_ID); + } + opData = deleteOpStatus.left().value(); + Operation operation = new Operation(opData.getOperationDataDefinition()); + if (arStatus != null) { + operation.setImplementation(arStatus.left().value()); + } + if (operations.size() <= 1) { + Either<InterfaceData, TitanOperationStatus> deleteInterfaceStatus = titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Interface), interfaceDataNode.left.getUniqueId(), InterfaceData.class); + if (deleteInterfaceStatus.isRight()) { + log.debug("failed to delete interface {}", interfaceDataNode.left.getUniqueId()); + return Either.right(TitanOperationStatus.INVALID_ID); + } + + } + + return Either.left(operation); + + } + } + } + } + + log.debug("Not found operation {}", interfaceName); + return Either.right(TitanOperationStatus.INVALID_ID); + } + + private String splitType(String interfaceName) { + String interfaceSplittedName; + String[] packageName = interfaceName.split("\\."); + + if (packageName.length == 0) { + interfaceSplittedName = interfaceName; + } else { + interfaceSplittedName = packageName[packageName.length - 1]; + } + + return interfaceSplittedName.toLowerCase(); + } + + /** + * FOR TEST ONLY + * + * @param titanGenericDao + */ + public void setTitanGenericDao(TitanGenericDao titanGenericDao) { + this.titanGenericDao = titanGenericDao; + } + + public void setArtifactOperation(ArtifactOperation artifactOperation) { + this.artifactOperation = artifactOperation; + } + + @Override + public Either<InterfaceDefinition, StorageOperationStatus> createInterfaceType(InterfaceDefinition interf, boolean inTransaction) { + Either<InterfaceDefinition, StorageOperationStatus> result = null; + try { + + InterfaceData interfaceData = new InterfaceData(interf); + interf.setUniqueId(interf.getType().toLowerCase()); + + Either<InterfaceData, TitanOperationStatus> existInterface = titanGenericDao.getNode(interfaceData.getUniqueIdKey(), interfaceData.getUniqueId(), InterfaceData.class); + + if (existInterface.isLeft()) { + // already exist + log.debug("Interface type already exist {}", interfaceData); + result = Either.right(StorageOperationStatus.ENTITY_ALREADY_EXISTS); + return result; + } + + log.debug("Before adding interface type to graph {}", interfaceData); + Either<InterfaceData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(interfaceData, InterfaceData.class); + log.debug("After adding property type to graph {}", interfaceData); + + if (createNodeResult.isRight()) { + TitanOperationStatus operationStatus = createNodeResult.right().value(); + log.error("Failed to add interface {} to graph. status is {}", interf.getType(), operationStatus); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(operationStatus)); + return result; + } + + InterfaceDefinition interfaceDefResult = convertInterfaceDataToInterfaceDefinition(interfaceData); + Map<String, Operation> operations = interf.getOperationsMap(); + + if (operations != null && !operations.isEmpty()) { + Map<String, Operation> newOperations = new HashMap<>(); + + for (Map.Entry<String, Operation> operation : operations.entrySet()) { + Either<OperationData, TitanOperationStatus> opStatus = addOperationToGraph(interf, operation.getKey(), operation.getValue(), interfaceData); + if (opStatus.isRight()) { + titanGenericDao.rollback(); + log.error("Failed to add operation {} to interface {}", operation.getKey(), interf.getType()); + + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(opStatus.right().value())); + return result; + } else { + OperationData opData = opStatus.left().value(); + Operation newOperation = this.convertOperationDataToOperation(opData); + newOperations.put(operation.getKey(), newOperation); + } + } + interfaceDefResult.setOperationsMap(newOperations); + } + result = Either.left(interfaceDefResult); + return result; + } finally { + if (!inTransaction) { + if (result == null || result.isRight()) { + log.error("Going to execute rollback on graph."); + titanGenericDao.rollback(); + } else { + log.debug("Going to execute commit on graph."); + titanGenericDao.commit(); + } + } + } + + } + + @Override + public Either<InterfaceDefinition, StorageOperationStatus> getInterface(String interfaceId) { + Either<InterfaceData, TitanOperationStatus> getResult = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Interface), interfaceId, InterfaceData.class); + if (getResult.isLeft()) { + InterfaceData interfaceData = getResult.left().value(); + return Either.left(convertInterfaceDataToInterfaceDefinition(interfaceData)); + } else { + TitanOperationStatus titanStatus = getResult.right().value(); + log.debug("Node with id {} was not found in the graph. status: {}", interfaceId, titanStatus); + StorageOperationStatus storageOperationStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(titanStatus); + return Either.right(storageOperationStatus); + } + } + + public String getShortInterfaceName(InterfaceDataDefinition interfaceDefinition) { + String[] packageName = interfaceDefinition.getType().split("\\."); + String interfaceName; + if (packageName.length == 0) { + interfaceName = interfaceDefinition.getType(); + } else { + interfaceName = packageName[packageName.length - 1]; + } + return interfaceName.toLowerCase(); + } + + /** + * + */ + public Either<InterfaceDefinition, StorageOperationStatus> createInterfaceType(InterfaceDefinition interf) { + return createInterfaceType(interf, false); + } } 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 new file mode 100644 index 0000000000..6093eb0433 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/Neo4jStatusConverter.java @@ -0,0 +1,78 @@ +/*- + * ============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/OnboardingClient.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/OnboardingClient.java index 7d299c85d1..8e1ee19358 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/OnboardingClient.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/OnboardingClient.java @@ -20,13 +20,7 @@ package org.openecomp.sdc.be.model.operations.impl; -import java.io.File; -import java.io.FileFilter; -import java.io.IOException; -import java.nio.file.Files; -import java.util.Map; -import java.util.Properties; - +import fj.data.Either; import org.apache.commons.io.filefilter.WildcardFileFilter; import org.apache.http.HttpStatus; import org.openecomp.sdc.be.config.Configuration.OnboardingConfig; @@ -35,155 +29,157 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.http.client.api.HttpRequest; import org.openecomp.sdc.common.http.client.api.HttpResponse; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.util.ZipUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import fj.data.Either; +import java.io.File; +import java.io.FileFilter; +import java.io.IOException; +import java.nio.file.Files; +import java.util.Map; +import java.util.Properties; @org.springframework.stereotype.Component("onboarding-client") public class OnboardingClient { - private static Logger log = LoggerFactory.getLogger(OnboardingClient.class.getName()); - - private static Properties downloadCsarHeaders = new Properties(); - - static { - downloadCsarHeaders.put("Accept", "application/octet-stream"); - } - - public OnboardingClient() { - super(); - } - - public static void main(String[] args) { - - OnboardingClient csarOperation = new OnboardingClient(); - - String csarUuid = "70025CF6081B489CA7B1CBA583D5278D"; - Either<Map<String, byte[]>, StorageOperationStatus> csar = csarOperation.getCsar(csarUuid, null); - System.out.println(csar.left().value()); - - } - - public Either<Map<String, byte[]>, StorageOperationStatus> getMockCsar(String csarUuid) { - File dir = new File("/var/tmp/mockCsar"); - FileFilter fileFilter = new WildcardFileFilter("*.csar"); - File[] files = dir.listFiles(fileFilter); - for (int i = 0; i < files.length; i++) { - File csar = files[i]; - if (csar.getName().startsWith(csarUuid)) { - log.debug("Found CSAR file {} matching the passed csarUuid {}", csar.getAbsolutePath(), csarUuid); - byte[] data; - try { - data = Files.readAllBytes(csar.toPath()); - } catch (IOException e) { - log.debug("Error reading mock file for CSAR, error: {}", e); - return Either.right(StorageOperationStatus.NOT_FOUND); - } - Map<String, byte[]> readZip = ZipUtil.readZip(data); - return Either.left(readZip); - } - } - log.debug("Couldn't find mock file for CSAR starting with {}", csarUuid); - return Either.right(StorageOperationStatus.NOT_FOUND); - } - - public Either<Map<String, byte[]>, StorageOperationStatus> getCsar(String csarUuid, String userId) { - String url = buildDownloadCsarUrl() + "/" + csarUuid; - - Properties headers = new Properties(); - if (downloadCsarHeaders != null) { - downloadCsarHeaders.forEach((k, v) -> headers.put(k, v)); - } - - if (userId != null) { - headers.put(Constants.USER_ID_HEADER, userId); - } - - log.debug("Url for downloading csar is {}. Headers are {}", url, headers); - - try { - HttpResponse<byte []> httpResponse = HttpRequest.getAsByteArray(url, headers); - log.debug("After fetching csar {}. Http return code is {}", csarUuid, httpResponse.getStatusCode()); - - switch (httpResponse.getStatusCode()) { - case HttpStatus.SC_OK: - byte[] data = httpResponse.getResponse(); - if (data != null && data.length > 0) { - Map<String, byte[]> readZip = ZipUtil.readZip(data); - return Either.left(readZip); - } else { - log.debug("Data received from rest is null or empty"); - return Either.right(StorageOperationStatus.NOT_FOUND); - } - - case HttpStatus.SC_NOT_FOUND: - return Either.right(StorageOperationStatus.CSAR_NOT_FOUND); - - default: - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - } - catch(Exception e) { - log.debug("Request failed with exception {}", e); - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - } - - public Either<String, StorageOperationStatus> getPackages(String userId) { - String url = buildDownloadCsarUrl(); - - Properties headers = new Properties(); - headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"); - - if (userId != null) { - headers.put(Constants.USER_ID_HEADER, userId); - } - - log.debug("Url for downloading packages is {}. Headers are {}", url, headers); - - try { - HttpResponse<String> httpResposne = HttpRequest.get(url, headers); - log.debug("After fetching packages. Http return code is {}", httpResposne.getStatusCode()); + private static final Logger log = Logger.getLogger(OnboardingClient.class.getName()); + + private static Properties downloadCsarHeaders = new Properties(); + + static { + downloadCsarHeaders.put("Accept", "application/octet-stream"); + } + + public OnboardingClient() { + super(); + } + + public static void main(String[] args) { + + OnboardingClient csarOperation = new OnboardingClient(); + + String csarUuid = "70025CF6081B489CA7B1CBA583D5278D"; + Either<Map<String, byte[]>, StorageOperationStatus> csar = csarOperation.getCsar(csarUuid, null); + System.out.println(csar.left().value()); + + } + + public Either<Map<String, byte[]>, StorageOperationStatus> getMockCsar(String csarUuid) { + File dir = new File("/var/tmp/mockCsar"); + FileFilter fileFilter = new WildcardFileFilter("*.csar"); + File[] files = dir.listFiles(fileFilter); + for (int i = 0; i < files.length; i++) { + File csar = files[i]; + if (csar.getName().startsWith(csarUuid)) { + log.debug("Found CSAR file {} matching the passed csarUuid {}", csar.getAbsolutePath(), csarUuid); + byte[] data; + try { + data = Files.readAllBytes(csar.toPath()); + } catch (IOException e) { + log.debug("Error reading mock file for CSAR, error: {}", e); + return Either.right(StorageOperationStatus.NOT_FOUND); + } + Map<String, byte[]> readZip = ZipUtil.readZip(data); + return Either.left(readZip); + } + } + log.debug("Couldn't find mock file for CSAR starting with {}", csarUuid); + return Either.right(StorageOperationStatus.NOT_FOUND); + } + + public Either<Map<String, byte[]>, StorageOperationStatus> getCsar(String csarUuid, String userId) { + String url = buildDownloadCsarUrl() + "/" + csarUuid; + + Properties headers = new Properties(); + if (downloadCsarHeaders != null) { + downloadCsarHeaders.forEach(headers::put); + } + + if (userId != null) { + headers.put(Constants.USER_ID_HEADER, userId); + } + + log.debug("Url for downloading csar is {}. Headers are {}", url, headers); + + try { + HttpResponse<byte []> httpResponse = HttpRequest.getAsByteArray(url, headers); + log.debug("After fetching csar {}. Http return code is {}", csarUuid, httpResponse.getStatusCode()); - switch (httpResposne.getStatusCode()) { - case HttpStatus.SC_OK: - String data = httpResposne.getResponse(); - return Either.left(data); + switch (httpResponse.getStatusCode()) { + case HttpStatus.SC_OK: + byte[] data = httpResponse.getResponse(); + if (data != null && data.length > 0) { + Map<String, byte[]> readZip = ZipUtil.readZip(data); + return Either.left(readZip); + } else { + log.debug("Data received from rest is null or empty"); + return Either.right(StorageOperationStatus.NOT_FOUND); + } - case HttpStatus.SC_NOT_FOUND: - return Either.right(StorageOperationStatus.CSAR_NOT_FOUND); + case HttpStatus.SC_NOT_FOUND: + return Either.right(StorageOperationStatus.CSAR_NOT_FOUND); - default: - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - } - catch(Exception e) { + default: + return Either.right(StorageOperationStatus.GENERAL_ERROR); + } + } + catch(Exception e) { log.debug("Request failed with exception {}", e); return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - } + } + } - /** - * Build the url for download CSAR - * - * E.g., http://0.0.0.0:8181/onboarding-api/v1.0/vendor-software-products/packages/ - * - * @return - */ - public String buildDownloadCsarUrl() { + public Either<String, StorageOperationStatus> getPackages(String userId) { + String url = buildDownloadCsarUrl(); - OnboardingConfig onboardingConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getOnboarding(); + Properties headers = new Properties(); + headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"); - String protocol = onboardingConfig.getProtocol(); - String host = onboardingConfig.getHost(); - Integer port = onboardingConfig.getPort(); - String uri = onboardingConfig.getDownloadCsarUri(); + if (userId != null) { + headers.put(Constants.USER_ID_HEADER, userId); + } - String getCsarUrl = protocol + "://" + host + ":" + port + uri; + log.debug("Url for downloading packages is {}. Headers are {}", url, headers); - return getCsarUrl; - } + try { + HttpResponse<String> httpResposne = HttpRequest.get(url, headers); + log.debug("After fetching packages. Http return code is {}", httpResposne.getStatusCode()); + + switch (httpResposne.getStatusCode()) { + case HttpStatus.SC_OK: + String data = httpResposne.getResponse(); + return Either.left(data); + + case HttpStatus.SC_NOT_FOUND: + return Either.right(StorageOperationStatus.CSAR_NOT_FOUND); + + default: + return Either.right(StorageOperationStatus.GENERAL_ERROR); + } + } + catch(Exception e) { + log.debug("Request failed with exception {}", e); + return Either.right(StorageOperationStatus.GENERAL_ERROR); + } + } + + /** + * Build the url for download CSAR + * + * E.g., http://0.0.0.0:8181/onboarding-api/v1.0/vendor-software-products/packages/ + * + * @return + */ + public String buildDownloadCsarUrl() { + + OnboardingConfig onboardingConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getOnboarding(); + + String protocol = onboardingConfig.getProtocol(); + String host = onboardingConfig.getHost(); + Integer port = onboardingConfig.getPort(); + String uri = onboardingConfig.getDownloadCsarUri(); + + return protocol + "://" + host + ":" + port + uri; + } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/OperationUtils.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/OperationUtils.java new file mode 100644 index 0000000000..dcaafe55ac --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/OperationUtils.java @@ -0,0 +1,21 @@ +package org.openecomp.sdc.be.model.operations.impl; + +import org.openecomp.sdc.be.dao.jsongraph.TitanDao; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.model.operations.StorageException; +import org.springframework.stereotype.Component; + +@Component +public class OperationUtils { + + private final TitanDao titanDao; + + public OperationUtils(TitanDao titanDao) { + this.titanDao = titanDao; + } + + public <T> T onTitanOperationFailure(TitanOperationStatus status) { + titanDao.rollback(); + throw new StorageException(status); + } +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperation.java index 11355f3387..76652e1cce 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/PolicyTypeOperation.java @@ -20,15 +20,8 @@ package org.openecomp.sdc.be.model.operations.impl; -import static org.openecomp.sdc.be.dao.titan.TitanUtils.buildNotInPredicate; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - +import com.thinkaurelius.titan.graphdb.query.TitanPredicate; +import fj.data.Either; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; @@ -42,19 +35,19 @@ import org.openecomp.sdc.be.model.operations.api.IPolicyTypeOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.resources.data.PolicyTypeData; import org.openecomp.sdc.be.resources.data.PropertyData; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import com.thinkaurelius.titan.graphdb.query.TitanPredicate; +import java.util.*; +import java.util.stream.Collectors; -import fj.data.Either; +import static org.openecomp.sdc.be.dao.titan.TitanUtils.buildNotInPredicate; @Component("policy-type-operation") public class PolicyTypeOperation extends AbstractOperation implements IPolicyTypeOperation { - private static final Logger log = LoggerFactory.getLogger(PolicyTypeOperation.class.getName()); + private static final Logger log = Logger.getLogger(PolicyTypeOperation.class.getName()); private static final String CREATE_FLOW_CONTEXT = "CreatePolicyType"; private static final String GET_FLOW_CONTEXT = "GetPolicyType"; @@ -62,6 +55,8 @@ public class PolicyTypeOperation extends AbstractOperation implements IPolicyTyp private PropertyOperation propertyOperation; @Autowired private DerivedFromOperation derivedFromOperation; + @Autowired + private OperationUtils operationUtils; @Override public Either<PolicyTypeDefinition, StorageOperationStatus> getLatestPolicyTypeByType(String type) { @@ -94,18 +89,17 @@ public class PolicyTypeOperation extends AbstractOperation implements IPolicyTyp @Override public Either<PolicyTypeDefinition, StorageOperationStatus> updatePolicyType(PolicyTypeDefinition updatedPolicyType, PolicyTypeDefinition currPolicyType) { log.debug("updating policy type {}", updatedPolicyType.getType()); - updatePolicyTypeData(updatedPolicyType, currPolicyType); return updatePolicyTypeOnGraph(updatedPolicyType, currPolicyType); } @Override - public Either<List<PolicyTypeDefinition>, StorageOperationStatus> getAllPolicyTypes(Set<String> excludedPolicyTypes) { + public List<PolicyTypeDefinition> getAllPolicyTypes(Set<String> excludedPolicyTypes) { Map<String, Map.Entry<TitanPredicate, Object>> predicateCriteria = buildNotInPredicate(GraphPropertiesDictionary.TYPE.getProperty(), excludedPolicyTypes); return titanGenericDao.getByCriteriaWithPredicate(NodeTypeEnum.PolicyType, predicateCriteria, PolicyTypeData.class) .left() .map(this::convertPolicyTypesToDefinition) - .right() - .map(DaoStatusConverter::convertTitanStatusToStorageStatus); + .left() + .on(operationUtils::onTitanOperationFailure); } private List<PolicyTypeDefinition> convertPolicyTypesToDefinition(List<PolicyTypeData> policiesTypes) { @@ -116,7 +110,7 @@ public class PolicyTypeOperation extends AbstractOperation implements IPolicyTyp private Either<PolicyTypeData, StorageOperationStatus> addPolicyTypeToGraph(PolicyTypeDefinition policyTypeDef) { log.debug("Got policy type {}", policyTypeDef); - String ptUniqueId = UniqueIdBuilder.buildPolicyTypeUid(policyTypeDef.getType(), policyTypeDef.getVersion()); + String ptUniqueId = UniqueIdBuilder.buildPolicyTypeUid(policyTypeDef.getType(), policyTypeDef.getVersion(), "policytype"); PolicyTypeData policyTypeData = buildPolicyTypeData(policyTypeDef, ptUniqueId); log.debug("Before adding policy type to graph. policyTypeData = {}", policyTypeData); Either<PolicyTypeData, TitanOperationStatus> eitherPolicyTypeData = titanGenericDao.createNode(policyTypeData, PolicyTypeData.class); 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 86e5b1b466..5e900e4041 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 @@ -20,25 +20,22 @@ package org.openecomp.sdc.be.model.operations.impl; -import java.io.IOException; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.StringJoiner; -import java.util.function.Consumer; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; - +import com.fasterxml.jackson.core.ObjectCodec; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonNode; +import com.google.common.collect.Maps; +import com.google.gson.*; +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.TitanVertex; +import com.thinkaurelius.titan.core.TitanVertexProperty; +import fj.data.Either; import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.tinkerpop.gremlin.structure.Edge; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.apache.tinkerpop.gremlin.structure.VertexProperty; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; import org.openecomp.sdc.be.dao.graph.GraphElementFactory; @@ -54,56 +51,41 @@ import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyRule; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.IComplexDefaultValue; -import org.openecomp.sdc.be.model.PropertyConstraint; -import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.operations.api.DerivedFromOperation; import org.openecomp.sdc.be.model.operations.api.IPropertyOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; -import org.openecomp.sdc.be.model.tosca.constraints.ConstraintType; -import org.openecomp.sdc.be.model.tosca.constraints.GreaterOrEqualConstraint; -import org.openecomp.sdc.be.model.tosca.constraints.GreaterThanConstraint; -import org.openecomp.sdc.be.model.tosca.constraints.InRangeConstraint; -import org.openecomp.sdc.be.model.tosca.constraints.LessOrEqualConstraint; -import org.openecomp.sdc.be.model.tosca.constraints.LessThanConstraint; -import org.openecomp.sdc.be.model.tosca.constraints.MinLengthConstraint; -import org.openecomp.sdc.be.model.tosca.constraints.ValidValuesConstraint; +import org.openecomp.sdc.be.model.tosca.constraints.*; import org.openecomp.sdc.be.model.tosca.converters.PropertyValueConverter; -import org.openecomp.sdc.be.resources.data.ComponentInstanceData; -import org.openecomp.sdc.be.resources.data.DataTypeData; -import org.openecomp.sdc.be.resources.data.PropertyData; -import org.openecomp.sdc.be.resources.data.PropertyValueData; -import org.openecomp.sdc.be.resources.data.ResourceMetadataData; -import org.openecomp.sdc.be.resources.data.UniqueIdData; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.be.resources.data.*; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.stereotype.Component; -import com.fasterxml.jackson.core.ObjectCodec; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonNode; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.JsonParser; -import com.google.gson.JsonSerializationContext; -import com.google.gson.JsonSerializer; -import com.thinkaurelius.titan.core.TitanVertex; +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.*; +import java.util.Map.Entry; +import java.util.function.Consumer; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; -import fj.data.Either; @Component("property-operation") public class PropertyOperation extends AbstractOperation implements IPropertyOperation { - - private TitanGenericDao titanGenericDao; + private static final String FAILED_TO_FETCH_PROPERTIES_OF_DATA_TYPE = "Failed to fetch properties of data type {}"; + private static final String DATA_TYPE_CANNOT_BE_FOUND_IN_GRAPH_STATUS_IS = "Data type {} cannot be found in graph. status is {}"; + private static final String GOING_TO_EXECUTE_COMMIT_ON_GRAPH = "Going to execute commit on graph."; + private static final String GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH = "Going to execute rollback on graph."; + private static final String FAILED_TO_ASSOCIATE_RESOURCE_TO_PROPERTY_IN_GRAPH_STATUS_IS = "Failed to associate resource {} to property {} in graph. status is {}"; + private static final String AFTER_ADDING_PROPERTY_TO_GRAPH = "After adding property to graph {}"; + private static final String BEFORE_ADDING_PROPERTY_TO_GRAPH = "Before adding property to graph {}"; + private static final String THE_VALUE_OF_PROPERTY_FROM_TYPE_IS_INVALID = "The value {} of property from type {} is invalid"; private DerivedFromOperation derivedFromOperation; - + private static final String PROPERTY = "Property"; + private static final String UPDATE_DATA_TYPE = "UpdateDataType"; + public static void main(String[] args) { List<Pattern> buildFunctionPatterns = buildFunctionPatterns(); @@ -124,14 +106,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe this.derivedFromOperation = derivedFromOperation; } - private static Logger log = LoggerFactory.getLogger(PropertyOperation.class.getName()); - - private static List<Pattern> functionPatterns = null; - - static { - - functionPatterns = buildFunctionPatterns(); - } + private static Logger log = Logger.getLogger(PropertyOperation.class.getName()); /** * The value of functions is in a json format. Build pattern for each function name @@ -160,7 +135,6 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe PropertyDefinition propertyDefResult = new PropertyDefinition(propertyDataResult.getPropertyDataDefinition()); propertyDefResult.setConstraints(convertConstraints(propertyDataResult.getConstraints())); propertyDefResult.setName(propertyName); -// propertyDefResult.setParentUniqueId(resourceId); return propertyDefResult; } @@ -196,6 +170,8 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe public static class PropertyConstraintDeserialiser implements JsonDeserializer<PropertyConstraint> { + private static final String THE_VALUE_OF_GREATER_THAN_CONSTRAINT_IS_NULL = "The value of GreaterThanConstraint is null"; + @Override public PropertyConstraint deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { @@ -231,7 +207,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe } } else { - log.warn("The value of GreaterThanConstraint is null"); + log.warn(THE_VALUE_OF_GREATER_THAN_CONSTRAINT_IS_NULL); } break; case GREATER_THAN: @@ -241,7 +217,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe propertyConstraint = new GreaterThanConstraint(asString); break; } else { - log.warn("The value of GreaterThanConstraint is null"); + log.warn(THE_VALUE_OF_GREATER_THAN_CONSTRAINT_IS_NULL); } break; @@ -272,7 +248,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe log.debug("Before adding value to LessOrEqualConstraint object. value = {}", asString); propertyConstraint = new LessOrEqualConstraint(asString); } else { - log.warn("The value of GreaterThanConstraint is null"); + log.warn(THE_VALUE_OF_GREATER_THAN_CONSTRAINT_IS_NULL); } break; @@ -285,7 +261,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe log.error("The valid values constraint content is invalid. value = {}", value); } else { ValidValuesConstraint vvConstraint = new ValidValuesConstraint(); - List<String> validValues = new ArrayList<String>(); + List<String> validValues = new ArrayList<>(); for (JsonElement jsonElement : rangeArray) { String item = jsonElement.getAsString(); validValues.add(item); @@ -321,60 +297,6 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe } - public TitanOperationStatus addPropertiesToGraph(Map<String, PropertyDefinition> properties, String resourceId, Map<String, DataTypeDefinition> dataTypes) { - - ResourceMetadataData resourceData = new ResourceMetadataData(); - resourceData.getMetadataDataDefinition().setUniqueId(resourceId); - - if (properties != null) { - for (Entry<String, PropertyDefinition> entry : properties.entrySet()) { - - String propertyName = entry.getKey(); - PropertyDefinition propertyDefinition = entry.getValue(); - - StorageOperationStatus validateAndUpdateProperty = validateAndUpdateProperty(propertyDefinition, dataTypes); - if (validateAndUpdateProperty != StorageOperationStatus.OK) { - log.error("Property {} is invalid. Status is {}", propertyDefinition, validateAndUpdateProperty); - return TitanOperationStatus.ILLEGAL_ARGUMENT; - } - - Either<PropertyData, TitanOperationStatus> addPropertyToGraph = addPropertyToGraph(propertyName, propertyDefinition, resourceId); - - if (addPropertyToGraph.isRight()) { - return addPropertyToGraph.right().value(); - } - } - } - - return TitanOperationStatus.OK; - - } - - public TitanOperationStatus addPropertiesToGraph(TitanVertex metadataVertex, Map<String, PropertyDefinition> properties, Map<String, DataTypeDefinition> dataTypes, String resourceId) { - - if (properties != null) { - for (Entry<String, PropertyDefinition> entry : properties.entrySet()) { - - String propertyName = entry.getKey(); - PropertyDefinition propertyDefinition = entry.getValue(); - - StorageOperationStatus validateAndUpdateProperty = validateAndUpdateProperty(propertyDefinition, dataTypes); - if (validateAndUpdateProperty != StorageOperationStatus.OK) { - log.error("Property {} is invalid. Status is {}", propertyDefinition, validateAndUpdateProperty); - return TitanOperationStatus.ILLEGAL_ARGUMENT; - } - - TitanOperationStatus addPropertyToGraph = addPropertyToGraphByVertex(metadataVertex, propertyName, propertyDefinition, resourceId); - - if (!addPropertyToGraph.equals(TitanOperationStatus.OK)) { - return addPropertyToGraph; - } - } - } - - return TitanOperationStatus.OK; - - } public Either<PropertyData, StorageOperationStatus> addProperty(String propertyName, PropertyDefinition propertyDefinition, String resourceId) { @@ -408,14 +330,12 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe return StorageOperationStatus.INVALID_TYPE; } - StorageOperationStatus status = validateAndUpdateComplexValue(propertyDefinition, propertyType, value, dataTypeDefinition, dataTypes); - - return status; + return validateAndUpdateComplexValue(propertyDefinition, propertyType, value, dataTypeDefinition, dataTypes); } String innerType = null; - Either<String, TitanOperationStatus> checkInnerType = getInnerType(type, () -> propertyDefinition.getSchema()); + Either<String, TitanOperationStatus> checkInnerType = getInnerType(type, propertyDefinition::getSchema); if (checkInnerType.isRight()) { return StorageOperationStatus.INVALID_TYPE; } @@ -424,8 +344,8 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe log.trace("After validating property type {}", propertyType); boolean isValidProperty = isValidValue(type, value, innerType, dataTypes); - if (false == isValidProperty) { - log.info("The value {} of property from type {} is invalid", value, type); + if (!isValidProperty) { + log.info(THE_VALUE_OF_PROPERTY_FROM_TYPE_IS_INVALID, value, type); return StorageOperationStatus.INVALID_VALUE; } @@ -434,7 +354,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe if (isEmptyValue(value)) { log.debug("Default value was not sent for property {}. Set default value to {}", propertyDefinition.getName(), EMPTY_VALUE); propertyDefinition.setDefaultValue(EMPTY_VALUE); - } else if (false == isEmptyValue(value)) { + } else if (!isEmptyValue(value)) { String convertedValue = converter.convert(value, innerType, dataTypes); propertyDefinition.setDefaultValue(convertedValue); } @@ -451,21 +371,21 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe propertyDefinition.setUniqueId(UniqueIdBuilder.buildComponentPropertyUniqueId(resourceId, propertyName)); PropertyData propertyData = new PropertyData(propertyDefinition, convertConstraintsToString(constraints)); - log.debug("Before adding property to graph {}", propertyData); + log.debug(BEFORE_ADDING_PROPERTY_TO_GRAPH, propertyData); Either<PropertyData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(propertyData, PropertyData.class); - log.debug("After adding property to graph {}", propertyData); + log.debug(AFTER_ADDING_PROPERTY_TO_GRAPH, propertyData); if (createNodeResult.isRight()) { TitanOperationStatus operationStatus = createNodeResult.right().value(); log.error("Failed to add property {} to graph. status is {}", propertyName, operationStatus); return Either.right(operationStatus); } - Map<String, Object> props = new HashMap<String, Object>(); + Map<String, Object> props = new HashMap<>(); props.put(GraphPropertiesDictionary.NAME.getProperty(), propertyName); Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(resourceData, propertyData, GraphEdgeLabels.PROPERTY, props); if (createRelResult.isRight()) { TitanOperationStatus operationStatus = createNodeResult.right().value(); - log.error("Failed to associate resource {} to property {} in graph. status is {}", resourceId, propertyName, operationStatus); + log.error(FAILED_TO_ASSOCIATE_RESOURCE_TO_PROPERTY_IN_GRAPH_STATUS_IS, resourceId, propertyName, operationStatus); return Either.right(operationStatus); } @@ -480,21 +400,21 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe propertyDefinition.setUniqueId(UniqueIdBuilder.buildComponentPropertyUniqueId(resourceId, propertyName)); PropertyData propertyData = new PropertyData(propertyDefinition, convertConstraintsToString(constraints)); - log.debug("Before adding property to graph {}", propertyData); + log.debug(BEFORE_ADDING_PROPERTY_TO_GRAPH, propertyData); Either<TitanVertex, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(propertyData); - log.debug("After adding property to graph {}", propertyData); + log.debug(AFTER_ADDING_PROPERTY_TO_GRAPH, propertyData); if (createNodeResult.isRight()) { TitanOperationStatus operationStatus = createNodeResult.right().value(); log.error("Failed to add property {} to graph. status is ", propertyName, operationStatus); return operationStatus; } - Map<String, Object> props = new HashMap<String, Object>(); + Map<String, Object> props = new HashMap<>(); props.put(GraphPropertiesDictionary.NAME.getProperty(), propertyName); TitanVertex propertyVertex = createNodeResult.left().value(); TitanOperationStatus createRelResult = titanGenericDao.createEdge(metadataVertex, propertyVertex, GraphEdgeLabels.PROPERTY, props); if (!createRelResult.equals(TitanOperationStatus.OK)) { - log.error("Failed to associate resource {} to property {} in graph. status is {}", resourceId, propertyName, createRelResult); + log.error(FAILED_TO_ASSOCIATE_RESOURCE_TO_PROPERTY_IN_GRAPH_STATUS_IS, resourceId, propertyName, createRelResult); return createRelResult; } @@ -506,20 +426,6 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe return titanGenericDao; } - // public Either<PropertyData, StorageOperationStatus> - // deletePropertyFromGraphFromBl(String propertyId) { - // - // } - - public Either<PropertyData, StorageOperationStatus> deleteProperty(String propertyId) { - Either<PropertyData, TitanOperationStatus> either = deletePropertyFromGraph(propertyId); - if (either.isRight()) { - StorageOperationStatus storageStatus = DaoStatusConverter.convertTitanStatusToStorageStatus(either.right().value()); - return Either.right(storageStatus); - } - return Either.left(either.left().value()); - } - public Either<PropertyData, TitanOperationStatus> deletePropertyFromGraph(String propertyId) { log.debug("Before deleting property from graph {}", propertyId); return titanGenericDao.deleteNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.Property), propertyId, PropertyData.class); @@ -601,17 +507,17 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe PropertyData propertyData = new PropertyData(propertyDefinition, convertConstraintsToString(constraints)); if (log.isDebugEnabled()) - log.debug("Before adding property to graph {}", propertyData); + log.debug(BEFORE_ADDING_PROPERTY_TO_GRAPH, propertyData); Either<PropertyData, TitanOperationStatus> createNodeResult = titanGenericDao.createNode(propertyData, PropertyData.class); if (log.isDebugEnabled()) - log.debug("After adding property to graph {}", propertyData); + log.debug(AFTER_ADDING_PROPERTY_TO_GRAPH, propertyData); if (createNodeResult.isRight()) { TitanOperationStatus operationStatus = createNodeResult.right().value(); log.error("Failed to add property {} to graph. status is {}", propertyName, operationStatus); return Either.right(operationStatus); } - Map<String, Object> props = new HashMap<String, Object>(); + Map<String, Object> props = new HashMap<>(); props.put(GraphPropertiesDictionary.NAME.getProperty(), propertyName); UniqueIdData uniqueIdData = new UniqueIdData(nodeType, uniqueId); @@ -619,7 +525,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao.createRelation(uniqueIdData, propertyData, GraphEdgeLabels.PROPERTY, props); if (createRelResult.isRight()) { TitanOperationStatus operationStatus = createNodeResult.right().value(); - log.error("Failed to associate resource {} to property {} in graph. status is {}", uniqueId, propertyName, operationStatus); + log.error(FAILED_TO_ASSOCIATE_RESOURCE_TO_PROPERTY_IN_GRAPH_STATUS_IS, uniqueId, propertyName, operationStatus); return Either.right(operationStatus); } @@ -629,7 +535,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe public Either<Map<String, PropertyDefinition>, TitanOperationStatus> findPropertiesOfNode(NodeTypeEnum nodeType, String uniqueId) { - Map<String, PropertyDefinition> resourceProps = new HashMap<String, PropertyDefinition>(); + Map<String, PropertyDefinition> resourceProps = new HashMap<>(); Either<List<ImmutablePair<PropertyData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, GraphEdgeLabels.PROPERTY, NodeTypeEnum.Property, PropertyData.class); @@ -662,6 +568,139 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe .right() .bind(err -> err == StorageOperationStatus.OK ? Either.left(Collections.emptyMap()) : Either.right(err)); } + + public Either<Map<String, PropertyData>, TitanOperationStatus> mergePropertiesAssociatedToNode(NodeTypeEnum nodeType, String uniqueId, Map<String, PropertyDefinition> newProperties) { + Either<Map<String, PropertyDefinition>, TitanOperationStatus> oldPropertiesRes = findPropertiesOfNode(nodeType, uniqueId); + + Map<String, PropertyDefinition> reallyNewProperties; + Map<String, PropertyData> unchangedPropsData; + + if (oldPropertiesRes.isRight()) { + TitanOperationStatus err = oldPropertiesRes.right().value(); + if (err == TitanOperationStatus.NOT_FOUND) { + reallyNewProperties = newProperties; + unchangedPropsData = Collections.emptyMap(); + } + else { + return Either.right(err); + } + } + else { + Map<String, PropertyDefinition> oldProperties = oldPropertiesRes.left().value(); + reallyNewProperties = collectReallyNewProperties(newProperties, oldProperties); + + for(Entry<String, PropertyDefinition> oldEntry: oldProperties.entrySet()) { + String key = oldEntry.getKey(); + PropertyDefinition newPropDef = newProperties != null? newProperties.get(key): null; + PropertyDefinition oldPropDef = oldEntry.getValue(); + + TitanOperationStatus status = updateOldProperty(newPropDef, oldPropDef); + if (status != TitanOperationStatus.OK) { + return Either.right(status); + } + } + unchangedPropsData = oldProperties.entrySet().stream() + .collect(Collectors.toMap(Entry::getKey, e-> new PropertyData(e.getValue(), null))); + } + + + // add other properties + return addPropertiesToElementType(nodeType, uniqueId, reallyNewProperties, unchangedPropsData); + } + + /** + * @param newProperties + * @param oldProperties + * @return + */ + private Map<String, PropertyDefinition> collectReallyNewProperties(Map<String, PropertyDefinition> newProperties, Map<String, PropertyDefinition> oldProperties) { + return newProperties != null? newProperties.entrySet().stream() + .filter(entry -> !oldProperties.containsKey(entry.getKey())) + .collect(Collectors.toMap(Entry::getKey, Entry::getValue) ): null; + } + + /** + * @param newPropDef + * @param oldPropDef + */ + private TitanOperationStatus updateOldProperty(PropertyDefinition newPropDef, PropertyDefinition oldPropDef) { + if (!isUpdateAllowed(newPropDef, oldPropDef)) { + return TitanOperationStatus.MATCH_NOT_FOUND; + } + + if (isUpdateRequired(newPropDef, oldPropDef)) { + modifyOldPropByNewOne(newPropDef, oldPropDef); + + List<PropertyConstraint> constraints = oldPropDef.getConstraints(); + PropertyData node = new PropertyData(oldPropDef, convertConstraintsToString(constraints)); + Either<PropertyData, TitanOperationStatus> updateResult = titanGenericDao.updateNode(node, PropertyData.class); + + if (updateResult.isRight()) { + return updateResult.right().value(); + } + } + + return TitanOperationStatus.OK; + } + + /** + * @param newPropDef + * @param oldPropDef + */ + private boolean isUpdateAllowed(PropertyDefinition newPropDef, PropertyDefinition oldPropDef) { + if (newPropDef == null) { + log.error("#mergePropertiesAssociatedToNode - Failed due attempt to delete the property with id {}", oldPropDef.getUniqueId()); + return false; + } + + // If the property type is missing it's something that we could want to fix + if ( oldPropDef.getType() != null && !oldPropDef.getType().equals(newPropDef.getType())) { + log.error("#mergePropertiesAssociatedToNode - Failed due attempt to change type of the property with id {}", oldPropDef.getUniqueId()); + return false; + } + + return true; + } + + /** + * Update only fields which modification is permitted. + * @param newPropDef + * @param oldPropDef + */ + private void modifyOldPropByNewOne(PropertyDefinition newPropDef, PropertyDefinition oldPropDef) { + oldPropDef.setDefaultValue(newPropDef.getDefaultValue()); + oldPropDef.setDescription(newPropDef.getDescription()); + oldPropDef.setRequired(newPropDef.isRequired()); + + // Type is updated to fix possible null type issue in TITAN DB + oldPropDef.setType(newPropDef.getType()); + } + + + private boolean isUpdateRequired(PropertyDefinition newPropDef, PropertyDefinition oldPropDef) { + return !StringUtils.equals(oldPropDef.getDefaultValue(), newPropDef.getDefaultValue()) || + !StringUtils.equals(oldPropDef.getDescription(), newPropDef.getDescription()) || + oldPropDef.isRequired() != newPropDef.isRequired(); + } + + /** + * Adds newProperties and returns in case of success (left part of Either) + * map of all properties i. e. added ones and contained in unchangedPropsData + * @param nodeType + * @param uniqueId + * @param newProperties + * @param unchangedPropsData + * @return + */ + private Either<Map<String, PropertyData>, TitanOperationStatus> addPropertiesToElementType(NodeTypeEnum nodeType, String uniqueId, Map<String, PropertyDefinition> newProperties, Map<String, PropertyData> unchangedPropsData) { + return addPropertiesToElementType(uniqueId, nodeType, newProperties) + .left() + .map(m -> { + m.putAll(unchangedPropsData); + return m; + }); + } + public Either<Map<String, PropertyDefinition>, StorageOperationStatus> deleteAllPropertiesAssociatedToNode(NodeTypeEnum nodeType, String uniqueId) { @@ -695,50 +734,6 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe return Either.left(value); } - /** - * - * - * @param nodeType - * @param uniqueId - * @param properties - * @return - */ - protected TitanOperationStatus findPropertiesOfNode(NodeTypeEnum nodeType, String uniqueId, List<PropertyDefinition> properties) { - - Either<List<ImmutablePair<PropertyData, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeType), uniqueId, GraphEdgeLabels.PROPERTY, NodeTypeEnum.Property, - PropertyData.class); - - if (childrenNodes.isRight()) { - TitanOperationStatus status = childrenNodes.right().value(); - if (status == TitanOperationStatus.NOT_FOUND) { - status = TitanOperationStatus.OK; - } - return status; - } - - List<ImmutablePair<PropertyData, GraphEdge>> values = childrenNodes.left().value(); - if (values != null) { - - for (ImmutablePair<PropertyData, GraphEdge> immutablePair : values) { - GraphEdge edge = immutablePair.getValue(); - String propertyName = (String) edge.getProperties().get(GraphPropertiesDictionary.NAME.getProperty()); - if (log.isDebugEnabled()) - log.debug("Property {} is associated to node {}", propertyName, uniqueId); - PropertyData propertyData = immutablePair.getKey(); - PropertyDefinition propertyDefinition = this.convertPropertyDataToPropertyDefinition(propertyData, propertyName, uniqueId); - //Adds parent property to List if it hasn't been overrided in one of the children - if(!properties.stream().filter(p -> p.getName().equals(propertyDefinition.getName())).findAny().isPresent()){ - properties.add(propertyDefinition); - } - - if (log.isTraceEnabled()) - log.trace("findPropertiesOfNode - property {} associated to node {}", propertyDefinition, uniqueId); - } - - } - - return TitanOperationStatus.OK; - } /** * Checks existence of a property with the same name belonging to the same resource * or existence of property with the same name and different type (including derived from hierarchy) @@ -763,73 +758,10 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe return result; } - /** - * add property to resource instance - * - * @param innerType - * TODO // * @param resourceInstanceProperty // * @param resourceInstanceId // * @param index - * - * @return - */ - /* - * public Either<PropertyValueData, TitanOperationStatus> addPropertyToResourceInstance( ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, Integer index) { - * - * Either<ComponentInstanceData, TitanOperationStatus> findResInstanceRes = titanGenericDao .getNode(UniqueIdBuilder .getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId, ComponentInstanceData.class); - * - * if (findResInstanceRes.isRight()) { TitanOperationStatus status = findResInstanceRes.right().value(); if (status == TitanOperationStatus.NOT_FOUND) { status = TitanOperationStatus.INVALID_ID; } return Either.right(status); } - * - * String propertyId = resourceInstanceProperty.getUniqueId(); Either<PropertyData, TitanOperationStatus> findPropertyDefRes = titanGenericDao .getNode(UniqueIdBuilder .getKeyByNodeType(NodeTypeEnum.Property), propertyId, PropertyData.class); - * - * if (findPropertyDefRes.isRight()) { TitanOperationStatus status = findPropertyDefRes.right().value(); if (status == TitanOperationStatus.NOT_FOUND) { status = TitanOperationStatus.INVALID_ID; } return Either.right(status); } - * - * String valueUniqueUid = resourceInstanceProperty.getValueUniqueUid(); if (valueUniqueUid == null) { - * - * PropertyData propertyData = findPropertyDefRes.left().value(); ComponentInstanceData resourceInstanceData = findResInstanceRes.left().value(); - * - * ImmutablePair<TitanOperationStatus, String> isPropertyValueExists = findPropertyValue(resourceInstanceId, propertyId); if (isPropertyValueExists.getLeft() == TitanOperationStatus.ALREADY_EXIST) { log.debug("The property " + propertyId + - * " already added to the resource instance " + resourceInstanceId); resourceInstanceProperty.setValueUniqueUid(isPropertyValueExists.getRight ()); Either<PropertyValueData, TitanOperationStatus> updatePropertyOfResourceInstance = - * updatePropertyOfResourceInstance(resourceInstanceProperty, resourceInstanceId); if (updatePropertyOfResourceInstance.isRight()) { BeEcompErrorManager.getInstance().logInternalFlowError( "UpdatePropertyValueOnComponentInstance", - * "Failed to update property value on instance. Status is " + updatePropertyOfResourceInstance.right().value(), ErrorSeverity.ERROR); return Either.right(updatePropertyOfResourceInstance.right().value()); } return - * Either.left(updatePropertyOfResourceInstance.left().value()); } - * - * if (isPropertyValueExists.getLeft() != TitanOperationStatus.NOT_FOUND) { - * log.debug("After finding property value of {} on componenet instance {}", propertyId, resourceInstanceId); - * return Either.right(isPropertyValueExists.getLeft()); } - * - * String propertyType = propertyData.getPropertyDataDefinition().getType(); String value = resourceInstanceProperty.getValue(); Either<Object, Boolean> isValid = validateAndUpdatePropertyValue(propertyType, value); - * - * String newValue = value; if (isValid.isRight()) { Boolean res = isValid.right().value(); if (res == false) { return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); } } else { Object object = isValid.left().value(); if (object != null) { - * newValue = object.toString(); } } - * - * String uniqueId = UniqueIdBuilder.buildResourceInstancePropertyValueUid( resourceInstanceData.getUniqueId(), index); PropertyValueData propertyValueData = new PropertyValueData(); propertyValueData.setUniqueId(uniqueId); - * propertyValueData.setValue(newValue); - * - * ImmutablePair<String, Boolean> pair = validateAndUpdateRules(propertyType, resourceInstanceProperty.getRules()); if (pair.getRight() != null && pair.getRight() == false) { BeEcompErrorManager.getInstance(). - * logBeInvalidValueError("Add property value", pair.getLeft(), resourceInstanceProperty.getName(), propertyType); return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); } addRulesToNewPropertyValue(propertyValueData, - * resourceInstanceProperty, resourceInstanceId); - * - * log.debug("Before adding property value to graph {}", propertyValueData); - * Either<PropertyValueData, TitanOperationStatus> createNodeResult = titanGenericDao .createNode(propertyValueData, PropertyValueData.class); - * log.debug("After adding property value to graph {}", propertyValueData); - * - * Either<GraphRelation, TitanOperationStatus> createRelResult = titanGenericDao .createRelation(propertyValueData, propertyData, GraphEdgeLabels.PROPERTY_IMPL, null); - * - * if (createRelResult.isRight()) { TitanOperationStatus operationStatus = createNodeResult.right() .value(); //TODO: change logger log.error("Failed to associate property value " + uniqueId + " to property " + propertyId + - * " in graph. status is " + operationStatus); return Either.right(operationStatus); } - * - * createRelResult = titanGenericDao .createRelation(resourceInstanceData, propertyValueData, GraphEdgeLabels.PROPERTY_VALUE, null); - * - * if (createRelResult.isRight()) { TitanOperationStatus operationStatus = createNodeResult.right() .value(); //TODO: change logger log.error("Failed to associate resource instance " + resourceInstanceId + " property value " + uniqueId + - * " in graph. status is " + operationStatus); return Either.right(operationStatus); } - * - * return Either.left(createNodeResult.left().value()); } else { log.error("property value already exists."); return Either.right(TitanOperationStatus.ALREADY_EXIST); } - * - * } - */ public ImmutablePair<String, Boolean> validateAndUpdateRules(String propertyType, List<PropertyRule> rules, String innerType, Map<String, DataTypeDefinition> dataTypes, boolean isValidate) { - if (rules == null || rules.isEmpty() == true) { - return new ImmutablePair<String, Boolean>(null, true); + if (rules == null || rules.isEmpty()) { + return new ImmutablePair<>(null, true); } for (PropertyRule rule : rules) { @@ -837,8 +769,8 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe Either<Object, Boolean> updateResult = validateAndUpdatePropertyValue(propertyType, value, isValidate, innerType, dataTypes); if (updateResult.isRight()) { Boolean status = updateResult.right().value(); - if (status == false) { - return new ImmutablePair<String, Boolean>(value, status); + if (!status) { + return new ImmutablePair<>(value, status); } } else { String newValue = null; @@ -850,7 +782,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe } } - return new ImmutablePair<String, Boolean>(null, true); + return new ImmutablePair<>(null, true); } public void addRulesToNewPropertyValue(PropertyValueData propertyValueData, ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId) { @@ -873,7 +805,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe // graph. // Update could be done on one level only, thus we can use this // operation to avoid migration. - if (path == null || path.isEmpty() == true) { + if (path == null || path.isEmpty()) { path = new ArrayList<>(); path.add(resourceInstanceId); } @@ -900,7 +832,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe if (getAllRes.isRight()) { TitanOperationStatus status = getAllRes.right().value(); log.trace("After fetching all properties of resource instance {}. Status is {}", resourceInstanceId, status); - return new ImmutablePair<TitanOperationStatus, String>(status, null); + return new ImmutablePair<>(status, null); } List<ComponentInstanceProperty> list = getAllRes.left().value(); @@ -911,63 +843,14 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe log.trace("Go over property {} under resource instance {}. valueUniqueId = {}", propertyUniqueId, resourceInstanceId, valueUniqueUid); if (propertyId.equals(propertyUniqueId) && valueUniqueUid != null) { log.debug("The property {} already created under resource instance {}", propertyId, resourceInstanceId); - return new ImmutablePair<TitanOperationStatus, String>(TitanOperationStatus.ALREADY_EXIST, valueUniqueUid); + return new ImmutablePair<>(TitanOperationStatus.ALREADY_EXIST, valueUniqueUid); } } } - return new ImmutablePair<TitanOperationStatus, String>(TitanOperationStatus.NOT_FOUND, null); + return new ImmutablePair<>(TitanOperationStatus.NOT_FOUND, null); } - /** - * update value of property on resource instance - * - * @param resourceInstanceProperty - * @param resourceInstanceId - * @return - */ - /* - * public Either<PropertyValueData, TitanOperationStatus> updatePropertyOfResourceInstance( ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId) { - * - * /// #RULES SUPPORT /// Ignore rules received from client till support resourceInstanceProperty.setRules(null); /// /// Either<ComponentInstanceData, TitanOperationStatus> findResInstanceRes = titanGenericDao .getNode(UniqueIdBuilder - * .getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId, ComponentInstanceData.class); - * - * if (findResInstanceRes.isRight()) { TitanOperationStatus status = findResInstanceRes.right().value(); if (status == TitanOperationStatus.NOT_FOUND) { status = TitanOperationStatus.INVALID_ID; } return Either.right(status); } - * - * String propertyId = resourceInstanceProperty.getUniqueId(); Either<PropertyData, TitanOperationStatus> findPropertyDefRes = titanGenericDao .getNode(UniqueIdBuilder .getKeyByNodeType(NodeTypeEnum.Property), propertyId, PropertyData.class); - * - * if (findPropertyDefRes.isRight()) { TitanOperationStatus status = findPropertyDefRes.right().value(); return Either.right(status); } - * - * String valueUniqueUid = resourceInstanceProperty.getValueUniqueUid(); if (valueUniqueUid == null) { return Either.right(TitanOperationStatus.INVALID_ID); } else { Either<PropertyValueData, TitanOperationStatus> findPropertyValueRes = - * titanGenericDao .getNode(UniqueIdBuilder .getKeyByNodeType(NodeTypeEnum.PropertyValue), valueUniqueUid, PropertyValueData.class); if (findPropertyValueRes.isRight()) { TitanOperationStatus status = findPropertyValueRes.right().value(); if - * (status == TitanOperationStatus.NOT_FOUND) { status = TitanOperationStatus.INVALID_ID; } return Either.right(status); } - * - * String value = resourceInstanceProperty.getValue(); - * - * Either<ImmutablePair<PropertyData, GraphEdge>, TitanOperationStatus> child = titanGenericDao.getChild(UniqueIdBuilder .getKeyByNodeType(NodeTypeEnum.PropertyValue), valueUniqueUid, GraphEdgeLabels.PROPERTY_IMPL, NodeTypeEnum.Property, - * PropertyData.class); - * - * if (child.isRight()) { TitanOperationStatus status = child.right().value(); if (status == TitanOperationStatus.NOT_FOUND) { status = TitanOperationStatus.INVALID_ID; } return Either.right(status); } - * - * PropertyData propertyData = child.left().value().left; String propertyType = propertyData.getPropertyDataDefinition().getType(); - * - * log.debug("The type of the property {} is {}", propertyData.getUniqueId(), propertyType); - * - * Either<Object, Boolean> isValid = validateAndUpdatePropertyValue(propertyType, value); - * - * String newValue = value; if (isValid.isRight()) { Boolean res = isValid.right().value(); if (res == false) { return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); } } else { Object object = isValid.left().value(); if (object != null) { - * newValue = object.toString(); } } PropertyValueData propertyValueData = findPropertyValueRes.left().value(); log.debug("Going to update property value from " + propertyValueData.getValue() + " to " + newValue); - * propertyValueData.setValue(newValue); - * - * ImmutablePair<String, Boolean> pair = validateAndUpdateRules(propertyType, resourceInstanceProperty.getRules()); if (pair.getRight() != null && pair.getRight() == false) { BeEcompErrorManager.getInstance(). - * logBeInvalidValueError("Add property value", pair.getLeft(), resourceInstanceProperty.getName(), propertyType); return Either.right(TitanOperationStatus.ILLEGAL_ARGUMENT); } updateRulesInPropertyValue(propertyValueData, - * resourceInstanceProperty, resourceInstanceId); - * - * Either<PropertyValueData, TitanOperationStatus> updateRes = titanGenericDao.updateNode(propertyValueData, PropertyValueData.class); if (updateRes.isRight()) { TitanOperationStatus status = updateRes.right().value(); return - * Either.right(status); } else { return Either.left(updateRes.left().value()); } } - * - * } - */ public void updateRulesInPropertyValue(PropertyValueData propertyValueData, ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId) { @@ -998,7 +881,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe List<PropertyRule> mergedRules = new ArrayList<>(); - if (newRules == null || newRules.isEmpty() == true) { + if (newRules == null || newRules.isEmpty()) { return currentRules; } @@ -1021,7 +904,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe private PropertyRule findRuleInList(PropertyRule rule, List<PropertyRule> rules) { - if (rules == null || rules.isEmpty() == true || rule.getRule() == null || rule.getRule().isEmpty() == true) { + if (rules == null || rules.isEmpty() || rule.getRule() == null || rule.getRule().isEmpty()) { return null; } @@ -1031,7 +914,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe continue; } boolean equals = propertyRule.compareRule(rule); - if (equals == true) { + if (equals) { foundRule = propertyRule; break; } @@ -1052,48 +935,6 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe } - /* - * public Either<ComponentInstanceProperty, StorageOperationStatus> addPropertyValueToResourceInstance( ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, Integer index, boolean inTransaction) { - * - * /// #RULES SUPPORT /// Ignore rules received from client till support resourceInstanceProperty.setRules(null); /// /// - * - * Either<ComponentInstanceProperty, StorageOperationStatus> result = null; - * - * try { - * - * Either<PropertyValueData, TitanOperationStatus> eitherStatus = this .addPropertyToResourceInstance(resourceInstanceProperty, resourceInstanceId, index); - * - * if (eitherStatus.isRight()) { log.error( "Failed to add property value {} to resource instance {} in Graph. status is {}" , resourceInstanceProperty, resourceInstanceId, eitherStatus.right().value().name()); result = - * Either.right(DaoStatusConverter .convertTitanStatusToStorageStatus(eitherStatus.right() .value())); return result; } else { PropertyValueData propertyValueData = eitherStatus.left() .value(); - * - * ComponentInstanceProperty propertyValueResult = buildResourceInstanceProperty( propertyValueData, resourceInstanceProperty); - * - * log.debug("The returned ResourceInstanceProperty is {}", propertyValueResult); result = Either.left(propertyValueResult); return result; } } - * - * finally { if (false == inTransaction) { if (result == null || result.isRight()) { log.error("Going to execute rollback on graph."); titanGenericDao.rollback(); } else { log.debug("Going to execute commit on graph."); titanGenericDao.commit(); - * } } } - * - * } - * - * public Either<ComponentInstanceProperty, StorageOperationStatus> updatePropertyValueInResourceInstance( ComponentInstanceProperty resourceInstanceProperty, String resourceInstanceId, boolean inTransaction) { - * - * Either<ComponentInstanceProperty, StorageOperationStatus> result = null; - * - * try { //TODO: verify validUniqueId exists Either<PropertyValueData, TitanOperationStatus> eitherStatus = this .updatePropertyOfResourceInstance(resourceInstanceProperty, resourceInstanceId); - * - * if (eitherStatus.isRight()) { log.error( "Failed to add property value {} to resource instance {} in Graph. status is {}" , resourceInstanceProperty, resourceInstanceId, eitherStatus.right().value().name()); result = - * Either.right(DaoStatusConverter .convertTitanStatusToStorageStatus(eitherStatus.right() .value())); return result; } else { PropertyValueData propertyValueData = eitherStatus.left() .value(); - * - * ComponentInstanceProperty propertyValueResult = buildResourceInstanceProperty( propertyValueData, resourceInstanceProperty); - * - * log.debug("The returned ResourceInstanceProperty is {}", propertyValueResult); result = Either.left(propertyValueResult); return result; } } - * - * finally { if (false == inTransaction) { if (result == null || result.isRight()) { log.error("Going to execute rollback on graph."); titanGenericDao.rollback(); } else { log.debug("Going to execute commit on graph."); titanGenericDao.commit(); - * } } } - * - * } - */ - public Either<PropertyValueData, TitanOperationStatus> removePropertyOfResourceInstance(String propertyValueUid, String resourceInstanceId) { Either<ComponentInstanceData, TitanOperationStatus> findResInstanceRes = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ResourceInstance), resourceInstanceId, ComponentInstanceData.class); @@ -1161,12 +1002,12 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe } finally { - if (false == inTransaction) { + if (!inTransaction) { if (result == null || result.isRight()) { - log.error("Going to execute rollback on graph."); + log.error(GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH); titanGenericDao.rollback(); } else { - log.debug("Going to execute commit on graph."); + log.debug(GOING_TO_EXECUTE_COMMIT_ON_GRAPH); titanGenericDao.commit(); } } @@ -1256,7 +1097,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe public ImmutablePair<String, Boolean> isPropertyInnerTypeValid(IComplexDefaultValue property, Map<String, DataTypeDefinition> dataTypes) { if (property == null) { - return new ImmutablePair<String, Boolean>(null, false); + return new ImmutablePair<>(null, false); } SchemaDefinition schema; @@ -1274,22 +1115,16 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe DataTypeDefinition dataTypeDefinition = dataTypes.get(innerType); if (dataTypeDefinition == null) { log.debug("The inner type {} is not a data type.", innerType); - return new ImmutablePair<String, Boolean>(innerType, false); + return new ImmutablePair<>(innerType, false); } else { log.debug("The inner type {} is a data type. Data type definition is {}", innerType, dataTypeDefinition); } } - return new ImmutablePair<String, Boolean>(innerType, true); + return new ImmutablePair<>(innerType, true); } private boolean isValidComplexValue(DataTypeDefinition foundDt, String value, Map<String, DataTypeDefinition> dataTypes) { - /* - * Either<Map<String, DataTypeDefinition>, TitanOperationStatus> allDataTypesRes = getAllDataTypes(); if (allDataTypesRes.isRight()) { TitanOperationStatus status = allDataTypesRes.right().value(); - * return false; } - * - * Map<String, DataTypeDefinition> allDataTypes = allDataTypesRes.left().value(); - */ ImmutablePair<JsonElement, Boolean> validateAndUpdate = dataTypeValidatorConverter.validateAndUpdate(value, foundDt, dataTypes); log.trace("The result after validating complex value of type {} is {}", foundDt.getName(), validateAndUpdate); @@ -1318,7 +1153,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe } List<ImmutablePair<TitanVertex, Edge>> list = propertyImplNodes.left().value(); - if (list == null || true == list.isEmpty()) { + if (list == null || list.isEmpty()) { return Either.right(TitanOperationStatus.NOT_FOUND); } @@ -1486,7 +1321,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe continue; } // check that the rule starts with correct component instance id - if (false == checkFirstItem(firstCompInstance, rule.getFirstToken())) { + if (!checkFirstItem(firstCompInstance, rule.getFirstToken())) { continue; } @@ -1664,9 +1499,9 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe */ private Either<Map<String, PropertyData>, TitanOperationStatus> addPropertiesToDataType(String uniqueId, List<PropertyDefinition> properties) { - Map<String, PropertyData> propertiesData = new HashMap<String, PropertyData>(); + Map<String, PropertyData> propertiesData = new HashMap<>(); - if (properties != null && false == properties.isEmpty()) { + if (properties != null && !properties.isEmpty()) { for (PropertyDefinition propertyDefinition : properties) { String propertyName = propertyDefinition.getName(); @@ -1677,7 +1512,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe return Either.right(validPropertyType.right().value()); } Boolean isValid = validPropertyType.left().value(); - if (isValid == null || isValid.booleanValue() == false) { + if (isValid == null || !isValid.booleanValue()) { log.debug("Data type {} contains invalid property type {}", uniqueId, propertyType); return Either.right(TitanOperationStatus.INVALID_TYPE); } @@ -1727,7 +1562,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe if (dataTypesRes.isRight()) { TitanOperationStatus status = dataTypesRes.right().value(); - log.debug("Data type {} cannot be found in graph. status is {}", uniqueId, status); + log.debug(DATA_TYPE_CANNOT_BE_FOUND_IN_GRAPH_STATUS_IS, uniqueId, status); return Either.right(status); } @@ -1736,7 +1571,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe TitanOperationStatus propertiesStatus = fillProperties(uniqueId, dataTypeDefinition); if (propertiesStatus != TitanOperationStatus.OK) { - log.error("Failed to fetch properties of data type {}", uniqueId); + log.error(FAILED_TO_FETCH_PROPERTIES_OF_DATA_TYPE, uniqueId); return Either.right(propertiesStatus); } @@ -1785,7 +1620,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe } } else { Map<String, PropertyDefinition> properties = findPropertiesOfNode.left().value(); - if (properties != null && properties.isEmpty() == false) { + if (properties != null && !properties.isEmpty()) { List<PropertyDefinition> listOfProps = new ArrayList<>(); for (Entry<String, PropertyDefinition> entry : properties.entrySet()) { @@ -1823,12 +1658,12 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe return result; } } finally { - if (false == inTransaction) { + if (!inTransaction) { if (result == null || result.isRight()) { - log.error("Going to execute rollback on graph."); + log.error(GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH); titanGenericDao.rollback(); } else { - log.debug("Going to execute commit on graph."); + log.debug(GOING_TO_EXECUTE_COMMIT_ON_GRAPH); titanGenericDao.commit(); } } @@ -1863,12 +1698,12 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe return result; } finally { - if (false == inTransaction) { + if (!inTransaction) { if (result == null || result.isRight()) { - log.error("Going to execute rollback on graph."); + log.error(GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH); titanGenericDao.rollback(); } else { - log.debug("Going to execute commit on graph."); + log.debug(GOING_TO_EXECUTE_COMMIT_ON_GRAPH); titanGenericDao.commit(); } } @@ -1907,12 +1742,12 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe return result; } finally { - if (false == inTransaction) { + if (!inTransaction) { if (result == null || result.isRight()) { - log.error("Going to execute rollback on graph."); + log.error(GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH); titanGenericDao.rollback(); } else { - log.debug("Going to execute commit on graph."); + log.debug(GOING_TO_EXECUTE_COMMIT_ON_GRAPH); titanGenericDao.commit(); } } @@ -1926,7 +1761,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe if (dataTypesRes.isRight()) { TitanOperationStatus status = dataTypesRes.right().value(); - log.debug("Data type {} cannot be found in graph. status is {}", uniqueId, status); + log.debug(DATA_TYPE_CANNOT_BE_FOUND_IN_GRAPH_STATUS_IS, uniqueId, status); return Either.right(status); } @@ -1935,7 +1770,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe TitanOperationStatus propertiesStatus = fillProperties(uniqueId, dataTypeDefinition); if (propertiesStatus != TitanOperationStatus.OK) { - log.error("Failed to fetch properties of data type {}", uniqueId); + log.error(FAILED_TO_FETCH_PROPERTIES_OF_DATA_TYPE, uniqueId); return Either.right(propertiesStatus); } @@ -1952,9 +1787,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe protected DataTypeDefinition convertDTDataToDTDefinition(DataTypeData dataTypeData) { log.debug("The object returned after create data type is {}", dataTypeData); - DataTypeDefinition dataTypeDefResult = new DataTypeDefinition(dataTypeData.getDataTypeDataDefinition()); - - return dataTypeDefResult; + return new DataTypeDefinition(dataTypeData.getDataTypeDataDefinition()); } private Either<Boolean, TitanOperationStatus> isValidPropertyType(String propertyType) { @@ -1965,8 +1798,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe ToscaPropertyType toscaPropertyType = ToscaPropertyType.isValidType(propertyType); if (toscaPropertyType == null) { - Either<Boolean, TitanOperationStatus> definedInDataTypes = isDefinedInDataTypes(propertyType); - return definedInDataTypes; + return isDefinedInDataTypes(propertyType); } else { return Either.left(true); } @@ -2058,7 +1890,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe if (dataTypesRes.isRight()) { TitanOperationStatus status = dataTypesRes.right().value(); - log.debug("Data type {} cannot be found in graph. status is {}", uniqueId, status); + log.debug(DATA_TYPE_CANNOT_BE_FOUND_IN_GRAPH_STATUS_IS, uniqueId, status); return Either.right(status); } @@ -2067,7 +1899,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe TitanOperationStatus propertiesStatus = fillProperties(uniqueId, dataTypeDefinition); if (propertiesStatus != TitanOperationStatus.OK) { - log.error("Failed to fetch properties of data type {}", uniqueId); + log.error(FAILED_TO_FETCH_PROPERTIES_OF_DATA_TYPE, uniqueId); return Either.right(propertiesStatus); } @@ -2125,7 +1957,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); - return getInnerType(type, () -> propDataDef.getSchema()); + return getInnerType(type, propDataDef::getSchema); } public Either<List<DataTypeData>, TitanOperationStatus> getAllDataTypeNodes() { @@ -2150,7 +1982,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType); ImmutablePair<JsonElement, Boolean> validateResult = dataTypeValidatorConverter.validateAndUpdate(value, dataTypeDefinition, dataTypes); if (Boolean.FALSE.equals(validateResult.right)) { - log.debug("The value {} of property from type {} is invalid", value, propertyType); + log.debug(THE_VALUE_OF_PROPERTY_FROM_TYPE_IS_INVALID, value, propertyType); return Either.right(false); } JsonElement jsonElement = validateResult.left; @@ -2160,7 +1992,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe log.trace("before validating property type {}", propertyType); boolean isValidProperty = isValidValue(type, value, innerType, dataTypes); if (!isValidProperty) { - log.debug("The value {} of property from type {} is invalid", value, type); + log.debug(THE_VALUE_OF_PROPERTY_FROM_TYPE_IS_INVALID, value, type); return Either.right(false); } } @@ -2197,7 +2029,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe Either<T, StorageOperationStatus> derivedFrom; while ((derivedFrom = derivedFromOperation.getDerivedFromChild(currentNodeUid, nodeType, clazz)).isLeft()) { currentNodeUid = derivedFrom.left().value().getUniqueId(); - TitanOperationStatus titanOperationStatus = fillProperties(currentNodeUid, nodeType, accumulatedProps::addAll); + TitanOperationStatus titanOperationStatus = fillPropertiesList(currentNodeUid, nodeType, accumulatedProps::addAll); if (titanOperationStatus != TitanOperationStatus.OK) { log.debug("failed to fetch properties for type {} with id {}", nodeType, currentNodeUid); return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(titanOperationStatus)); @@ -2214,28 +2046,30 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe /* * @Override public PropertyOperation getPropertyOperation() { return this; } */ - protected TitanOperationStatus fillProperties(String uniqueId, NodeTypeEnum nodeType, Consumer<List<PropertyDefinition>> propertySetter) { - Either<Map<String, PropertyDefinition>, TitanOperationStatus> findPropertiesOfNode = this.findPropertiesOfNode(nodeType, uniqueId); - if (findPropertiesOfNode.isRight()) { - TitanOperationStatus titanOperationStatus = findPropertiesOfNode.right().value(); - log.debug("After looking for properties of vertex {}. status is {}", uniqueId, titanOperationStatus); - if (TitanOperationStatus.NOT_FOUND.equals(titanOperationStatus)) { - return TitanOperationStatus.OK; - } else { - return titanOperationStatus; - } - } else { - Map<String, PropertyDefinition> properties = findPropertiesOfNode.left().value(); - - if (properties != null) { - List<PropertyDefinition> propertiesAsList = properties.entrySet().stream().map(p -> p.getValue()).collect(Collectors.toList()); - propertySetter.accept(propertiesAsList); - } - - return TitanOperationStatus.OK; + public TitanOperationStatus fillPropertiesList(String uniqueId, NodeTypeEnum nodeType, Consumer<List<PropertyDefinition>> propertySetter) { + Either<Map<String, PropertyDefinition>, TitanOperationStatus> findPropertiesRes = findPropertiesifExist(uniqueId, nodeType); + if (findPropertiesRes.isRight()) { + return findPropertiesRes.right().value(); + } + Map<String, PropertyDefinition> properties = findPropertiesRes.left().value(); + if (properties != null) { + List<PropertyDefinition> propertiesAsList = properties.entrySet().stream().map(Entry::getValue).collect(Collectors.toList()); + propertySetter.accept(propertiesAsList); } + return TitanOperationStatus.OK; } + Either<Map<String, PropertyDefinition>, TitanOperationStatus> findPropertiesifExist(String uniqueId, NodeTypeEnum nodeType){ + Either<Map<String, PropertyDefinition>, TitanOperationStatus> findPropertiesOfNode = this.findPropertiesOfNode(nodeType, uniqueId); + if (findPropertiesOfNode.isRight()) { + log.debug("After looking for properties of vertex {}. status is {}", uniqueId, findPropertiesOfNode.right().value()); + if(findPropertiesOfNode.right().value() == TitanOperationStatus.NOT_FOUND) + return Either.left(Maps.newHashMap()); + return findPropertiesOfNode; + } + return findPropertiesOfNode; + } + /** * add properties to element type. * @@ -2248,7 +2082,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe */ protected Either<Map<String, PropertyData>, TitanOperationStatus> addPropertiesToElementType(String uniqueId, NodeTypeEnum nodeType, Map<String, PropertyDefinition> propertiesMap) { - Map<String, PropertyData> propertiesData = new HashMap<String, PropertyData>(); + Map<String, PropertyData> propertiesData = new HashMap<>(); if (propertiesMap != null) { @@ -2277,7 +2111,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe if (properties == null) { propMap = null; } else { - propMap = properties.stream().collect(Collectors.toMap(propDef -> propDef.getName(), propDef -> propDef)); + propMap = properties.stream().collect(Collectors.toMap(PropertyDataDefinition::getName, propDef -> propDef)); } return addPropertiesToElementType(uniqueId, elementType, propMap); } @@ -2297,9 +2131,9 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe List<PropertyDefinition> oldProperties = oldDataTypeDefinition.getProperties(); - String newDerivedFromName = getDerivedFromName(newDataTypeDefinition); + String newDerivedFromName = newDataTypeDefinition.getDerivedFromName(); - String oldDerivedFromName = getDerivedFromName(oldDataTypeDefinition); + String oldDerivedFromName = oldDataTypeDefinition.getDerivedFromName(); String dataTypeName = newDataTypeDefinition.getName(); @@ -2317,12 +2151,24 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe result = Either.right(StorageOperationStatus.OK); return result; } + Map<String, String> newDescriptions = getPropertyDescriptionsToUpdate(oldProperties, newProperties); + + if(MapUtils.isNotEmpty(newDescriptions)){ + + TitanOperationStatus updatePropertiesStatus = updateDataTypePropertyDescriptions(oldDataTypeDefinition.getUniqueId(), newDescriptions); + if (updatePropertiesStatus != TitanOperationStatus.OK) { + log.debug("#updateDataType - Failed to update the descriptions of the properties of the data type {}. Status is {}", oldDataTypeDefinition, updatePropertiesStatus); + BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError(UPDATE_DATA_TYPE, PROPERTY); + result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updatePropertiesStatus)); + return result; + } + } Either<Map<String, PropertyData>, TitanOperationStatus> addPropertiesToDataType = addPropertiesToDataType(oldDataTypeDefinition.getUniqueId(), propertiesToAdd); if (addPropertiesToDataType.isRight()) { log.debug("Failed to update data type {} to Graph. Status is {}", oldDataTypeDefinition, addPropertiesToDataType.right().value().name()); - BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError("UpdateDataType", "Property"); + BeEcompErrorManager.getInstance().logBeFailedAddingNodeTypeError(UPDATE_DATA_TYPE, PROPERTY); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(addPropertiesToDataType.right().value())); return result; } else { @@ -2331,7 +2177,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe if (dataTypeByUid.isRight()) { TitanOperationStatus status = addPropertiesToDataType.right().value(); log.debug("Failed to get data type {} after update. Status is {}", oldDataTypeDefinition.getUniqueId(), status.name()); - BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError("UpdateDataType", "Property", status.name()); + BeEcompErrorManager.getInstance().logBeFailedRetrieveNodeError(UPDATE_DATA_TYPE, PROPERTY, status.name()); result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); } else { result = Either.left(dataTypeByUid.left().value()); @@ -2341,12 +2187,12 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe return result; } finally { - if (false == inTransaction) { + if (!inTransaction) { if (result == null || result.isRight()) { - log.error("Going to execute rollback on graph."); + log.error(GOING_TO_EXECUTE_ROLLBACK_ON_GRAPH); titanGenericDao.rollback(); } else { - log.debug("Going to execute commit on graph."); + log.debug(GOING_TO_EXECUTE_COMMIT_ON_GRAPH); titanGenericDao.commit(); } } @@ -2354,17 +2200,12 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe } - private String getDerivedFromName(DataTypeDefinition dataTypeDefinition) { - String derivedFromName = dataTypeDefinition.getDerivedFromName(); - return derivedFromName; - } - private boolean isPropertyTypeChanged(String dataTypeName, List<PropertyDefinition> newProperties, List<PropertyDefinition> oldProperties, List<PropertyDefinition> outputPropertiesToAdd) { if (newProperties != null && oldProperties != null) { - Map<String, PropertyDefinition> newPropsMapper = newProperties.stream().collect(Collectors.toMap(p -> p.getName(), p -> p)); - Map<String, PropertyDefinition> oldPropsMapper = oldProperties.stream().collect(Collectors.toMap(p -> p.getName(), p -> p)); + Map<String, PropertyDefinition> newPropsMapper = newProperties.stream().collect(Collectors.toMap(PropertyDataDefinition::getName, p -> p)); + Map<String, PropertyDefinition> oldPropsMapper = oldProperties.stream().collect(Collectors.toMap(PropertyDataDefinition::getName, p -> p)); for (Entry<String, PropertyDefinition> newPropertyEntry : newPropsMapper.entrySet()) { @@ -2384,12 +2225,12 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe String newType = propDef.getType(); String newEntryType = getEntryType(propDef); - if (false == oldType.equals(newType)) { + if (!oldType.equals(newType)) { log.debug("Existing property {} in data type {} has a differnet type {} than the new one {}", propName, dataTypeName, oldType, newType); return true; } - if (false == equalsEntryTypes(oldEntryType, newEntryType)) { + if (!equalsEntryTypes(oldEntryType, newEntryType)) { log.debug("Existing property {} in data type {} has a differnet entry type {} than the new one {}", propName, dataTypeName, oldEntryType, newEntryType); return true; } @@ -2427,19 +2268,19 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe private boolean isPropertyOmitted(List<PropertyDefinition> newProperties, List<PropertyDefinition> oldProperties, String dataTypeName) { boolean isValid = validateChangeInCaseOfEmptyProperties(newProperties, oldProperties, dataTypeName); - if (false == isValid) { + if (!isValid) { log.debug("At least one property is missing in the new data type {}", dataTypeName); return false; } if (newProperties != null && oldProperties != null) { - List<String> newProps = newProperties.stream().map(p -> p.getName()).collect(Collectors.toList()); - List<String> oldProps = oldProperties.stream().map(p -> p.getName()).collect(Collectors.toList()); + List<String> newProps = newProperties.stream().map(PropertyDataDefinition::getName).collect(Collectors.toList()); + List<String> oldProps = oldProperties.stream().map(PropertyDataDefinition::getName).collect(Collectors.toList()); - if (false == newProps.containsAll(oldProps)) { + if (!newProps.containsAll(oldProps)) { StringJoiner joiner = new StringJoiner(",", "[", "]"); - newProps.forEach(p -> joiner.add(p)); + newProps.forEach(joiner::add); log.debug("Properties {} in data type {} are missing, but they already defined in the existing data type", joiner.toString(), dataTypeName); return true; } @@ -2473,7 +2314,7 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe if (newDerivedFromName != null) { boolean isEqual = newDerivedFromName.equals(oldDerivedFromName); - if (false == isEqual) { + if (!isEqual) { log.debug("The new datatype {} derived from another data type {} than the existing one {}", dataTypeName, newDerivedFromName, oldDerivedFromName); } return !isEqual; @@ -2487,43 +2328,170 @@ public class PropertyOperation extends AbstractOperation implements IPropertyOpe } /** - * - * Future - unfinished - * - * @param type - * @param value + * @param instanceId + * @param nodeType * @return */ - public boolean isValueToscaFunction(String type, String value) { + public Either<Integer, StorageOperationStatus> increaseAndGetObjInstancePropertyCounter(String instanceId, NodeTypeEnum nodeType) { + Either<TitanGraph, TitanOperationStatus> graphResult = titanGenericDao.getGraph(); + if (graphResult.isRight()) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(graphResult.right().value())); + } + Either<TitanVertex, TitanOperationStatus> vertexService = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(nodeType), instanceId); + if (vertexService.isRight()) { + log.debug("failed to fetch vertex of resource instance for id = {}", instanceId); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(vertexService.right().value())); + } + Vertex vertex = vertexService.left().value(); + + VertexProperty<Object> vertexProperty = vertex.property(GraphPropertiesDictionary.PROPERTY_COUNTER.getProperty()); + Integer counter = 0; + if (vertexProperty.isPresent() && vertexProperty.value() != null) { + counter = (Integer) vertexProperty.value(); + } + + counter++; + vertex.property(GraphPropertiesDictionary.PROPERTY_COUNTER.getProperty(), counter); + + return Either.left(counter); + } + + + public Either<List<PropertyDefinition>, TitanOperationStatus> validatePropertiesUniqueness(Map<String, PropertyDefinition> inheritedProperties, List<PropertyDefinition> properties) { + Either<List<PropertyDefinition>, TitanOperationStatus> result = Either.left(properties); + + for (PropertyDefinition property : properties) { + TitanOperationStatus status = validatePropertyUniqueness(inheritedProperties, property); + if (status != TitanOperationStatus.OK) { + result = Either.right(status); + break; + } + } + + return result; + } - boolean result = false; + /** + * Validates uniqueness of examined property by comparing it with properties in propertiesOfType + * and updates if need type and inner type of the property. + */ + private TitanOperationStatus validatePropertyUniqueness(Map<String, PropertyDefinition> inheritedProperties, PropertyDefinition property) { + String propertyName = property.getName(); + String propertyType = property.getType(); + + TitanOperationStatus result = TitanOperationStatus.OK; + if (inheritedProperties.containsKey(propertyName)) { + PropertyDefinition defaultProperty = inheritedProperties.get(propertyName); + if (typesMismatch(propertyType, defaultProperty.getType())) { + log.error("#validatePropertyUniqueness - Property with name {} and different type already exists.", propertyName); + result = TitanOperationStatus.PROPERTY_NAME_ALREADY_EXISTS; + } else { + property.setType(defaultProperty.getType()); + String innerType = defaultProperty.getSchemaType(); + + PropertyDataDefinition schemaProperty = property.getSchemaProperty(); + if (schemaProperty != null) { + schemaProperty.setType(innerType); + } + } + } + + return result; + } - if (ToscaPropertyType.STRING.getType().equals(type) || isScalarDerivedFromString(type)) { + private boolean typesMismatch(String type1, String type2) { + return type1 != null && type2 != null && !type2.equals(type1); + } - } - String[] functions = { "get_input" }; + public <T extends GraphNode> Either<Map<String, PropertyDefinition>, TitanOperationStatus> getAllTypePropertiesFromAllDerivedFrom(String nextParentUid, + NodeTypeEnum nodeType, + Class<T> clazz) { + Map<String, PropertyDefinition> allProperies = new HashMap<>(); + return getTypePropertiesFromDerivedFromRecursively(nextParentUid, allProperies, nodeType, clazz); + } - if (value != null) { + private <T extends GraphNode> Either<Map<String, PropertyDefinition>, TitanOperationStatus> getTypePropertiesFromDerivedFromRecursively(String nextParentUid, + Map<String, PropertyDefinition> allProperies, + NodeTypeEnum nodeType, + Class<T> clazz) { + TitanOperationStatus error; + Either<List<ImmutablePair<T, GraphEdge>>, TitanOperationStatus> childrenNodes = titanGenericDao.getChildrenNodes(UniqueIdBuilder.getKeyByNodeType(nodeType), + nextParentUid, GraphEdgeLabels.DERIVED_FROM, nodeType, clazz); + if (childrenNodes.isRight()) { + if (childrenNodes.right().value() != TitanOperationStatus.NOT_FOUND) { + error = childrenNodes.right().value(); + log.debug("#getTypePropertiesFromDerivedFromRecursively - Couldn't fetch derived from node with UID {}, error: {}", nextParentUid, error); + return Either.right(error); + } + else { + log.debug("#getTypePropertiesFromDerivedFromRecursively - Derived from node is not found with UID {} - this is OK for root.", nextParentUid); + return Either.left(allProperies); + } + } else { + + Either<Map<String, PropertyDefinition>, TitanOperationStatus> allPropertiesOfTypeRes = findPropertiesOfNode(nodeType, nextParentUid); + if (allPropertiesOfTypeRes.isRight() && !allPropertiesOfTypeRes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { + error = allPropertiesOfTypeRes.right().value(); + log.error("#getTypePropertiesFromDerivedFromRecursively - Failed to retrieve properties for node with UID {} from graph. status is {}", nextParentUid, error); + return Either.right(error); + } else if (allPropertiesOfTypeRes.isLeft()) { + if (allProperies.isEmpty()) { + allProperies.putAll(allPropertiesOfTypeRes.left().value()); + } else { + allProperies.putAll(allPropertiesOfTypeRes.left().value().entrySet().stream().filter(e -> !allProperies.containsKey(e.getKey())).collect(Collectors.toMap(Entry::getKey, Entry::getValue))); + } + } + return getTypePropertiesFromDerivedFromRecursively(childrenNodes.left().value().get(0).getLeft().getUniqueId(), allProperies, nodeType, clazz); + } + } + private TitanOperationStatus updateDataTypePropertyDescriptions(String uniqueId, Map<String, String> newDescriptions) { - for (String function : functions) { + if (MapUtils.isNotEmpty(newDescriptions)) { + Either<List<ImmutablePair<TitanVertex, Edge>>, TitanOperationStatus> getDataTypePropertiesRes = titanGenericDao.getChildrenVertecies(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), uniqueId, GraphEdgeLabels.PROPERTY); - } + if(getDataTypePropertiesRes.isRight()){ + log.debug("#updateDataTypePropertiesDescriptions - Failed to fetch the property verticies of the Data type {} ", uniqueId); + return getDataTypePropertiesRes.right().value(); + } + getDataTypePropertiesRes.left().value().stream() + .filter(pair -> newDescriptions.containsKey(getPropertyNameFromEdge(pair))) + .forEach(pair -> setNewDescriptionToVertex(newDescriptions.get(getPropertyNameFromEdge(pair)), pair)); - } + } + return TitanOperationStatus.OK; + } - return result; + private TitanVertexProperty<String> setNewDescriptionToVertex(String newDescription, ImmutablePair<TitanVertex, Edge> pair) { + return pair.getLeft().property(GraphPropertiesDictionary.DESCRIPTION.getProperty(), newDescription); + } - } + private String getPropertyNameFromEdge(ImmutablePair<TitanVertex, Edge> pair) { + return (String) pair.getRight().property(GraphPropertiesDictionary.NAME.getProperty()).value(); + } - /** - * Future - unfinished - * - * @param type - * @return - */ - private boolean isScalarDerivedFromString(String type) { - // TODO Auto-generated method stub - return false; - } + private Map<String, String> getPropertyDescriptionsToUpdate(List<PropertyDefinition> oldProperties, List<PropertyDefinition> newProperties) { + + Map<String, PropertyDefinition> newPropertiesMap = newProperties + .stream() + .collect(Collectors.toMap(PropertyDefinition::getName, p->p)); + + return oldProperties + .stream() + .filter(p-> newPropertiesMap.containsKey(p.getName()) && !descriptionsEqual(p, newPropertiesMap.get(p.getName()))) + .collect(Collectors.toMap(PropertyDefinition::getName, p->newPropertiesMap.get(p.getName()).getDescription())); + } + + private boolean descriptionsEqual(PropertyDefinition property, PropertyDefinition otherProperty){ + if(StringUtils.isEmpty(property.getDescription()) && StringUtils.isEmpty(otherProperty.getDescription())){ + return true; + } + if(StringUtils.isNotEmpty(property.getDescription()) && StringUtils.isEmpty(otherProperty.getDescription())){ + return false; + } + if(StringUtils.isEmpty(property.getDescription()) && StringUtils.isNotEmpty(otherProperty.getDescription())){ + return false; + } + return property.getDescription().equals(otherProperty.getDescription()); + } } 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 4cdb21a908..058e9de163 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 @@ -20,10 +20,6 @@ package org.openecomp.sdc.be.model.operations.impl; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; @@ -34,230 +30,182 @@ import org.openecomp.sdc.be.resources.data.UserData; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.util.ValidationUtils; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + public class UniqueIdBuilder { - private static String DOT = "."; - private static final String HEAT_PARAM_PREFIX = "heat_"; - - public static String buildPropertyUniqueId(String resourceId, String propertyName) { - return resourceId + DOT + propertyName; - } - - public static String buildHeatParameterUniqueId(String resourceId, String propertyName) { - return resourceId + DOT + HEAT_PARAM_PREFIX + propertyName; - } - - public static String buildHeatParameterValueUniqueId(String resourceId, String artifactLabel, String propertyName) { - return resourceId + DOT + artifactLabel + DOT + propertyName; - } - - private static UserData userData = new UserData(); - private static TagData tagData = new TagData(); - private static ResourceCategoryData resCategoryData = new ResourceCategoryData(); - private static ServiceCategoryData serCategoryData = new ServiceCategoryData(); - - private static Map<NodeTypeEnum, String> nodeTypeToUniqueKeyMapper = new HashMap<NodeTypeEnum, String>(); - - static { - - nodeTypeToUniqueKeyMapper.put(NodeTypeEnum.User, userData.getUniqueIdKey()); - nodeTypeToUniqueKeyMapper.put(NodeTypeEnum.Tag, tagData.getUniqueIdKey()); - nodeTypeToUniqueKeyMapper.put(NodeTypeEnum.ResourceCategory, resCategoryData.getUniqueIdKey()); - nodeTypeToUniqueKeyMapper.put(NodeTypeEnum.ServiceCategory, serCategoryData.getUniqueIdKey()); - } - - /** - * find the unique id key of a node on the graph - * - * @param nodeTypeEnum - * @return - */ - public static String getKeyByNodeType(NodeTypeEnum nodeTypeEnum) { - - String key = nodeTypeToUniqueKeyMapper.get(nodeTypeEnum); - if (key == null) { - key = GraphPropertiesDictionary.UNIQUE_ID.getProperty(); - } - - return key; - } - - public static String buildResourceUniqueId() { - return generateUUID(); - } - - public static String generateUUID() { - UUID uuid = UUID.randomUUID(); - return uuid.toString(); - } - - public static String buildComponentUniqueId() { - return generateUUID(); - } - - public static String buildConstantProductId() { - return generateUUID(); - } - - public static String buildCapabilityTypeUid(String type) { - return type; - } - - public static String buildAttributeUid(String resourceId, String attName) { - return NodeTypeEnum.Attribute.getName() + DOT + resourceId + DOT + attName; - } - public static String buildArtifactUid(String parentId, String label) { - return parentId + DOT + label; - } - public static String buildRequirementUid(String resourceId, String reqName) { - return resourceId + DOT + reqName; - } - - public static String buildRequirementImplUid(String resourceId, String reqName) { - - return NodeTypeEnum.RequirementImpl.getName() + DOT + resourceId + DOT + reqName; - - } - - public static String buildCapabilityUid(String resourceId, String capabilityName) { - return NodeTypeEnum.Capability.getName() + DOT + resourceId + DOT + capabilityName; - } - - public static String buildCapabilityInstanceUid(String parentId, String capabilityName) { - return NodeTypeEnum.CapabilityInst.getName() + DOT + parentId + DOT + capabilityName; - } - - public static String buildPropertyValueUniqueId(String parentId, String paramName) { - return NodeTypeEnum.PropertyValue.getName() + DOT + parentId + DOT + paramName; - } - - public static String buildArtifactByInterfaceUniqueId(String resourceId, String interfaceName, String operation, String artifactLabel) { - - return resourceId + DOT + interfaceName + DOT + operation + DOT + artifactLabel; - } - - public static String buildInstanceArtifactUniqueId(String parentId, String instanceId, String artifactLabel) { - - return parentId + DOT + instanceId + DOT + artifactLabel; - } - - // public static String - // buildArtifactByInterfaceUniqueIdAndRsrcNameVersion(String - // resourceName,String resourceVersion,String interfaceName,String - // operation,String artifactLabel) { - // String resourceId = UniqueIdBuilder.buildResourceUniqueId(resourceName, - // resourceVersion); - // return resourceId + DOT + interfaceName + DOT +operation + DOT + - // artifactLabel; - // } - public static String buildArtifactByInterfaceUniqueIdAndRsrcId(String resourceId, String interfaceName, String operation, String artifactLabel) { - return resourceId + DOT + interfaceName + DOT + operation + DOT + artifactLabel; - } - - public static String buildOperationByInterfaceUniqueId(String resourceId, String interfaceName, String operation) { - - return resourceId + DOT + interfaceName + DOT + operation; - } - - public static String buildInterfaceUniqueId(String resourceId, String interfaceName) { - return resourceId + DOT + interfaceName; - } - - public static String buildResourceInstanceUniuqeId(String serviceId, String resourceId, String logicalName) { - - return serviceId + DOT + resourceId + DOT + logicalName; - } - - public static String buildRelationsipInstInstanceUid(String resourceInstUid, String requirement) { - - return generateUUID(); - } - - /* - * TODO Pavel To be removed when new category logic comes in - */ - public static String buildResourceCategoryUid(String categoryName, String subcategoryName, NodeTypeEnum type) { - return type.getName() + DOT + categoryName + DOT + subcategoryName; - } - - /* - * TODO Pavel To be removed when new category logic comes in - */ - public static String buildServiceCategoryUid(String categoryName, NodeTypeEnum type) { - return type.getName() + DOT + categoryName; - } - - // New logic - public static String buildCategoryUid(String categoryName, NodeTypeEnum type) { - return type.getName() + DOT + categoryName; - } - public static String buildComponentCategoryUid(String categoryName, VertexTypeEnum type) { - return type.getName() + DOT + ValidationUtils.normalizeCategoryName4Uniqueness(categoryName); - } - - public static String buildSubCategoryUid(String categoryUid, String subCategoryName) { - return categoryUid + DOT + subCategoryName; - } - - public static String buildGroupingUid(String subCategoryUid, String groupingName) { - return subCategoryUid + DOT + groupingName; - } - - public static String buildResourceInstancePropertyValueUid(String resourceInstanceUniqueId, Integer index) { - return resourceInstanceUniqueId + DOT + "property" + DOT + index; - } - - public static String buildComponentPropertyUniqueId(String resourceId, String propertyName) { - return NodeTypeEnum.Property.getName() + DOT + resourceId + DOT + propertyName; - } - - public static String buildResourceInstanceAttributeValueUid(String resourceInstanceUniqueId, Integer index) { - return resourceInstanceUniqueId + DOT + "attribute" + DOT + index; - } - - public static String buildResourceInstanceInputValueUid(String resourceInstanceUniqueId, Integer index) { - return resourceInstanceUniqueId + DOT + "input" + DOT + index; - } - - public static String buildAdditionalInformationUniqueId(String resourceUniqueId) { - return resourceUniqueId + DOT + "additionalinformation"; - } - - public static String buildHeatParamValueUid(String heatEnvArtifactId, String parameterName) { - return heatEnvArtifactId + DOT + parameterName; - } - - public static String buildDataTypeUid(String name) { - return name + DOT + "datatype"; - } - - public static String buildInvariantUUID() { - return generateUUID(); - } - - public static String buildGroupTypeUid(String type, String version) { - return type + DOT + version + DOT + "grouptype"; - } - - public static String buildPolicyTypeUid(String type, String version) { - return type + DOT + version + DOT + "policytype"; - } - - public static String buildGroupUniqueId(String componentId, String name) { - return componentId + DOT + name + DOT + "group"; - } - - public static String buildPolicyUniqueId(String componentId, String name) { - return componentId + DOT + name + Constants.POLICY_UID_POSTFIX; - } - - public static String buildGroupPropertyValueUid(String groupUniqueId, Integer index) { - return groupUniqueId + DOT + "property" + DOT + index; - - } - - public static String buildUserFunctionalMenuUid(String userId) { - return userId + DOT + "functionalmenu"; - - } + private static String DOT = "."; + private static final String HEAT_PARAM_PREFIX = "heat_"; + + public static String buildPropertyUniqueId(String resourceId, String propertyName) { + return resourceId + DOT + propertyName; + } + + static String buildHeatParameterUniqueId(String resourceId, String propertyName) { + return resourceId + DOT + HEAT_PARAM_PREFIX + propertyName; + } + + static String buildHeatParameterValueUniqueId(String resourceId, String artifactLabel, String propertyName) { + return buildTypeUid(resourceId, artifactLabel, propertyName); + } + + private static UserData userData = new UserData(); + private static TagData tagData = new TagData(); + private static ResourceCategoryData resCategoryData = new ResourceCategoryData(); + private static ServiceCategoryData serCategoryData = new ServiceCategoryData(); + + private static Map<NodeTypeEnum, String> nodeTypeToUniqueKeyMapper = new HashMap<>(); + + static { + + nodeTypeToUniqueKeyMapper.put(NodeTypeEnum.User, userData.getUniqueIdKey()); + nodeTypeToUniqueKeyMapper.put(NodeTypeEnum.Tag, tagData.getUniqueIdKey()); + nodeTypeToUniqueKeyMapper.put(NodeTypeEnum.ResourceCategory, resCategoryData.getUniqueIdKey()); + nodeTypeToUniqueKeyMapper.put(NodeTypeEnum.ServiceCategory, serCategoryData.getUniqueIdKey()); + } + + /** + * find the unique id key of a node on the graph + * + * @param nodeTypeEnum + * @return + */ + public static String getKeyByNodeType(NodeTypeEnum nodeTypeEnum) { + + String key = nodeTypeToUniqueKeyMapper.get(nodeTypeEnum); + if (key == null) { + key = GraphPropertiesDictionary.UNIQUE_ID.getProperty(); + } + + return key; + } + + public static String buildResourceUniqueId() { + return generateUUID(); + } + + public static String generateUUID() { + UUID uuid = UUID.randomUUID(); + return uuid.toString(); + } + + public static String buildComponentUniqueId() { + return generateUUID(); + } + + static String buildCapabilityTypeUid(String type) { + return type; + } + + public static String buildAttributeUid(String resourceId, String attName) { + return buildTypeUid(NodeTypeEnum.Attribute.getName(), resourceId, attName); + } + public static String buildRequirementUid(String resourceId, String reqName) { + return resourceId + DOT + reqName; + } + + public static String buildCapabilityUid(String resourceId, String capabilityName) { + return buildTypeUid(NodeTypeEnum.Capability.getName(), resourceId, capabilityName); + } + + public static String buildArtifactByInterfaceUniqueId(String resourceId, String interfaceName, String operation, String artifactLabel) { + + return resourceId + DOT + interfaceName + DOT + operation + DOT + artifactLabel; + } + + public static String buildInstanceArtifactUniqueId(String parentId, String instanceId, String artifactLabel) { + + return buildTypeUid(parentId, instanceId, artifactLabel); + } + + public static String buildResourceInstanceUniuqeId(String serviceId, String resourceId, String logicalName) { + + return buildTypeUid(serviceId, resourceId, logicalName); + } + + public static String buildRelationsipInstInstanceUid(String resourceInstUid, String requirement) { + + return generateUUID(); + } + + /* + * TODO Pavel To be removed when new category logic comes in + */ + static String buildResourceCategoryUid(String categoryName, String subcategoryName, NodeTypeEnum type) { + return buildTypeUid(type.getName(), categoryName, subcategoryName); + } + + /* + * TODO Pavel To be removed when new category logic comes in + */ + static String buildServiceCategoryUid(String categoryName, NodeTypeEnum type) { + return type.getName() + DOT + categoryName; + } + + // New logic + public static String buildCategoryUid(String categoryName, NodeTypeEnum type) { + return type.getName() + DOT + categoryName; + } + public static String buildComponentCategoryUid(String categoryName, VertexTypeEnum type) { + return type.getName() + DOT + ValidationUtils.normalizeCategoryName4Uniqueness(categoryName); + } + + public static String buildSubCategoryUid(String categoryUid, String subCategoryName) { + return categoryUid + DOT + subCategoryName; + } + + public static String buildGroupingUid(String subCategoryUid, String groupingName) { + return subCategoryUid + DOT + groupingName; + } + + static String buildResourceInstancePropertyValueUid(String resourceInstanceUniqueId, Integer index) { + return resourceInstanceUniqueId + DOT + "property" + DOT + index; + } + + public static String buildComponentPropertyUniqueId(String resourceId, String propertyName) { + return buildTypeUid(NodeTypeEnum.Property.getName(), resourceId, propertyName); + } + + static String buildResourceInstanceAttributeValueUid(String resourceInstanceUniqueId, Integer index) { + return resourceInstanceUniqueId + DOT + "attribute" + DOT + index; + } + + static String buildResourceInstanceInputValueUid(String resourceInstanceUniqueId, Integer index) { + return resourceInstanceUniqueId + DOT + "input" + DOT + index; + } + + static String buildAdditionalInformationUniqueId(String resourceUniqueId) { + return resourceUniqueId + DOT + "additionalinformation"; + } + + static String buildDataTypeUid(String name) { + return name + DOT + "datatype"; + } + + public static String buildInvariantUUID() { + return generateUUID(); + } + + static String buildGroupTypeUid(String type, String version, String resourceName) { + return buildTypeUid(type, version, resourceName); + } + + static String buildPolicyTypeUid(String type, String version, String resourceName) { + return buildTypeUid(type, version, resourceName); + } + + static String buildTypeUid(String type, String version, String resourceName) { + return type + DOT + version + DOT + resourceName; + } + + public static String buildPolicyUniqueId(String componentId, String name) { + return componentId + DOT + name + Constants.POLICY_UID_POSTFIX; + } + + public static String buildGroupPropertyValueUid(String groupUniqueId, Integer index) { + return groupUniqueId + DOT + "property" + DOT + index; + + } } 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 9aa231497d..72c370ffe6 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/UserAdminOperation.java @@ -20,12 +20,9 @@ package org.openecomp.sdc.be.model.operations.impl; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - +import com.thinkaurelius.titan.core.TitanVertex; +import fj.data.Either; +import org.apache.commons.lang3.BooleanUtils; import org.apache.tinkerpop.gremlin.structure.Direction; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Vertex; @@ -43,372 +40,362 @@ import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation; 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.wrappers.Logger; import org.openecomp.sdc.common.util.MethodActivationStatusEnum; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; -import com.thinkaurelius.titan.core.TitanVertex; +import java.util.*; -import fj.data.Either; +import static org.apache.commons.collections.CollectionUtils.isEmpty; @Component("user-operation") public class UserAdminOperation implements IUserAdminOperation { - private TitanGenericDao titanGenericDao; - - public UserAdminOperation(@Qualifier("titan-generic-dao") TitanGenericDao titanGenericDao) { - super(); - this.titanGenericDao = titanGenericDao; - - } - - private static Logger log = LoggerFactory.getLogger(UserAdminOperation.class.getName()); - - @Override - public Either<User, ActionStatus> getUserData(String id, boolean inTransaction) { - return getUserData(id, true, inTransaction); - } - - private Either<User, ActionStatus> getUserData(String id, boolean isActive, boolean inTransaction) { - log.debug("getUserData - start"); - Wrapper<Either<User, ActionStatus>> resultWrapper = new Wrapper<>(); - Wrapper<UserData> userWrapper = new Wrapper<>(); - try { - validateUserExists(resultWrapper, userWrapper, id); - - if (resultWrapper.isEmpty()) { - validateUserData(resultWrapper, userWrapper.getInnerElement(), id); - - } - if (resultWrapper.isEmpty()) { - if (isActive) { - validateActiveUser(resultWrapper, userWrapper.getInnerElement()); - } else { - validateInActiveUser(resultWrapper, userWrapper.getInnerElement()); - } - } - - if (resultWrapper.isEmpty()) { - Either<User, ActionStatus> result = Either.left(convertToUser(userWrapper.getInnerElement())); - resultWrapper.setInnerElement(result); - } - - return resultWrapper.getInnerElement(); - } finally { - if (!inTransaction) { - titanGenericDao.commit(); - } - log.debug("getUserData - end"); - } - } - - private void validateInActiveUser(Wrapper<Either<User, ActionStatus>> resultWrapper, UserData userData) { - User user = convertToUser(userData); - if (user.getStatus() == UserStatusEnum.ACTIVE) { - Either<User, ActionStatus> result = Either.right(ActionStatus.USER_NOT_FOUND); - resultWrapper.setInnerElement(result); - } - } - - private void validateActiveUser(Wrapper<Either<User, ActionStatus>> resultWrapper, UserData userData) { - User user = convertToUser(userData); - if (user.getStatus() == UserStatusEnum.INACTIVE) { - Either<User, ActionStatus> result = Either.right(ActionStatus.USER_INACTIVE); - resultWrapper.setInnerElement(result); - } - } - - private void validateUserData(Wrapper<Either<User, ActionStatus>> resultWrapper, UserData userData, String id) { - if (userData == null) { - log.debug("Problem get User with userId {}. Reason - either.left().value() = null", id); - Either<User, ActionStatus> result = Either.right(ActionStatus.GENERAL_ERROR); - resultWrapper.setInnerElement(result); - } - } - - private void validateUserExists(Wrapper<Either<User, ActionStatus>> resultWrapper, Wrapper<UserData> userWrapper, String id) { - Either<User, ActionStatus> result; - if (id == null) { - log.info("User userId is empty"); - result = Either.right(ActionStatus.MISSING_INFORMATION); - resultWrapper.setInnerElement(result); - return; - } - id = id.toLowerCase(); - Either<UserData, TitanOperationStatus> either = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), id, UserData.class); - - if (either.isRight()) { - resultWrapper.setInnerElement(getUserNotFoundError(id, either.right().value())); - } else { - userWrapper.setInnerElement(either.left().value()); - } - } - - @Override - public Either<User, StorageOperationStatus> saveUserData(User user) { - - Either<UserData, TitanOperationStatus> result = null; - try { - UserData userData = convertToUserData(user); - result = titanGenericDao.createNode(userData, UserData.class); - if (result.isRight()) { - log.debug("Problem while saving User {}. Reason - {}",userData.toString(),result.right().value().name()); - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - log.debug("User {} saved successfully",userData.toString()); - return Either.left(convertToUser(result.left().value())); - - } finally { - - if (result == null || result.isRight()) { - log.error("saveUserData - Failed"); - titanGenericDao.rollback(); - } else { - log.debug("saveUserData - end"); - titanGenericDao.commit(); - } - } - } - - @Override - public Either<User, StorageOperationStatus> updateUserData(User user) { - Either<UserData, TitanOperationStatus> result = null; - try { - log.debug("updateUserData - start"); - UserData userData = convertToUserData(user); - result = titanGenericDao.updateNode(userData, UserData.class); - if (result.isRight()) { - log.debug("Problem while updating User {}. Reason - {}",userData.toString(),result.right().value().name()); - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - log.debug("User {} updated successfully",userData.toString()); - return Either.left(convertToUser(result.left().value())); - - } finally { - - if (result == null || result.isRight()) { - log.error("updateUserData - Failed"); - titanGenericDao.rollback(); - } else { - log.debug("updateUserData - end"); - titanGenericDao.commit(); - } - - } - } - - @Override - public Either<User, StorageOperationStatus> deActivateUser(User user) { - Either<User, StorageOperationStatus> result; - 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; - } - - @Override - public Either<User, ActionStatus> deleteUserData(String id) { - Either<User, ActionStatus> result; - Either<UserData, TitanOperationStatus> eitherGet = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), id, UserData.class); - if (eitherGet.isRight()) { - log.debug("Problem while retriving user with userId {}",id); - if (eitherGet.right().value() == TitanOperationStatus.NOT_FOUND) { - result = Either.right(ActionStatus.USER_NOT_FOUND); - } else { - result = Either.right(ActionStatus.GENERAL_ERROR); - } - - } else { - result = deleteUserLogic(eitherGet.left().value()); - } - return result; - } - - private Either<User, ActionStatus> deleteUserLogic(UserData userData) { - Wrapper<Either<User, ActionStatus>> resultWrapper = new Wrapper<>(); - try { - validateUserHasNoConnections(resultWrapper, userData); - - if (resultWrapper.isEmpty()) { - deleteUser(resultWrapper, userData); - } - - } finally { - titanGenericDao.commit(); - } - - return resultWrapper.getInnerElement(); - } - - private void deleteUser(Wrapper<Either<User, ActionStatus>> resultWrapper, UserData userData) { - Either<UserData, TitanOperationStatus> eitherDelete = titanGenericDao.deleteNode(userData, UserData.class); - if (eitherDelete.isRight()) { - log.debug("Problem while deleting User {}. Reason - {}",userData.toString(),eitherDelete.right().value().name()); - Either<User, ActionStatus> result = Either.right(ActionStatus.GENERAL_ERROR); - resultWrapper.setInnerElement(result); - } else { - log.debug("User {} deleted successfully",userData.toString()); - Either<User, ActionStatus> result = Either.left(convertToUser(eitherDelete.left().value())); - resultWrapper.setInnerElement(result); - } - } - - private void validateUserHasNoConnections(Wrapper<Either<User, ActionStatus>> resultWrapper, UserData userData) { - if (resultWrapper.isEmpty()) { - - Either<List<Edge>, TitanOperationStatus> edgesForNode = titanGenericDao.getEdgesForNode(userData, Direction.BOTH); - if (edgesForNode.isRight()) { - log.debug("Problem while deleting User {}. Reason - {}",userData.toString(),edgesForNode.right().value().name()); - Either<User, ActionStatus> result = Either.right(ActionStatus.GENERAL_ERROR); - resultWrapper.setInnerElement(result); - } else { - List<Edge> vertexEdges = edgesForNode.left().value(); - if (vertexEdges.size() > 0) { - Either<User, ActionStatus> result = Either.right(ActionStatus.USER_HAS_ACTIVE_ELEMENTS); - resultWrapper.setInnerElement(result); - } - } - } - } - - public Either<List<Edge>, StorageOperationStatus> getUserPendingTasksList(User user, Map<String, Object> properties) { - - UserData userData = convertToUserData(user); - - Either<TitanVertex, TitanOperationStatus> vertexUser = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), user.getUserId()); - if (vertexUser.isRight()) { - log.debug("Problem while deleting User {}. Reason - {}",userData.toString(),vertexUser.right().value().name()); - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - - List<Edge> pandingTasks = new ArrayList<>(); - Either<List<Edge>, TitanOperationStatus> edges = titanGenericDao.getOutgoingEdgesByCriteria(vertexUser.left().value(), GraphEdgeLabels.STATE, properties); - - if (edges.isRight() || edges.left().value() == null) { - if (edges.right().value() == TitanOperationStatus.NOT_FOUND) { - return Either.left(pandingTasks); - } else { - log.debug("Problem while deleting User {}. Reason - ",userData.toString(),edges.right().value().name()); - return Either.right(StorageOperationStatus.GENERAL_ERROR); - } - } - - for (Edge edge : edges.left().value()) { - Vertex componentVertex = edge.inVertex(); - VertexProperty<Object> property = componentVertex.property(GraphPropertiesDictionary.IS_DELETED.getProperty()); - if (!property.isPresent()) { - pandingTasks.add(edge); - } else { - Boolean isDeletedValue = (java.lang.Boolean) property.value(); - if (isDeletedValue == null || isDeletedValue == false) { - pandingTasks.add(edge); - } - } - } - - if(log.isDebugEnabled()) { - for (Edge edge : pandingTasks) { - Object resourceUuid = edge.inVertex().property(GraphPropertyEnum.UNIQUE_ID.getProperty()).value(); - Object componentName = edge.inVertex().property(GraphPropertyEnum.NAME.getProperty()).value(); - Object componentState = edge.inVertex().property(GraphPropertyEnum.STATE.getProperty()).value(); - log.debug("The user userId = {} is working on the component name = {} uid = {} in state {}", user.getUserId(), componentName, resourceUuid, componentState); - } - } - - return Either.left(pandingTasks); - } - - @Override - public Either<List<User>, ActionStatus> getAllUsersWithRole(String role, String status) { - try { - List<User> result = new ArrayList<>(); - Map<String, Object> propertiesToMatch = new HashMap<>(); - if (role != null && !role.trim().isEmpty()) { - propertiesToMatch.put(GraphPropertiesDictionary.ROLE.getProperty(), role); - } - if (status != null && !status.isEmpty()) { - propertiesToMatch.put(GraphPropertiesDictionary.USER_STATUS.getProperty(), status); - } - - Either<List<UserData>, TitanOperationStatus> userNodes = titanGenericDao.getByCriteria(NodeTypeEnum.User, propertiesToMatch, UserData.class); - - titanGenericDao.commit(); - return convertToUsers(role, userNodes); - } finally { - titanGenericDao.commit(); - } - } - - private Either<List<User>, ActionStatus> convertToUsers(String role, Either<List<UserData>, TitanOperationStatus> userNodes) { - - if (userNodes.isRight()) { + private TitanGenericDao titanGenericDao; + + public UserAdminOperation(@Qualifier("titan-generic-dao") TitanGenericDao titanGenericDao) { + super(); + this.titanGenericDao = titanGenericDao; + + } + + 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); + } + + private Either<User, ActionStatus> getUserData(String id, boolean isActive, boolean inTransaction) { + log.debug("getUserData - start"); + Wrapper<Either<User, ActionStatus>> resultWrapper = new Wrapper<>(); + Wrapper<UserData> userWrapper = new Wrapper<>(); + try { + validateUserExists(resultWrapper, userWrapper, id); + + if (resultWrapper.isEmpty()) { + validateUserData(resultWrapper, userWrapper.getInnerElement(), id); + + } + if (resultWrapper.isEmpty()) { + if (isActive) { + validateActiveUser(resultWrapper, userWrapper.getInnerElement()); + } else { + validateInActiveUser(resultWrapper, userWrapper.getInnerElement()); + } + } + + if (resultWrapper.isEmpty()) { + resultWrapper.setInnerElement(Either.left(convertToUser(userWrapper.getInnerElement()))); + } + + return resultWrapper.getInnerElement(); + } finally { + if (!inTransaction) { + titanGenericDao.commit(); + } + log.debug("getUserData - end"); + } + } + + private void validateInActiveUser(Wrapper<Either<User, ActionStatus>> resultWrapper, UserData userData) { + User user = convertToUser(userData); + if (user.getStatus() == UserStatusEnum.ACTIVE) { + resultWrapper.setInnerElement(Either.right(ActionStatus.USER_NOT_FOUND)); + } + } + + private void validateActiveUser(Wrapper<Either<User, ActionStatus>> resultWrapper, UserData userData) { + User user = convertToUser(userData); + if (user.getStatus() == UserStatusEnum.INACTIVE) { + resultWrapper.setInnerElement(Either.right(ActionStatus.USER_INACTIVE)); + } + } + + private void validateUserData(Wrapper<Either<User, ActionStatus>> resultWrapper, UserData userData, String id) { + if (userData == null) { + log.debug("Problem get User with userId {}. Reason - either.left().value() = null", id); + resultWrapper.setInnerElement(Either.right(ActionStatus.GENERAL_ERROR)); + } + } + + 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)); + return; + } + id = id.toLowerCase(); + Either<UserData, TitanOperationStatus> either = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), id, UserData.class); + + if (either.isRight()) { + resultWrapper.setInnerElement(getUserNotFoundError(id, either.right().value())); + } else { + userWrapper.setInnerElement(either.left().value()); + } + } + + @Override + public Either<User, StorageOperationStatus> saveUserData(User user) { + Either<UserData, TitanOperationStatus> result = null; + try { + UserData userData = convertToUserData(user); + result = titanGenericDao.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.debug("User {} saved successfully", userData.getUserId()); + return Either.left(convertToUser(result.left().value())); + + } finally { + + if (result == null || result.isRight()) { + log.error("saveUserData - Failed"); + titanGenericDao.rollback(); + } else { + log.debug("saveUserData - end"); + titanGenericDao.commit(); + } + } + } + + @Override + public Either<User, StorageOperationStatus> updateUserData(User user) { + Either<UserData, TitanOperationStatus> result = null; + try { + log.debug("updateUserData - start"); + UserData userData = convertToUserData(user); + result = titanGenericDao.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.debug("User {} updated successfully",userData.getUserId()); + return Either.left(convertToUser(result.left().value())); + + } finally { + + if (result == null || result.isRight()) { + log.error("updateUserData - Failed"); + titanGenericDao.rollback(); + } else { + log.debug("updateUserData - end"); + titanGenericDao.commit(); + } + + } + } + + @Override + public Either<User, StorageOperationStatus> deActivateUser(User user) { + Either<User, StorageOperationStatus> result; + 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; + } + + @Override + public Either<User, ActionStatus> deleteUserData(String id) { + Either<User, ActionStatus> result; + Either<UserData, TitanOperationStatus> eitherGet = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), id, UserData.class); + if (eitherGet.isRight()) { + log.debug("Problem while retriving user with userId {}",id); + if (eitherGet.right().value() == TitanOperationStatus.NOT_FOUND) { + result = Either.right(ActionStatus.USER_NOT_FOUND); + } else { + result = Either.right(ActionStatus.GENERAL_ERROR); + } + } else { + result = deleteUserLogic(eitherGet.left().value()); + } + return result; + } + + private Either<User, ActionStatus> deleteUserLogic(UserData userData) { + Wrapper<Either<User, ActionStatus>> resultWrapper = new Wrapper<>(); + try { + validateUserHasNoConnections(resultWrapper, userData); + if (resultWrapper.isEmpty()) { + deleteUser(resultWrapper, userData); + } + } finally { + titanGenericDao.commit(); + } + return resultWrapper.getInnerElement(); + } + + private void deleteUser(Wrapper<Either<User, ActionStatus>> resultWrapper, UserData userData) { + Either<UserData, TitanOperationStatus> eitherDelete = titanGenericDao.deleteNode(userData, UserData.class); + if (eitherDelete.isRight()) { + if (log.isDebugEnabled()) { + log.debug("Problem while deleting User {}. Reason - {}", userData.toString(), eitherDelete.right().value()); + } + resultWrapper.setInnerElement(Either.right(ActionStatus.GENERAL_ERROR)); + } else { + log.debug("User {} deleted successfully",userData.getUserId()); + resultWrapper.setInnerElement(Either.left(convertToUser(eitherDelete.left().value()))); + } + } + + private void validateUserHasNoConnections(Wrapper<Either<User, ActionStatus>> resultWrapper, UserData userData) { + if (resultWrapper.isEmpty()) { + + Either<List<Edge>, TitanOperationStatus> edgesForNode = titanGenericDao.getEdgesForNode(userData, Direction.BOTH); + if (edgesForNode.isRight()) { + if (log.isDebugEnabled()) { + log.debug("Problem while deleting User {}. Reason - {}", userData.getUserId(), edgesForNode.right().value()); + } + resultWrapper.setInnerElement(Either.right(ActionStatus.GENERAL_ERROR)); + } else { + List<Edge> vertexEdges = edgesForNode.left().value(); + if (!isEmpty(vertexEdges)) { + resultWrapper.setInnerElement(Either.right(ActionStatus.USER_HAS_ACTIVE_ELEMENTS)); + } + } + } + } + + public Either<List<Edge>, StorageOperationStatus> getUserPendingTasksList(User user, Map<String, Object> properties) { + + Either<TitanVertex, TitanOperationStatus> vertexUser = titanGenericDao.getVertexByProperty(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.User), user.getUserId()); + if (vertexUser.isRight()) { + TitanOperationStatus tos = vertexUser.right().value(); + log.debug("Failed to get User {} from graph while retrieving pending tasks. Reason - {}", user.getUserId(), tos); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(tos)); + } + List<Edge> pendingTasks = new ArrayList<>(); + Either<List<Edge>, TitanOperationStatus> edges = titanGenericDao.getOutgoingEdgesByCriteria(vertexUser.left().value(), GraphEdgeLabels.STATE, properties); + if (edges.isRight() || edges.left().value() == null) { + TitanOperationStatus tos = edges.right().value(); + if (tos == TitanOperationStatus.NOT_FOUND) { + return Either.left(pendingTasks); + } else { + log.debug("Failed while retrieving pending tasks for user {} . Reason - {}", user.getUserId(), tos); + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(tos)); + } + } + for (Edge edge : edges.left().value()) { + if (!isComponentDeleted(edge.inVertex())) { + pendingTasks.add(edge); + } + } + logPendingTasks(user, pendingTasks); + return Either.left(pendingTasks); + } + + private boolean isComponentDeleted(Vertex componentVertex) { + VertexProperty<Object> property = componentVertex.property(GraphPropertiesDictionary.IS_DELETED.getProperty()); + if (property.isPresent()) { + return BooleanUtils.isTrue((Boolean) property.value()); + } + return false; + } + + private void logPendingTasks(User user, List<Edge> pendingTasks) { + if (log.isDebugEnabled()) { + for (Edge edge : pendingTasks) { + Object resourceUuid = edge.inVertex().property(GraphPropertyEnum.UNIQUE_ID.getProperty()).value(); + Object componentName = edge.inVertex().property(GraphPropertyEnum.NAME.getProperty()).value(); + Object componentState = edge.inVertex().property(GraphPropertyEnum.STATE.getProperty()).value(); + log.debug("The user userId = {} is working on the component name = {} uid = {} in state {}", user.getUserId(), componentName, resourceUuid, componentState); + } + } + } + + @Override + public Either<List<User>, ActionStatus> getAllUsersWithRole(String role, String status) { + try { + Map<String, Object> propertiesToMatch = new HashMap<>(); + if (role != null && !role.trim().isEmpty()) { + propertiesToMatch.put(GraphPropertiesDictionary.ROLE.getProperty(), role); + } + if (status != null && !status.isEmpty()) { + propertiesToMatch.put(GraphPropertiesDictionary.USER_STATUS.getProperty(), status); + } + + Either<List<UserData>, TitanOperationStatus> userNodes = titanGenericDao.getByCriteria(NodeTypeEnum.User, propertiesToMatch, UserData.class); + + titanGenericDao.commit(); + return convertToUsers(role, userNodes); + } finally { + titanGenericDao.commit(); + } + } + + private Either<List<User>, ActionStatus> convertToUsers(String role, Either<List<UserData>, TitanOperationStatus> userNodes) { + + if (userNodes.isRight()) { // in case of NOT_FOUND from Titan return empty list - if (userNodes.right().value().equals(TitanOperationStatus.NOT_FOUND)) { + TitanOperationStatus tos = userNodes.right().value(); + if (tos.equals(TitanOperationStatus.NOT_FOUND)) { return Either.left(Collections.emptyList()); } else { - log.error("Problem while getting all users with role {}. Reason - {}", role, userNodes.right().value().name()); + log.error("Problem while getting all users with role {}. Reason - {}", role, tos); return Either.right(ActionStatus.GENERAL_ERROR); } } else { - List<UserData> userDataList = userNodes.left().value(); + List<UserData> userDataList = userNodes.left().value(); if (userDataList != null) { return Either.left(convertToUsers(userDataList)); } log.debug("No users were found with role {}", role); return Either.left(Collections.emptyList()); } - } - - private List<User> convertToUsers(List<UserData> usersData) { - List<User> result = new ArrayList<>(); - for (UserData userData : usersData) { - User user = convertToUser(userData); - result.add(user); - } - return result; - } - - private Either<User, ActionStatus> getUserNotFoundError(String uid, TitanOperationStatus status) { - if (status == TitanOperationStatus.NOT_FOUND) { + } + + private List<User> convertToUsers(List<UserData> usersData) { + List<User> result = new ArrayList<>(); + for (UserData userData : usersData) { + User user = convertToUser(userData); + result.add(user); + } + return result; + } + + private Either<User, ActionStatus> getUserNotFoundError(String uid, TitanOperationStatus status) { + if (status == TitanOperationStatus.NOT_FOUND) { log.debug("User with userId {} not found", uid); return Either.right(ActionStatus.USER_NOT_FOUND); } else { - log.debug("Problem get User with userId {}. Reason - {}", uid, status.name()); + log.debug("Problem get User with userId {}. Reason - {}", uid, status); return Either.right(ActionStatus.GENERAL_ERROR); } - } - - protected User convertToUser(UserData userData) { - User user = new User(); - user.setUserId(userData.getUserId()); - user.setEmail(userData.getEmail()); - user.setFirstName(userData.getFirstName()); - user.setLastName(userData.getLastName()); - user.setRole(userData.getRole()); - user.setLastLoginTime(userData.getLastLoginTime()); - // Support backward compatibility - user status may not exist in old - // users - Either<UserStatusEnum, MethodActivationStatusEnum> either = UserStatusEnum.findByName(userData.getStatus()); - user.setStatus(either.isLeft() ? either.left().value() : UserStatusEnum.ACTIVE); - return user; - } - - protected UserData convertToUserData(User user) { - UserData userData = new UserData(); - userData.setUserId(user.getUserId().toLowerCase()); - userData.setEmail(user.getEmail()); - userData.setFirstName(user.getFirstName()); - userData.setLastName(user.getLastName()); - userData.setRole(user.getRole()); - userData.setStatus(user.getStatus().name()); - userData.setLastLoginTime(user.getLastLoginTime()); - return userData; - } + } + + protected User convertToUser(UserData userData) { + User user = new User(); + user.setUserId(userData.getUserId()); + user.setEmail(userData.getEmail()); + user.setFirstName(userData.getFirstName()); + user.setLastName(userData.getLastName()); + user.setRole(userData.getRole()); + user.setLastLoginTime(userData.getLastLoginTime()); + // Support backward compatibility - user status may not exist in old + // users + Either<UserStatusEnum, MethodActivationStatusEnum> either = UserStatusEnum.findByName(userData.getStatus()); + user.setStatus(either.isLeft() ? either.left().value() : UserStatusEnum.ACTIVE); + return user; + } + + protected UserData convertToUserData(User user) { + UserData userData = new UserData(); + userData.setUserId(user.getUserId().toLowerCase()); + userData.setEmail(user.getEmail()); + userData.setFirstName(user.getFirstName()); + userData.setLastName(user.getLastName()); + userData.setRole(user.getRole()); + userData.setStatus(user.getStatus().name()); + userData.setLastLoginTime(user.getLastLoginTime()); + return userData; + } } |